Require pattern or password when user attempts to shutdown device from lock

Hey guys is there a way to intercept shut down to make the user enter password if the state is in the locked state? Its just that I am engineering an anti-theft app and would to disable shut down from lock screen while the device is in the locked state. Is there a way of achieving this with Android Java. I tried listening on the shut down intent but the device does not even give the code in the OnRecieve to execute

How to implement Infocards using interfaces in dotnet?

Hello guys am trying to implement Info Cards using the IInfoCard and IInfoCardFactory and IInfocards interfaces. If you know how to complete the methods of these interfaces to make a program show the forms for the respective categories, then you might just be the guy to help me. I have the interface code as below.

using System;
using System.Windows.Forms;

public interface IInfoCard
{
    string Name { get; set; }
    string Category { get; }
    string GetDataAsString();
    void DisplayData(Panel displayPanel);
    void CloseDisplay();
    bool EditData();
}

and then the interface for IInfoCardFactory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public interface IInfoCardFactory
{
    IInfoCard CreateNewInfoCard(string category);
    IInfoCard CreateInfoCard(string initialDetails);
    string[] CategoriesSupported { get; }
    string GetDescription(string category);
}

How do I complete the methods in the class below to make them create the needed info cards and save data to a file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Assignment
{
    internal class CreditCardInfo : IInfoCardFactory,IInfoCard
    {
        private string[] categories = new string[] { "Credit Card" };
        private string name;

        public string[] CategoriesSupported
        {
            get { return categories; }
            set { categories = value; } 

        }

        public string Name { get
            {
                return this.name;   
            } 
            set { this.name = value; }  
        }

        public string Category
        {
            get
            {
                return this.Name;   
            }
            set
            {
                this.Name = value;
            }
        }

        public void CloseDisplay()
        {

            return;
        }

        public IInfoCard CreateInfoCard(string initialDetails)
        {
            string[] stringToSplit = initialDetails.Split(new char[] { '|' });
            string category = stringToSplit[0];
            string description = stringToSplit[1];
            CreditCardInfo info = new CreditCardInfo();
            info.CategoriesSupported=categories;
            return  info;
        }

        public IInfoCard CreateNewInfoCard(string category)
        {
            CreditCardInfo info= new CreditCardInfo();
            info.Category = category;
            return info;
        }

        public void DisplayData(Panel displayPanel)
        {
            //get the string[] categories and display
            string text = this.GetDataAsString();
            string[] info=text.Split(new char[] { '|' });   
            CreditCardDetails form=new CreditCardDetails();
            for(int i=0;i<form.Controls.Count;i++)
            {
                if (form.Controls[i].Name == "label7")
                {
                    form.Controls[i].Text = info[0];
                }
            }
            form.Show();    

        }
        public bool EditData()
        {
            new CreditCardForm().ShowDialog();
            return true;
        }

        public string GetDataAsString()
        {
            string data = this.Name;
            if(categories.Length > 0)
            {
                data+=categories[0].ToString();
            }
            return data;
        }

        public string GetDescription(string category)
        {
            if (category == "Credit Card")
                return "Save personal info about your credit card";
            else
                return "";


        }
    }
}

How to add firebase database to Xamarin android app

Hey guys, I am trying to upload text entered by a user of my app in an edit text to a google firebase application. Tried to find some reference online on how to do this, the article suggested I add Firebase.FirebaseDatabae.net which I added to the project via the Nuget package manager. I logged into my Google Firebase Console and got the Firebase url string for use with the client. I instantiated the client like below

protected string firebase_link = "https://xxxxxx-default-rtdb.firebaseio.com/";
FirebaseClient myclient;

//create a new instance of the firebase client
protected override void OnCreate(Bundle savedInstanceState){
 myclient = new FirebaseClient(firebase_link);
//define the buton for uploading the details in the edit text to the server
Button upload = FindViewById<Button>(Resource.Id.upload);
//subscribe to the event listener
upload.Click+=Upload_Click;
}
//method to upload text to the firebase app
private void Upload_Click(object sender, EventArgs e){
               try {
                if(myclient.Child("Users").PostAsync("Timothy").IsCompleted){
                    Snackbar.Make(email, "Firebase call completed succesfully", Snackbar.LengthLong).Show();
                }
                else
                {
                    Snackbar.Make(email, "An exception ocurred, try again in a little bit", Snackbar.LengthLong).Show();
                }
            }
            catch (Exception j)
            {
                Toast.MakeText(this,j.Message, ToastLength.Long).Show();    
            }
}

When I run the app, it is not making changes to the firebase database online, neither is it throwing an exception, it is just returning false for the if conditional structure inside the try catch block, please help.

Why my form does not pass parameters to my controller?

Hey guys am trying to pass values entered by a user in a form to an ASP.NET controller for processing to a database context. I do not know why the values in the form are not being passed to the controller method with the same parameter names, because when I tr to submit the form, it does nothing. Please help me do this correctly to pass entries from the form to the controller.
Below is mycontroller code

using Cars.Models;
using Microsoft.AspNetCore.Mvc;


namespace Cars.Controllers
{
    public class CarController:Controller
    {
        //declare the reference to database
        CarsContext _context ;
        public CarController()
        {
            _context = new CarsContext();
        }
        [HttpPost]
        //this method is supposed to receive the form values
        //and insert into the database
        public void GetProperties(string make,string model, string year,string nop)
        {
            //create a new car object
            Car car = new Car()
            {
                Make = make,
                Model = model,
                Year = Int32.Parse(year),
                NoPassengers = Int32.Parse(nop)

            };
            //create a new database context

            _context.Add(car);
            //save changes
            _context.SaveChanges();



        }
        //method to get all the cars
        public List<Car> GetAllCars()
        {

            //create a new database context
            return _context.Car.ToList();
        }
        //method to get a car by id
        public Car? GetById(int? id)
        {
            return _context.Car.FirstOrDefault(c => c.Id == id);
        }
       //method to check if a car exists
        public bool Exists(Car obj)
        {
            return _context.Car.Where(c => c.Id == obj.Id).Any();
        }
        //return cars whose passenger seats is three or less
        public List<Car> ThreePassengers()
        {
            return _context.Car.Where(c=>c.NoPassengers<=3).ToList();  
        }
    }
}

below is my index.cshtml form with the values I need passed to the controller via parameters

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Car Property Editor</h1>
   <p>Fill out the details of the car in the form below </p>
   <br/>
   <br/>
   @using (Html.BeginForm("ReceiveWithRequestFormData", "CarController"))
   {
   <table class="table">
     <thead>
         <tr>
             <td>Make</td>
             <td>Model</td>
             <td>Year Manufactured</td>
             <td>Number of Passengers</td>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>@Html.TextBox("make")</td>
               <td>@Html.TextBox("model")</td>
                 <td>@Html.TextBox("year")</td>
                   <td>@Html.TextBox("nop")</td>

         </tr>
     </tbody>
     <br/>

   </table>
    <center><input class="btn" type="submit" value="Insert"asp-action="myfunction()" style="background:blue;color:#111"></center>
   }
   <button class="btn">Get All Cars</button>
   <button class="btn">Get Car  by Id</button>
   <button class="btn">Get Car with three passenger seats</button>
   <button class="btn">Sort Cars by year manufactured</button>
</div>

Please help me hook the values in the form to the controller, Thank you.

Why my ASP controller is returning a null Model

Good morning everyone, I have an MVC projet in ASP.NET and I got a little problem with the project, when I run the main program.cs script it breaks and says that the Model is null. I have followed every required step when implementing an entity relationship framework in ASP.NET. I suspect my problem is in the AlienController.cs file. Here is how am building the app

namespace L06HandsOn.Models
{
   //alien model
    public class Alien
    {

        public int? arms {get;set;}
        public int? legs { get; set; }
        public int? heads { get; set; } 
        public DateTime? BirthDate { get; set; }
        public Planet PlanetOrigin { get; set; }    

    }
    public enum Planet
    {
        Mercury,Venus, Earth, WhatOnceWas,Jupiter,Saturn,Uranus,Neptune,TheUnappreciatedPluto
    }
}

and below is my datacontext file

using Microsoft.EntityFrameworkCore;

namespace L06HandsOn.Models
{
    public class AliensContext:DbContext
    {
        public AliensContext(DbContextOptions<AliensContext> options) : base(options)
        {

        }
        public DbSet<Alien> Aliens { get; set; }
    }
}

and below is my aliencontroller.cs file

using L06HandsOn.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace L06HandsOn.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class AlienController:Controller
    {
        private readonly AliensContext _context;

        //require the parameter on constructor 
        public AlienController(AliensContext cont)
        {
            _context =cont; 
        }
        [HttpGet]
        //get the aliens
        public async Task<IActionResult> Index()
        {
            return View(await _context.Aliens.ToListAsync());
        }
        [HttpGet]
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var alien=await _context.Aliens.SingleOrDefaultAsync(); 
            if(alien== null)
            {
                return NotFound();
            }
            return View(alien);
        }
    }
}

and finally here is how am registering the database context in the main of the program

using L06HandsOn.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var connectionString = "Data Source=AliensEntityFramework.db";
builder.Services.AddDbContext<AliensContext>(optionsAction=>optionsAction.UseSqlite(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Why is my ASP.NET app returning a null for the Model please help

SQLite query to return records earlier than a certain year?

I am trying to come up with an SQL query to return all the records earlier than a certain year with SQLite using DB Browser. I can't seem to come up with the right regex expressipn to use for filtering only the year from a row for comparison, below is the query am using. It is returning 0 records please help.

SELECT * FROM EMPLOYEES WHERE strftime('%Y', HireDate)<2003;

I am trying to get all records where the HireDate which is a column is earler than 2003, please help.

Why is my ASP route returning no data

Helllo guys am trying to build my first ASP.NET application here and I have a Models folder and Controllers folder. The models folder contains the class for an entity called customer whose properties are to be read from sqlite database. Thee is also a Pages folder that contains a folder called Shared that contains files such as index.cshtml. When I launch the project, a web browser opens up with the later file opened. The controllers folder contains files such as DataBaseController with the code to query the database and return a response in the specified url. I am trying to access the DataBaseController file directly from the url section like localhost:5001/api/databases but it is returning 404 Not Found. Please help me access the controller file route rom the browser. Below is the DatabaseController.cs file. How do I get the url to show the results of the controller below thank you.

using Databases.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;

namespace SqliteFromScratch.Controllers
{
    // MVC is handling the routing for you.
    [Route("api/[Controller]")]
    public class DatabaseController:Controller
    {
        [HttpGet]
        //change the return type to return the 
        //customer lists from the database
        public List<Customer> GetData()
        {
            //initialize the list
            List<Customer> data = new List<Customer>();
            //perform a query using the connection for the database file
            string dataSource = "Data Source=" + Path.GetFullPath("chinook.db");
            using (SqliteConnection conn = new SqliteConnection(dataSource))
            {

                conn.Open();

                // sql is the string that will be run as an sql command
                string sql = $"select * from customers limit 200;";
                using (SqliteCommand command = new SqliteCommand(sql, conn))
                {

                    // reader allows you to read each value that comes back and do something to it.
                    using (SqliteDataReader reader = command.ExecuteReader())
                    {

                        // Read returns true while there are more rows to advance to. then false when done.
                        while (reader.Read())
                        {

                            // map the data to the model.
                            // add each one to the list.
                            Customer customer = new Customer()
                            {
                                Id = reader.GetInt32(0),
                                FirstName=reader.GetString(1),
                                LastName=reader.GetString(2),
                                Company=reader.GetString(3),
                                Address=reader.GetString(4),
                                City=reader.GetString(5),
                                State=reader.GetString(6),
                                Country=reader.GetString(7),
                                PostalCode=reader.GetString(8),
                                Phone=reader.GetString(9),  
                                Fax=reader.GetString(10),
                                Email=reader.GetString(11), 
                                SupportRep=reader.GetInt32(12),
                            };
                            //add each one to the list
                            data.Add(customer);
                        }
                    }
                }
                conn.Close();

            }
            return data;
        }
    }
}

How to access bluetooth adapter on windows with C#

Hello guys, am trying to access the windows in-built adapter from C# library known as Bluetooth LE (Low Energy). I have installed the nuget package and when I try to run my code, I get the error that
Unhandled exception. System.ArgumentException: [Plugin.BluetoothLE] No platform plugin found. Did you install the nuget package in your app project as well?. I have tried looking online to see if there is a GATTServer instance that needs to be started but did not succeed. Please help me access the adapter correctly without this exception being thrown. Here is the C# code am trying to use

public class BTClient
    {
        //define the adapter
        static IAdapter adapter;
        //declare  variable to hold the UUID of a device
        string UUID;
        public BTClient()
        {
            //assign the adapter on constructor exit
            //this adapter allows usage across various platforms
            adapter = CrossBleAdapter.Current;
        }
        /// <summary>
        /// the method below is for discovering bluetooth devices
        /// nearby
        /// </summary>
        /// <returns></returns>
      [DllExport("devices", CallingConvention = CallingConvention.Cdecl),ComVisible(true)]
        public static List<Plugin.BluetoothLE.IDevice> DiscoverDevices()
        {
            IGattServer server = (IGattServer)CrossBleAdapter.Current.CreateGattServer();
            server.CreateService(new Guid(), true);
             var devices = new List<Plugin.BluetoothLE.IDevice>();
            var scanner = CrossBleAdapter.Current.Scan().Subscribe(scanResult =>
             {
                 devices.Add(scanResult.Device);
             });
            return devices;
        }
}

class Solution{
   static void Main(){
            List<IDevice> devices = new List<IDevice>();
            devices = BTClient.DiscoverDevices();
            foreach(var device in devices){
             Console.WriteLine(device.Name);
            }
   }


}

Traverse binary tree with recursion and number of nodes

Is there a way to print out numbers for pre-order, post-order and in-order traversals of trees using just recursion and a number. The trees are binary and n is the number of nodes from the parent to al children. Can anyone help me write the function to print the numbers in their orderly fashion in any programming language?

Face Detection using PCA in C#

Am trying to implement face detection using the PCA algorithm in C#,I have a button on my windows forms that is supposed to intitiate the learning process once it is clicked. It should use the images in a folder called training to compute the eigen values and eigen vectors so that it would be able to identify a similar image from the test folder. I have loaded all the 200 images in the training folder into an array list and now my problem is converting this collection of images to a one dimension vector so that i can be able to compute the co-variance matrix and eigen values for it. My code is listed below, if there is any way my code can be improved then your corrections are welcome

namespace PCA
{
    public partial class Form1 : Form
    {
        //the mapack library has been used to create new instances of the matrices
        //hold the width and height of an image in a variable
        static int height = 112;
        static int width = 92;
        //store the number of train images in a variable
        static int train_images = 200;
        //store the number of eigen values to keep in a variable
        static int eigen_values = 50;
        //initialize the matrix data
        PCALib.Matrix matrix_data = new PCALib.Matrix(train_images, width * height);
        //initialize the Target matrix data
        PCALib.Matrix T = new PCALib.Matrix(train_images,eigen_values);
        //initialize the mean of the images
        int image_mean = 0;
        //initialize the image array 
        List<Image> training = new List<Image>();
        //the path to the images
        static string path = "C:/Users/TimothyFarCry5/Documents/visual studio 2015/Projects/PCA/PCA/training";
        public Form1()
        {
            InitializeComponent();
        }
        //the method below starts the training process
        private void button1_Click(object sender, EventArgs e)
        {
            /*read all the images in the training folder into an array
            in this case the images are already in gray scale so we do not need to convert
            */
            var files = Directory.GetFiles(path);
            foreach(string r in files)
            {
                if(Regex.IsMatch(r, @"\.jpg$|\.png$|\.gif$"))
                {
                    training.Add(Image.FromFile(r));
                }
            }
            //convert the list of images to a one dimension vector

Remove non letters characters from a string but leave alone the spaces(C#)

Am working on a decipher algorithm that is supposed to take a string input of en english sentence flipped backwards and contains numbers, spaces and delimiters.
I got code that removes numbers and special characters but also removes spaces, Can you help me tell this code to not bully the spaces and just leave them in my string, Thank You.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{
    static List<string> mywords=new List<string>();
    public static void Main()
    {
        string inp=Console.ReadLine();
        string answer=Regex.Replace(inp,"[^a-zA-Z]", "");
        string replacement=reverse(answer);
        Console.WriteLine(replacement);
    }
    private static string reverse(string b){
     string reverse="";int Length=0;
          Length = b.Length - 1;  
            while(Length>=0)  
            {  
                reverse = reverse + b[Length];  
                Length--;  
            }  
        return reverse;
    }
}

parse string for integers and add to an integer array

i have a script in clojure that can read a string of integers separated by commas from a file..the scrip is succesful and reads the line from the file as astring,all i want is some clojure loop to scan the string for integers and add to an integer array
here is the code

(ns Files.myfile)
(defn hello-world []
  (println "Hello World"))
 (hello-world)
(def s (slurp "integers.txt"))
  (println s)
(s)

##integers.txt contains random integers separated by commas

list all the elements that pecede a certain element in python array

I have an array in python that has letters as strings and a comma as a string also. I have managed to find code that finds all the letters that come before that comma letter, there are other comma letters and i would like to iterate to list every letter that comes before the commas in the array here is what i got so far

##THE ARRAY IS THIS ONE
myarray=['G', 'o', 'T', ',', 'I', 't', 'B', ',', 'M', 'N', 'R', ',', 'K', 'F', 'P', ',', 'M', 'F', 'I', 'H', ',', 'A', 'H', ',']
temp = myarray.index(",")
res = myarray[:temp]
print(res)

##tHE CODE ABOVE outputs ['G','o','T'], is there a way in which i can iterate through all elements in 
the array listing every letter that comes before the commas