text:
Q: Tailwind sidebar issues I'm new to tailwind, I tried making a sidebar and the main bar, the sidebar should be on the left while the main bar should be on the right but the sidebar is pushing the main bar content to the bottom.

<!DOCTYPE html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>{{ config('app.name', 'Laravel') }}</title>

        <link rel="stylesheet" href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap">

        @vite(['resources/css/app.css', 'resources/js/app.js'])

                Flowtrail UI
                <button class="rounded-lg md:hidden focus:outline-none focus:shadow-outline" @click="open = !open">
                    <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
                        <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
                        <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                    </svg>
                </button>

                    Blog
                    Portfolio
                    About
                    Contact

                        <button @click="open = !open" class="flex flex-row items-center w-full px-4 py-2 mt-2 text-sm font-semibold text-left bg-transparent rounded-lg dark-mode:bg-transparent dark-mode:focus:text-white dark-mode:hover:text-white dark-mode:focus:bg-gray-600 dark-mode:hover:bg-gray-600 md:block hover:text-gray-900 focus:text-gray-900 hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline">
                            Dropdown
                            <svg fill="currentColor" viewBox="0 0 20 20" :class="{'rotate-180': open, 'rotate-0': !open}" class="inline w-4 h-4 mt-1 ml-1 transition-transform duration-200 transform md:-mt-1"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
                        </button>

                                Link #1

                {{ $slot }}

A: Make sure the width of the first div inside the parent div is not full and add md:justify-between in the parent div like this:

Your logged in

A: Maybe you have the main, outside the tag

        Flowtrail UI
        <button class="rounded-lg md:hidden rounded-lg focus:outline-none focus:shadow-outline" @click="open = !open">
          <svg fill="currentColor" viewBox="0 0 20 20" class="w-6 h-6">
            <path x-show="!open" fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM9 15a1 1 0 011-1h6a1 1 0 110 2h-6a1 1 0 01-1-1z" clip-rule="evenodd"></path>
            <path x-show="open" fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
          </svg>
        </button>

        Categorias
        Menu
        Mesas
        Reservacion

          <button @click="open = !open" class="flex flex-row items-center w-full px-4 py-2 mt-2 text-sm font-semibold text-left bg-transparent rounded-lg dark-mode:bg-transparent dark-mode:focus:text-white dark-mode:hover:text-white dark-mode:focus:bg-gray-600 dark-mode:hover:bg-gray-600 md:block hover:text-gray-900 focus:text-gray-900 hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline">
            {{ Auth::user()->name }}
            <svg fill="currentColor" viewBox="0 0 20 20" :class="{'rotate-180': open, 'rotate-0': !open}" class="inline w-4 h-4 mt-1 ml-1 transition-transform duration-200 transform md:-mt-1"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
          </button>

              Link #1

               <form method="POST" action="{{ route('logout') }}">
                @csrf

                <x-dropdown-link :href="route('logout')"
                        onclick="event.preventDefault();
                                    this.closest('form').submit();">
                    {{ __('Log Out') }}
                </x-dropdown-link>
            </form>

      {{ $slot }}


text:
Q: Merge data table into dataset and save changes back to data source First c# project and I need to pull records off a remote SQL Server into a localDB instance. Reading so many docs I'm about brain dead. Source is a npsql datasource. Target is localdb instance I built the local table with the same schema. I don't think SqlBulkCopy is the right solution here so I'm trying to bring over changes and adds. While I get no errors in the code the localdb instance is not updated.
DataTable custMsrDT = this.MeasureDB.getMsrCustomerDT();

using (SqlConnection connection = new SqlConnection(LocalDB.connStringLocalDB))
{
    connection.Open();

    SqlDataAdapter da = new SqlDataAdapter("SELECT id, crm_customer_id, jb_customer_id, fname, lname, phone, alt_phone, email, street_address, unit_number, neighborhood, city, state, zip, county FROM dbo.customer;", connection);

    DataSet localDS = new DataSet();

    da.Fill(localDS, "customer");
    SqlCommandBuilder builder = new SqlCommandBuilder(da);

    localDS.Tables["customer"].RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed);

    localDS.Tables["customer"].Merge(custMsrDT, true, MissingSchemaAction.Add);

    da.Update(localDS, "customer");
}

A: figured it out.  using the table.merge function was not the answer.  it comes down to understanding how the row state is set.  in the original the rowstate was always "unchanged" thus the datatable.update was not doing anything.  using the load function on the table was the correct approach.
    DataTable custMsrDT = this.MeasureDB.getMsrCustomerDT();

    using (SqlConnection connection = new SqlConnection(LocalDB.connStringLocalDB))
    {
        connection.Open();

        SqlDataAdapter da = new SqlDataAdapter("SELECT id, crm_customer_id, jb_customer_id, fname, lname, phone, alt_phone, email, street_address, unit_number, neighborhood, city, state, zip, county FROM dbo.customer;", connection);

        DataSet localDS = new DataSet();

        da.Fill(localDS, "customer");

        SqlCommandBuilder builder = new SqlCommandBuilder(da);

        localDS.Tables["customer"].RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed);

        //localDS.Tables["customer"].Merge(custMsrDT, true, MissingSchemaAction.Add);

        using (DataTableReader changeReader = new DataTableReader(custMsrDT))
        {

            localDS.Tables["customer"].Load(changeReader, LoadOption.Upsert);

        }

        PrintColumns(localDS.Tables["customer"]);

        DisplayRowState(localDS.Tables["customer"]);

        da.Update(localDS, "customer")

redpajama_set_name: RedPajamaStackExchange


text:
Q: When to include a library in target_link_libraries Suppose I have an executable Alpha, which must link with a shared library Beta. Beta itself is dependent on shared library Gamma. Gamma already exists for me, but I must compile Alpha and Beta myself, using cmake.
So, with the two CMakeLists.txt files, one for each of Alpha and Beta, I use the command target_link_libraries to indicate which libraries are needed for compilation. My question is: which of these two CMakeLists.txt files do I need to add Gamma?
Beta directly depends on Gamma, because code in Beta calls functions in Gamma. However, Alpha indirectly depends on Gamma too, so do I need to tell Alpha's CMakeLists.txt file about this?

A: If CMake knows about the Beta->Gamma dependency, it should be able to make everything work.  If there were a case where you built Beta without telling CMake about its dependency on Gamma (which is possible to do), you would then have to express the Alpha->Gamma dependency explicitly.


text:
Q: HTML Table Formatting Aligning Image in Column 1 With Text in Column 2 I am working on updating a table in a Pardot email template. I am trying to align an image in column 1 with the first line of text in column 2. Meaning, for this master template, when users go in the first line text will remain in alignment with the image and additional lines of text can be added below in column 2- currently when lines are added the first line of text is bumped up higher in the cell and is no longer in alignment with the image in column 1.

   Title

   Content

   Title

   Content

   Title

   Content

A: i think i have a understanding of what you are trying to say, so in order to place text below, there are currently two ways that i see it. either place the text in div tag such as

    Test Test Title content

Test im placing text below

or another method of placing text below is by using a paragraph tag such as

    Test Test Title content

 test i have more text below

However it looks like the that the Div tag will be more suited to you as i feel like you will be using this code in the navigation bar


text:
Q: How to uniformly sample a big graph? I have a big graph which has around 4M nodes. The graph consists of two files, one containing the node names and one containing edges (each line represents one edge). I want to uniformly sample the graph nodes and come up with a sample as big as 15% of the whole graph. Considering the size of the graph, what is the best (or maybe possible) way to generate such a sample?

A: Use this java code to select 15% of the vertices randomly:
import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class RandomSample {

 public static class Map extends Mapper<LongWritable, Text, Text, Text> {
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException {
        if (Math.random()<0.15)
            context.write(value,null);
        else
            context.write(null,null);
    context.write(value,null);
    }
 }

 public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();

    Job job = new Job(conf, "randomsample");
    job.setJarByClass(RandomSample.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setInputFormatClass(TextInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);

    job.setNumReduceTasks(0);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));

    job.waitForCompletion(true);
 }

}

And use this bash script to run it
echo "Running Job"
hadoop jar RandomSample.jar RandomSample $1 tmp
echo "copying result to local path (RandomSample)"
hadoop fs -getmerge tmp RandomSample
echo "Clean up"
hadoop fs -rmr tmp

For example, if we name the script random_sample.sh, to select 15% from folder /example/, simply run
./random_sample.sh /example/

Then, you can use simple grep operation on the second file to select only edges that contains the randomly chosen vertices


text:
Q: Wait until all dependencies are loaded in controller - resolve without $routeProvider AngularJS provides with the RouteProvider https://docs.angularjs.org/api/ngRoute/provider/$routeProvider the resolve property. If any of these dependencies are promises, the router will wait for them until all to them are resolved.
But how can I solve this issue when the controller is not mentioned in the route because I'm using something like ng-include or

Any hints are welcome.


text:
Q: Group Elements Under another element with jquery I have a list of 100 links of referrers. They are from different cities and I need to group the ones from same city. since my output is created by a CMS it's not static.
imagine a list of 100 different
Name

I'm planning to add a rel, class or id to specify their cities
Name

I need to group the links from same city and put them in some div
City1
 - link1
 - link2
 - link3
 - link4

City2
 - link1
 - link2
 - link3

some cities have over 20 links some have only 1.

A: I did not understand exactly your issue, but you can make an array with your links and  check how to sort or map an array with jquery.


text:
Q: Azure ML model to a container instance, call to the model fails when using the code provided in the "Consume" section of the endpoint (Python and C#) After deploying an Azure ML model to a container instance, call to the model fails when using the code provided in the "Consume" section of the endpoint (Python and C#).
I have trained a model in Azure Auto-ML and deployed the model to a container instance.
Now when I am try to use the Python code provided in the Endpoint's "Consume" section I get the following error:
The request failed with status code: 502
Content-Length: 55
Content-Type: text/html; charset=utf-8
Date: Mon, 07 Mar 2022 12:32:07 GMT
Server: nginx/1.14.0 (Ubuntu)
X-Ms-Request-Id: 768c2eb5-10f3-4e8a-9412-3fcfc0f6d648
X-Ms-Run-Function-Failed: True
Connection: close

---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-1-6eeff158e915> in <module>
48 # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
49 print(error.info())
---> 50 print(json.loads(error.read().decode("utf8", 'ignore')))

/anaconda/envs/azureml_py36/lib/python3.6/json/init.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder

/anaconda/envs/azureml_py36/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):

/anaconda/envs/azureml_py36/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

If I use C# code provided in the Endpoint's "Consume" section I get the following error:
The request failed with status code: BadGateway
Connection: keep-alive
X-Ms-Request-Id: 5c3543cf-29ac-46a3-a9fb-dcb6a0041b08
X-Ms-Run-Function-Failed: True
Date: Mon, 07 Mar 2022 12:38:32 GMT
Server: nginx/1.14.0 (Ubuntu)

'<=' not supported between instances of 'str' and 'int'

The Python code I am using:
 import urllib.request
 import json
 import os
 import ssl

 def allowSelfSignedHttps(allowed):
     # bypass the server certificate verification on client side
     if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
         ssl._create_default_https_context = ssl._create_unverified_context

 allowSelfSignedHttps(True) # this line is needed if you use self-signed certificate in your scoring service.

 data = {
     "Inputs": {
         "data":
         [
             {
                 "SaleDate": "2022-02-08T00:00:00.000Z",
                 "OfferingGroupId": "0",
                 "week_of_year": "7",
                 "month_of_year": "2",
                 "day_of_week": "1"
             },
         ]
     },
     "GlobalParameters": {
         "quantiles": "0.025,0.975"
     }
 }

 body = str.encode(json.dumps(data))

 url = 'http://4a0427c2-30d4-477e-85f5-dfdfdfdfdsfdff623f.uksouth.azurecontainer.io/score'
 api_key = '' # Replace this with the API key for the web service
 headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

 req = urllib.request.Request(url, body, headers)

 try:
     response = urllib.request.urlopen(req)

     result = response.read()
     print(result)
 except urllib.error.HTTPError as error:
     print("The request failed with status code: " + str(error.code))

     # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
     print(error.info())
     print(json.loads(error.read().decode("utf8", 'ignore')))

The C# code I have tried:
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Net.Http;
 using System.Net.Http.Headers;
 using System.Text;
 using System.Threading.Tasks;
 using Newtonsoft.Json;

 namespace MLModelAPICall
 {
     class Program
     {
         static void Main(string[] args)
         {
             InvokeRequestResponseService().Wait();
         }

         static async Task InvokeRequestResponseService()
         {
             var handler = new HttpClientHandler()
             {
                 ClientCertificateOptions = ClientCertificateOption.Manual,
                 ServerCertificateCustomValidationCallback =
                         (httpRequestMessage, cert, cetChain, policyErrors) => { return true; }
             };
             using (var client = new HttpClient(handler))
             {
                 // Request data goes here
                 var scoreRequest = new
                 {
                     Inputs = new Dictionary<string, List<Dictionary<string, string>>>()
                     {
                         {
                             "data",
                             new List<Dictionary<string, string>>()
                             {
                                 new Dictionary<string, string>()
                                 {
                                     {
                                         "SaleDate", "2022-02-08T00:00:00.000Z"
                                     },
                                     {
                                         "OfferingGroupId", "0"
                                     },
                                     {
                                         "week_of_year", "7"
                                     },
                                     {
                                         "month_of_year", "2"
                                     },
                                     {
                                         "day_of_week", "1"
                                     }
                                 }
                             }
                         }
                     },
                     GlobalParameters = new Dictionary<string, string>()
                     {
                         {
                             "quantiles", "0.025,0.975"
                         }
                     }
                 };

                 const string apiKey = ""; // Replace this with the API key for the web service
                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                 client.BaseAddress = new Uri("http://4a0427c2-30d4-477e-85f5-xxxxxxxxxxxxx.uksouth.azurecontainer.io/score");

                 // WARNING: The 'await' statement below can result in a deadlock
                 // if you are calling this code from the UI thread of an ASP.Net application.
                 // One way to address this would be to call ConfigureAwait(false)
                 // so that the execution does not attempt to resume on the original context.
                 // For instance, replace code such as:
                 //      result = await DoSomeTask()
                 // with the following:
                 //      result = await DoSomeTask().ConfigureAwait(false)

                 var requestString = JsonConvert.SerializeObject(scoreRequest);
                 var content = new StringContent(requestString);

                 content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                 HttpResponseMessage response = await client.PostAsync("", content);

                 if (response.IsSuccessStatusCode)
                 {
                     string result = await response.Content.ReadAsStringAsync();
                     Console.WriteLine("Result: {0}", result);
                 }
                 else
                 {
                     Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                     // Print the headers - they include the requert ID and the timestamp,
                     // which are useful for debugging the failure
                     Console.WriteLine(response.Headers.ToString());

                     string responseContent = await response.Content.ReadAsStringAsync();
                     Console.WriteLine(responseContent);
                     Console.ReadLine();
                 }
             }
         }
     }
 }

Could you please help me with this issue? I am not sure what do to if Microsoft's provided code is erroring out, don't know what else to do.

A: After much more digging I found out that the "Consume" scripts provided with the endpoint are wrong (Python and C#) .
When making a call to the endpoint the GlobalParameters expects an integer value, but the provided scripts have wrapped the values in double quotes hence making it a string:
 },
 "GlobalParameters": {
     "quantiles": "0.025,0.975"
 }

If you are using Python to consume the model, when making call to the endpoint your GlobalParameters should be define as this:
 },
 "GlobalParameters": {
     "quantiles": [0.025,0.975]
 }

wrapped in square brackets

[0.025,0.975]

and not in double quotes "

I have also opened a ticket with microsoft so hopefully they will fix the code provided in the "consume" section of every endpoint


text:
Q: Laravel - Migration scripts used multple times across platforms I just had a thought of serving fresh data for a demo app.
What I want to achieve is to have the schema and a set of data prepared beforehand and got ready to be migrated as the demo app is run. Simply put, every time a user runs the app, the database will be dumped with fresh data.
Is that possible? In Laravel 4, I know when I generate a migration script through the CLI, it seems like it has a timestamps attached to the file name, I was wondering if that would prevent the migration from being executed in later days in the future?
Thanks everyone.

A:
What I want to achieve is to have the schema and a set of data prepared beforehand and got ready to be migrated as the demo app is run. Simply put, every time a user runs the app, the database will be dumped with fresh data.

Speaking of having a set of prepared data, I think Database Seeding is close to what you want.
The docs also mention how you could use the migration and seeding together. Although you'll need to decide how to do the migration + seed yourself. E.g. trigger by artisan command, trigger every page load, etc.
Rollback all migrations and run them all again (reference):

php artisan migrate:refresh
php artisan migrate:refresh --seed

You could also use packages like fzaninotto/Faker to help with generating a closer-to-real-life seed data for you.

In Laravel 4, I know when I generate a migration script through the CLI, it seems like it has a timestamps attached to the file name, I was wondering if that would prevent the migration from being executed in later days in the future?

The timestamp in the migration file name is only used for indicating the order in which the migration should be run. So you don't end up running migrations where you try to add a column before adding its table. As long as you do php artisan migrate:refresh and you have set up the up() and down() in your migration files correctly, it should not be a problem.
Although note that if you are in a team, be sure to check the migration order since two or more members can create migration files in parallel to each other.


text:
Q: Making an Object accessible in a controllers which was set in kernel.controller Event How can make an Object accessible in a controllers which was set in kernel.controller Event?
I have a onKernelController method which is run before controller and I need some data in a controller which was set in onKernelController.

A: You can use dependency injection to solve this:
1) Turn your object/class into a service and inject it into the listener.
services:
    your_object:
        class: Your\Namespace\YourObjectClass

    your_listener:
        class: Your\Namespace\YourListener
        arguments: [ @your_object ]
        tags:
            - { name: kernel.controller, event: kernel.request, method: onKernelController }

2) Set some property (can be an object aswell) on the injected object
listener class
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class YourListener
{
    protected $object;

    public function __construct($object)
    {
         $this->object = $object;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        // ...

        $object->setProperty('some_property_value');
    }
}

3.) Get the property inside a container-aware controller (or turn your controller into a service aswell and inject @your_object )
controller
use Symfony\Component\DependencyInjection\ContainerAware;
// or: use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SomeController extends ContainerAware // or: extends Controller
{

    public function someAction()
    {
        $property = $this->container->get('your_object')->getProperty;
        // $property => 'some_property_value'
    }


text:
Q: WPF ComboBox SelectedItem Ok been working with WPF for a while but I need some help.
I have a ComboBox like below:
<TabControl>
    <TabItem Header="1">
        <ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyListSelection}"/>
    </TabItem>
    <TabItem Header="2"/>
</TabControl>

Whenever I move away from tab 1 and then come back to it the selection gets removed. I think the reason for that is that the controls get destroyed when they go out of scope and then back in. But in the process of that the SelectedItem becomes null which isn't really what the user wanted, it's an event due to the UI lifecycle.
So I'm wondering what is the best route to take? I'm building this app with MVVM so I could ignore a set call on the MyListSelection Property in my ViewModel but I have ComboBoxes all over the place and don't like modifying my ViewModel for what I consider a bug of WPF.
I could subclass the WPF ComboBox, but there is no SelectedItemChanging event I can only add a handler when SelectedItem changed.
Any ideas?
UPDATE:
Okay, after beating my head against the wall I found out why my problem couldn't get reproduced. If the list item type is a class for some reason the SelectedItem gets set by WPF to null but if it's a value type it doesn't.
here's my test class(VMBase is just an abstract class that implements INotifyPropertyChanged):
public class TestListViewModel : VMBase
{
    public TestListViewModel()
    {
        TestList = new List<TestViewModel>();
        for (int i = 0; i < 10; i++)
        {
            TestList.Add(new TestViewModel(i.ToString()));
        }
    }

    public List<TestViewModel> TestList { get; set; }

    TestViewModel _SelectedTest;
    public TestViewModel SelectedTest
    {
        get { return _SelectedTest; }
        set
        {
            _SelectedTest = value;
            OnPropertyChanged("SelectedTest");
        }
    }
}

public class TestViewModel : VMBase
{
  public string Name {get;set;}
}

So when I change TestList to type int and go back and forth between tabs SelectedItem stays the same. But when it is of type TestViewModel SelectedTest gets set to null when the tabitem goes out of focus.
What's going on?

A: I've the exact same problem, and till now I couldn't figure what the problem is. I tested in 4 different machines with the same OS, .Net version and hardware specifications and could reproduce the issue in two of them, in the other ones worked just fine.
The workaround I could find that works for me is to define the SelectedItem binding before the ItemsSource. Strangely if I follow this pattern, everything works as expected.
That said, you just have to do the following:
<Window x:Class="ComboBoxInTabItemSpike.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <TabControl>
            <TabItem Header="1">
                <ComboBox SelectedItem="{Binding MySelect}" ItemsSource="{Binding MyList}"/>
            </TabItem>
            <TabItem Header="2"/>
        </TabControl>
        <TextBlock Text="{Binding MySelect}"/>
    </StackPanel>
</Window>

A: EDITED after change in OP.
Hi Jose, I am unable to reproduce the error you mention. So your assumption about the Control being destroyed is wrong. The Combobox behaves as expected with the code behind below even it is now using a reference type. Some other piece of your code must kick in when you change TabItems.
<Window x:Class="ComboBoxInTabItemSpike.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <TabControl>
            <TabItem Header="1">
                <ComboBox ItemsSource="{Binding MyList}"
                          SelectedItem="{Binding MySelect}"/>
            </TabItem>
            <TabItem Header="2"/>
        </TabControl>
        <TextBlock Text="{Binding MySelect}"/>
    </StackPanel>
</Window>

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace ComboBoxInTabItemSpike
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public Window1()
        {
            InitializeComponent();
            MyList=new ObservableCollection<TestObject>(
                new[]{new TestObject("1"),new TestObject("2"),new TestObject("3") });
            DataContext = this;
        }

        public ObservableCollection<TestObject> MyList { get; set; }

        private TestObject mySelect;
        public TestObject MySelect
        {
            get { return mySelect; }
            set{ mySelect = value;
            if(PropertyChanged!=null)
                PropertyChanged(this,new PropertyChangedEventArgs("MySelect"));}
        }

        public TestObject MySelectedItem
        {
            get { return (TestObject)GetValue(MySelectedItemProperty); }
            set { SetValue(MySelectedItemProperty, value); }
        }

        public static readonly DependencyProperty MySelectedItemProperty =
            DependencyProperty.Register("MySelectedItem",
                                typeof(TestObject),
                                typeof(Window1),
                                new UIPropertyMetadata(null));

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class TestObject
    {
        public string Name { get; set; }

        public TestObject(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}

A: I would recommend checking the bindings.  If anything else in your app is changing the selected item or the items source, then your binding will break.  You can also look in Visual Studio at the output window to see if there are any errors.

A: I think what you may be missing here is a TwoWay binding on the SelectedItem. When you bind your ViewModel class which contains the MyList(bound ItemsSource) and MyListSelection(Bond to SelectedItem in your Case) will always have those information even though you went to different tabs. So when you come back to this Tab the MyListSelection will bind back to the ComboBoc.SelectedItem again and you will be good. Try this and let me know.

A: I think this could be solved with a simple null check.
public TestViewModel SelectedTest
{
    get { return _SelectedTest; }
    set
    {
        if(value != null)
            _SelectedTest = value;
        OnPropertyChanged("SelectedTest");
    }
}

This is because ComboBox has a tendency to reset its SelectedIndex when recycled. This simple null check will force it to rebind to the last valid item.

A: I was having the exact same problem with a reference type in my list.  The solution was to override Equals() in my TestViewModel so that WPF would be able to do a value equality check (instead of a reference check) between the objects to determine which one is the SelectedItem.  Mine happened to have an ID field that was really the identifying feature of a TestViewModel.

A: This behavior by the combobox, should be implemented by the compiler in a better fashion than it is...  IE the compiler should check and see if the types for the ItemsSource and the type reference value of the property that the SelectedItem is bound to will EVER return the a value that is comparable
It should warn that you might consider overriding the Equals() and GetHashCode() methods...
Wasted a lot of time on this today !!


text:
Q: How to avoid Decimal values in input type number How to avoid Decimal values from input of Number in HTML5. Currently it allows user to type decimal value.

A: <input type="number" onkeydown="return event.keyCode !== 190">

This will Restrict period(.) input.For any Key restriction:
https://css-tricks.com/snippets/javascript/javascript-keycodes/

A: I ended up checking to see if a user types in a period then preventing the event from propagating.
Edit: A better approach. The key press event has been deprecated. Also added in a regex to strip out everything but numbers [0-9] on paste.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}"  oninput="event.target.value = event.target.value.replace(/[^0-9]*/g,'');">

Caution Experimental. Only partially works on chrome:
Wanted to look at a great way to grab the pasted value strip everything out then have it placed in input as normal. With the above method you are relying on the event order to correct the input, then any event listeners will ideally fire after. The onpaste method will fire before the input event fires so you keep the flow of events correct. However when replacing the string with only numbers the decimal point would still sneak in. Looking to update this when I find a better solution.

<input type="number" onkeydown="if(event.key==='.'){event.preventDefault();}" onpaste="let pasteData = event.clipboardData.getData('text'); if(pasteData){pasteData.replace(/[^0-9]*/g,'');} " >

A: Use pattern attribute
<input type="number" name="num" pattern="[0-9]" title="Numbers only">

For more details http://www.w3schools.com/tags/att_input_pattern.asp
FIDDLE

A: Just plain example using parseInt()

<input type="number" oninput="this.value=(parseInt(this.value)||0)" placeholder="0-9" autofocus='' value='0' />

A: An alternative to the supplied answers is to monitor the keypress while in the input. I personally like leaving the type="number" as an attribute. Here's a JSFiddle
<form action="#" method="post">
  Numbers: <input name="num"
                  type="number"
                  min="1"
                  step="1"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>

A: Based on other answers here, I tried this:

<input id="storeId" min="0" pattern="[0-9]" onkeypress="return !(event.charCode == 46)" step="1" title="Must be an integer number" type="number" >

I just blocked input of dot, but again this does not block paste.
ASCII DOT . character is 46

A: You guys can try this
This function does not allow user to paste unwanted characters and also disallow user to enter .+-E

var inputBox = document.getElementById("inputBox");

                var invalidChars = [
                    "-",
                    "+",
                    "e",
                    "."
                ];

                inputBox.addEventListener("input", function() {
                    this.value = this.value.replace(/[e\+\-\.]/gi, "");
                });

                inputBox.addEventListener("keydown", function(e) {
                    if (invalidChars.includes(e.key)) {
                        e.preventDefault();
                    }
                });

<input type="number" id="inputBox" >

`
If error occured in your JS. You can add this
`$(document).ready(function() { code });

A: Try this :
<input type="number"  value=""  min="0" oninput="this.value=(parseInt(this.value)||0)" onkeypress="return !(event.charCode == 45||event.charCode == 46||event.charCode == 43)"  class="form-control" step="any" />

A: <input type="number" onkeypress="return event.charCode >= 48 && event.charCode <= 57"  name="quantity">

A: event.key and event.charCode are deprecated features and don't work well with mobile virtual keyboards. I've done some research and this seems to be the easiest way to make it work.
Tested in Chrome and Firefox on Windows, in Chrome on Android and in Safari on iOS and seems to be working perfectly.

document.getElementById("myInput").addEventListener('beforeinput', e => {
  if (!(Number(e.data) >= 0 && Number(e.data) <= 9)) {
    e.preventDefault();
  }
});
/* unnecessary */
#myInput {
width: 24ch;
}
<input type="number" inputmode="numeric" placeholder="only a number can go here" id="myInput">

By the way, this is my first post here, so please tell me if I'm doing anything wrong.

A: You should post what you have tried when asking questions.
To use integers only, change the following attribute.
step="any"

to
step="1"

A: A simple regex can help sort with this issue .
var re = new regExp('[.]+) ;
if(!re.test(num)){listOfNumbers.push(num)};

not letting the user type in a '.' on the input might not be a viable option when you are dealing with multiple cultures and interpretations of '.'.

A: function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode==46))
        return false;
    return true;
}

A: @Html.TextBoxFor(model => model.num, new { @class = "form-control input-sm",@maxlength = 5 ,@oninput = "this.value = this.value.replace(/[^0-9]/g, '');"})
In MVC, above solution works.


text:
Q: How does CONTEXT's auto-generation of code documentation work? Unlike LaTeX's core, CONTEXT core macros have quite readable code and, specially in the lack of up-to-date documentation for certain commands, one can learn a lot by just reading the code itself and the documentation provided therein.  That's also a good source of learning how to write CONTEXT macros.
In fact, there is a way to generate documentation right from the code itself, which adds the provided annotations to the PDF output along with the actual code.  According to Garden, this is done via the following command line.
context --ctx=s-mod core-con.mkiv
This generates a core-con.mkiv.prep file and also compiles it into a nice PDF output.
How does the same functionality work for Lua files?  The same page on Garden suggests the following.
context --ctx=x-ldx core-con.lua
This generates a core-con.lua.prep and then a core-con.lua.prep.prep file but not the desired supposedly HTML documentation.  Question:  What am I doing wrong here?
Question: What tags beside the \module definition at the top and the index mechanism \macros can we use inside the %D comments (in MkIV sources)?  (I know we can use any TeX code; I'm asking what special macros are available.)  I also notice a special %C tag for the copyright statement but don't know what effect it has.  Are there any other special comment codes?
Question: What about the tags in the Lua file?  Those are more mysterious and scarcer.  Why are these HTML tags, anyway, instead of TeX macros?

A: It should be fixed in beta, see
CONTEXT distribution - beta version


text:
Q: Does the presence of an particular object in all the images of data set affect a CNN's performance Context: I have partial images of size view of different types of vehicles in my data set ( Partial images because of limited Field Of View of my camera lens ). These partial images cover more than half the vehicle and can be considered as good representative images of the vehicle. The vehicle categories are car, bus, trucks. I always get a wheel of the vehicle in these images and because I am capturing these images during different parts of the day the colour intensity of the wheels vary throughout the day. However a wheel is definitely present in all the images.
Question: I wanted to know if presence of a object in all the images of a data set not logically useful for classification will affect the CNN in any way. Basically I wanted to know before training the CNN should I mask the object i.e black it out in all the images or just let it be there.

A: A CNN creates a hierarchical decomposition of the image into combinations of various discriminatory patterns. These patterns are learnt during training to find those that separate the classes well.
If an object is present in every image, it is likely that it is not needed to separate the classes and won't be learnt. If there is some variation on the onject that is class dependant, then maybe it will be used. It is really difficult to know what features are important beforehand. Maybe busses have shinier wheels than other cars, and this is something you have not noticed, and thus having the wheel in the image is beneficial.
If you have inadvertently introduced some class specific variation, this can cause a problem for later classification. For example, if you only took photos of busses at night, the network might learn night = bus and when you show it a photo of a bus during the day it won't classify correctly.
However, using dropout in the network forces it to learn multiple features for classification, and not just rely on one. So if there is variation, this might not have as big an impact.
I would use the images without blanking anything out. Unless it is something simple such as background removal of particles etc., finding and blacking out the object adds another layer of complexity. You can test if the wheels make a big difference by training the network on the normal images, then classifying a few training examples with the object blacked out and seeing if the class probabilities change.
Focus you energy on doing good data augmentation, that is where you will get the most gains.
You can see an example of which features are learnt on MNIST in this paper.


text:
Q: Network Driver failing after every reboot I have a windows 8.1 machine. Every time I boot this system, without uninstalling the network adapter and scanning for any hardware changes in device manager it doesn't get the internet access. This happens after every single boot and is very miserable. Someone please help me out.

A: Hi there Arunachaleshwar K! Did you try updating windows? If not, then try this:
Step 1. Go to your start menu and press Restart whilst holding the shift key
Step 2. Once it boots into the advanced options menu, click on Refresh Computer (NOTE: You will need to back up all the installers for the programs you have as it will uninstall every program on your computer).
Step 3. press OK and wait around 1 hour (sometimes more) for the process to finish.
Now you should be able to update the driver.


text:
Q: Debug Jinja2 in Google App Engine When I'm running Jinja2 in Google App Engine, I get useless debugging information. I gather this is because of this item in the FAQ:

My tracebacks look weird. What's happening?
If the speedups module is not compiled and you are using a Python installation without ctypes (Python 2.4 without ctypes, Jython or Google's AppEngine) Jinja2 is unable to provide correct debugging information and the traceback may be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and it's not possible to use the speedups extension.

While there is no 'good' workaround for this at the moment, is there any workaround so that the information printed when exceptions arise can be made more helpful?
Thank you for reading.
Brian

A: You can get around this by adding _ctypes and gestalt to the development server's C module whitelist with monkeypatching.
To do so, put the following snippet at the top of your main.py:
import os
if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
    # Enable ctypes for Jinja debugging
    from google.appengine.tools.dev_appserver import HardenedModulesHook
    HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']

You can also use this trick to enable other C modules, if you have similar local-only module needs. Do note that these modules still won't actually work once you deploy, so tread carefully.
On SDK 1.6.3 using python2.7 you need to change the above code to:
import os
if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
    # Enable ctypes for Jinja debugging
    import sys
    from google.appengine.tools.dev_appserver import HardenedModulesHook
    assert isinstance(sys.meta_path[0], HardenedModulesHook)
    sys.meta_path[0]._white_list_c_modules += ['_ctypes', 'gestalt']

On SDK 1.8.6 for python 2.7, try this:
PRODUCTION_MODE = not os.environ.get(
    'SERVER_SOFTWARE', 'Development').startswith('Development')
if not PRODUCTION_MODE:
    from google.appengine.tools.devappserver2.python import sandbox
    sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']

A: Perhaps just use PyCharm's interactive debugger and step through the code:
http://www.jetbrains.com/pycharm/quickstart/#RunAndDebug

A: I use the following monkeypatch to enable slightly more helpful information when an exception occurs during Jinja2 template rendering:
# Enabling this monkeypatch can help track down hard to find errors that crop
# up during template rendering (since Jinja's own error reporting is so
# unhelpful on AppEngine).
real_handle_exception = environment.handle_exception
def handle_exception(self, *args, **kwargs):
    import logging, traceback
    logging.error('Template exception:\n%s', traceback.format_exc())
    real_handle_exception(self, *args, **kwargs)
environment.handle_exception = handle_exception

This will result in slightly more accurate exception tracebacks in your error logs.  I don't think it usually shows you exactly what went wrong (but if I remember correctly it sometimes does), but it will at least narrow the exception down to the correct template.
Why this works, I do not know (or cannot remember).
As an example, I just added some code that will trigger an exception to one of my templates. Under the development server, this is what the "normal" exception handler shows me:
Traceback (most recent call last):
  File "/Users/will/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__
    handler.get(*groups)
  File "/Users/will/workspace/keypremium/ki/shared/decorators.py", line 27, in inner
    return func(self, *args, **kwargs)
  File "/Users/will/workspace/keypremium/account/views.py", line 114, in get
    self.render_jinja('accounts/edit_card.html', ctx)
  File "/Users/will/workspace/keypremium/ki/webapp/handlers.py", line 186, in render_jinja
    return self.response.out.write(jinja.render(template_path, new_context))
  File "/Users/will/workspace/keypremium/ki/shared/jinja/__init__.py", line 21, in render
    return template.render(context)
  File "/Users/will/workspace/keypremium/ki/ext/jinja2/environment.py", line 705, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/will/workspace/keypremium/ki/shared/jinja/environment.py", line 24, in handle_exception
    real_handle_exception(self, *args, **kwargs)
  File "/Users/will/workspace/keypremium/templates/accounts/edit_card.html", line 1, in top-level template code
    {% extends 'accounts/base.html' %}
UndefinedError: 'sequence' is undefined

But the exception is not in the accounts/base.html template, it's in accounts/edit_card.html.  This is the most frustrating part of debugging Jinja2 template exceptions on App Engine:  The source of the exception is almost always misrepresented.  In my experience, the source is usually reported as either the parent template or as some template macro.
With the exception logging monkeypatch installed, the same exception generates this traceback in the logs:
Traceback (most recent call last):
  File "/Users/will/workspace/keypremium/ki/ext/jinja2/environment.py", line 702, in render
    return concat(self.root_render_func(self.new_context(vars)))
  File "/Users/will/workspace/keypremium/templates/accounts/edit_card.html", line 11, in root

  File "/Users/will/workspace/keypremium/templates/accounts/base.html", line 11, in root

  File "/Users/will/workspace/keypremium/templates/accounts/edit_card.html", line 54, in block_content
    {{ form.cvv2|safe }}
  File "/Users/will/workspace/keypremium/ki/ext/jinja2/environment.py", line 352, in getattr
    return getattr(obj, attribute)
  File "/Users/will/workspace/keypremium/ki/ext/jinja2/runtime.py", line 445, in _fail_with_undefined_error
    raise self._undefined_exception(hint)
UndefinedError: 'sequence' is undefined

There's still a lot of extraneous information here, but this traceback at least points me in the right direction.  It claims that the problem is on line 54 of accounts/edit_card.html (the correct template), but the actual exception occurs at line 86.
But given the correct template and the correct exception, I can pretty easily find that the troublesome code is this
{% for x in sequence.sequence() %}
    {{ x.y }}
{% endfor %}

where there is no sequence variable in the template context.
This isn't a perfect solution, but I've found it mighty helpful.

A: Not sure if that will be helpful, but it might be possible to at least add block templatetag like django's 'debug' which will at least help to localize the problem.

A: A way to avoid monkey-patching (which depends on the changing internals of the SDK) is to use the imp module, which is at least currently not disabled in the local development environment. Then just load _ctypes like this to enable better Jinja2 debugging:
import imp
file, pathname, description =  imp.find_module('_ctypes')
imp.load_module('_ctypes', file, pathname, description)

A: When I hit a problem like that I try to debug it on my local iPython shell. I wonder what the code that generates such a bug is. There should be a way to write a test for it.


text:
Q: определение методов во вложенных шаблонных классах template<class T>
class LinkedList
{
public:
LinkedList(int capacity);
~LinkedList();
const LinkedList& operator = (const LinkedList& right);
LinkedList(const LinkedList& right);

class Iterator : public std::iterator<std::bidirectional_iterator_tag, T>
{
public:
    Iterator(const LinkedList<T> &obj, int index);
    T& operator*();
    Iterator& operator++();
    Iterator& operator--();
    int GetIndex() const { return _copyIndex; };
    int *GetNext() const { return _copyNext; };

 private:
    int _copyIndex;
    int _copyPrevIndex;
    T *_copyItems;
    int *_copyNext;
    int *_copyPrev;
};

Iterator Add(T value);
Iterator Insert(Iterator it, T value);

private:
T *_items;
int *_next;
int *_prev;
int _index;
int _prevIndex;
int _deletedIndex;
int _head;
int _count;
int _capacity;
};

вопрос: подскажите пожалуста как вынести определение методов в классе Iterator и методов которые возвращают итератор из класса LinkedList?

A: Методы класса LinkedList<T>::Iterator:
template <class T>
LinkedList<T>::Iterator::Iterator(const LinkedList<T>& obj, int index)
{
     // ...
}

template <class T>
T& LinkedList<T>::Iterator::operator*()
{
    // ...
}

template <class T>
typename LinkedList<T>::Iterator& LinkedList<T>::Iterator::operator++()
{
    // ...
}

template <class T>
typename LinkedList<T>::Iterator& LinkedList<T>::Iterator::operator--()
{
    // ...
}

template <class T>
int LinkedList<T>::Iterator::GetIndex() const
{
    // ...
}

template <class T>
int* LinkedList<T>::Iterator::GetNext() const
{
    // ...
}

Методы класса LinkedList<T>, возращающие экземпляры LinkedList<T>::Iterator:
template <class T>
typename LinkedList<T>::Iterator LinkedList<T>::Add(T value)
{
    // ...
}

template <class T>
typename LinkedList<T>::Iterator LinkedList<T>::Insert(Iterator it, T value)
{
    // ...
}

Для чего необходимо дополнительное ключевое слово typename при обращении к типу LinkedList<T>::Iterator, можно прочитать здесь.


text:
Q: How to create a navigation bar that fades in when user scrolls down? (on blogspot) Okay, total noob here.
I have a blog on a blogspot platform, and I'm trying to create a navbar that fades in when the user is scrolling down. I've made my navbar in flash, put it in the right place, made it transparent and fixed etc. It is a div. I've no idea what code to use and where exactly to put it to make it fade-in on scroll down. HELP :D
http://blackforestdesigns.blogspot.com

A: Add this code just before </body>.
<script>
var navbar = document.querySelector('.sticknav');
navbar.style.opacity = 0;
window.addEventListener('scroll', function() {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if(scrollTop > 400) {
        navbar.style.opacity = 1;
    }
    else {
        navbar.style.opacity = 0;
    }
});
</script>

If you want to get more adventurous, make a CSS class that animates the transition:
<style type="text/css">
.sticknav {
    opacity: 0;
    transition: opacity 0.8s ease;
}
.sticknav.is-visible {
    opacity: 1;
}
</style>

And replace the if/else above with:
if(scrollTop > 400) {
    navbar.classList.add('is-visible');
}
else {
    navbar.classList.remove('is-visible');
}


text:
Q: Creating a dictionary in python from txt file I know variations of this has been asked before but I'm still struggling with moving a txt file into a dictionary. The txt file has names and amounts separated by a ":" . I'm having issues with the strip function not removing blank lines. Another issue I'm having is if two lines have the same key, I would like to sum the values. I'm still relatively new to python so any help would be appreciated!
enter image description here

A: very simple but not safe, there are lot of places where your program can crash but you probably don't care about that
def loadToDict(path):
    f = open(path)
    d = {}
    for line in f:
        line = line.strip()
        if line == "": # ignore empty line
            continue
        key, value = line.split(":") # decompose
        if key in d: # contains so add
            d[key] += int(value)
        else:
            d[key] = int(value)
    return d


text:
Q: ValueError: Input contains NaN, infinity or.....('float32') Trying to figure out why I keep getting the message listed as the headline of this question. I think I already cleaned data, removing NaN's. Can anyone help me out?
Looking into a dataset with 11K lines, I am trying to make the code train data to predict level of students dropping out. Using an ordinary Windows laptop, whilst also exercising in getting better doing data analysis.
# divide the data set into categorial and non categorial features and apply models to get the insight of the data
print("\nDEFINING CATEGORICAL AND NUMERICAL FEATURES")
categorical_features = X.select_dtypes(include=['object']).columns
print(categorical_features)
numerical_features = X.select_dtypes(exclude = ["object"]).columns
print(numerical_features)

print("\nDIVIDE THE DATA SET INTO CATEGORIAL AND NON CATEGORIAL FEATURES AND APPLY MODELS TO GET THE INSIGHT OF THE DATA")
print("Numerical features : " + str(len(numerical_features)))
print("Categorical features : " + str(len(categorical_features)))

print("\nFILLING THE MISSING VALUE OF TEST WITH THEIR MEAN VALUE, FOR BETTER ACCURACY")

test = test.select_dtypes(exclude=[np.object])
test.info()
test = test.fillna(test.mean(), inplace=True)
print("\nAPPLYING MODEL RANDOM FOREST REGRESSOR")

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from warnings import simplefilter
# ignore all future warnings
simplefilter(action='ignore', category=FutureWarning)

# pull data into target (y) and predictors (X)
predictor_cols = ['F18 ECTS på kurser med beståede talkarakter']

# -------------------------------------------

# Create training predictors data
train_X = X[predictor_cols]
my_model = RandomForestRegressor()
my_model.fit(train_X, y)
my_model.score(train_X, y)
print(predictor_cols)
print(my_model.score(train_X, y))

test = pd.read_csv("…_test.csv")

# -------------------------------------------

print("\nPRINT PREDICTED FACTORS")
test_X = test[predictor_cols]

#  model to make predictions

predicted_factor = my_model.predict(test_X)

#  at the predicted prices to ensure something sensible.

print(predicted_factor)

Get most of my code running fine, except:
APPLYING MODEL RANDOM FOREST REGRESSOR
Traceback (most recent call last):
  File "C:/Users/jcst/PycharmProjects/Frafaldsanalyse/DefiningCatAndNumFeatures_4_new.py", line 142, in <module>
    my_model.fit(train_X, y)
  File "C:\Users\jcst\PycharmProjects\Frafaldsanalyse\venv\lib\site-packages\sklearn\ensemble\forest.py", line 250, in fit
    X = check_array(X, accept_sparse="csc", dtype=DTYPE)
  File "C:\Users\jcst\PycharmProjects\Frafaldsanalyse\venv\lib\site-packages\sklearn\utils\validation.py", line 573, in check_array
    allow_nan=force_all_finite == 'allow-nan')
  File "C:\Users\jcst\PycharmProjects\Frafaldsanalyse\venv\lib\site-packages\sklearn\utils\validation.py", line 56, in _assert_all_finite
    raise ValueError(msg_err.format(type_err, X.dtype))
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').

Process finished with exit code 1

A: As said, your dataset X_train or y must contain nans. Check again to see where that comes from. It typically comes from division by 0 or math functions domain error like log of negative values.
Something else you're gonna run in after :
You're using test = test.fillna(test.mean(), inplace=True)
You should use test = test.fillna(test.mean())
Or test.fillna(test.mean(), inplace=True)
When specifying inplace=True, the function returns None and so test is None.
Also you're doing all this without use since you're overwriting test by reading a DataFrame later. Maybe you have an unintended behavior here.


text:
Q: Editing all occurrences of a string within a lists-within-list object Example data:
ds <- data.frame(q1 = c(1:3), q1b = c(1:3), q1c = c(1:3), q2 = c(1:3), q2b = c(1:3), q2c = c(1:3))

filterList <- list()
filterList[[1]] <- list(var= "q1", filterFor= c("q1b", "q1c"))
filterList[[2]] <- list(var= "q2", filterFor= c("q2b", "q2c"))

I have a data frame containing survey data, and a lists-within-list setup to keep track of filters. Eg. "only ask q1b if a certain answer was given in q1". The actual filter conditions are stored elsewhere, the lists-within-list setup is just there to help me keep track of dependencies.
I'm working on a function that will allow me to rename a variable (eg. q1) in both the data frame, and the list at the same time. In other words, I need a function that can rename every occurrence of the string "q1" to "Question 1", within both objects defined in the example code.

A: This function changes values of global variables, bouth to data.frame and list
renameF <- function(xold, xnew){
  colnames(ds) <<- gsub(xold, xnew, colnames(ds))
  filterList <<- lapply(filterList, function(x)
    lapply(x, function(y) gsub(xold, xnew, y)))
  return(NULL)
}

renameF("q1", "Question1")
ds
  Question1 Question1b Question1c Question2 Question2b Question2c
1         1          1          1         1          1          1
2         2          2          2         2          2          2
3         3          3          3         3          3          3

filterList
[[1]]
[[1]]$var
[1] "Question1"

[[1]]$filterFor
[1] "Question1b" "Question1c"

[[2]]
[[2]]$var
[1] "Question2"

[[2]]$filterFor
[1] "Question2b" "Question2c"


text:
Q: Problems setting up worker MPM Can't get MPM Worker to work..
I've installed the php-zts package, uncommented #HTTPD=/usr/sbin/httpd.worker in /etc/sysconfig/httpd and restarted the httpd service.
the httpd printout:
[root@web06 ~]# httpd -V
Server version: Apache/2.2.3
Server built:   Sep  3 2009 17:38:51
Server's Module Magic Number: 20051115:3
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/httpd"
 -D SUEXEC_BIN="/usr/sbin/suexec"
 -D DEFAULT_PIDLOG="logs/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="logs/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

the Apache:
[root@web06 ~]# apachectl -v
Server version: Apache/2.2.3
Server built:   Sep  3 2009 17:41:45
[root@web06 ~]# apachectl -l
Compiled in modules:
  core.c
  worker.c
  http_core.c
  mod_so.c

Server's details:
Linux web 2.6.18-164.15.1.el5PAE #1 SMP Wed Mar 17 12:14:29 EDT 2010 i686 i686 i386 GNU/Linux

How come the https still works in prefork mode?
I feel I miss something really basic..
Thanks!
EDIT 1
[root@web06 ~]# ps -ef | grep httpd
apache    4366 14700  0 05:44 ?        00:00:34 /usr/sbin/httpd
apache    9239 14700  0 06:07 ?        00:00:22 /usr/sbin/httpd
apache    9260 14700  0 06:07 ?        00:00:23 /usr/sbin/httpd
apache    9271 14700  0 06:07 ?        00:00:23 /usr/sbin/httpd
apache    9288 14700  0 06:07 ?        00:00:22 /usr/sbin/httpd
apache    9337 14700  0 06:07 ?        00:00:23 /usr/sbin/httpd
root     14700     1  0 Aug08 ?        00:00:00 /usr/sbin/httpd
apache   14702 14700  0 Aug08 ?        00:00:00 /usr/sbin/httpd
apache   22445 14700  0 06:57 ?        00:00:04 /usr/sbin/httpd
apache   22480 14700  0 06:57 ?        00:00:04 /usr/sbin/httpd
apache   27910 14700  0 07:10 ?        00:00:00 /usr/sbin/httpd
apache   27917 14700  0 07:10 ?        00:00:00 /usr/sbin/httpd
root     27948  9898  0 07:11 pts/2    00:00:00 grep httpd

EDIT 2
[root@web06 ~]# ls -l /usr/sbin/httpd*
-rwxr-xr-x 1 root root 315284 Sep  3  2009 /usr/sbin/httpd
-rwxr-xr-x 1 root root 327708 Sep  3  2009 /usr/sbin/httpd.event
-rwxr-xr-x 1 root root 327708 Sep  3  2009 /usr/sbin/httpd.worker

[root@web06 ~]# cat /var/log/httpd/error_log
[Thu Aug 09 07:26:14 2012] [notice] SELinux policy enabled; httpd running as context root:system_r:httpd_t
[Thu Aug 09 07:26:14 2012] [notice] Digest: generating secret for digest authentication ...
[Thu Aug 09 07:26:14 2012] [notice] Digest: done
[Thu Aug 09 07:26:14 2012] [notice] mod_python: Creating 4 session mutexes based on 6 max processes and 25 max threads.
[Thu Aug 09 07:26:14 2012] [notice] Apache/2.2.3 (CentOS) configured -- resuming normal operations

EDIT 3
[root@web06 conf]# grep '/etc/sysconfig/httpd' /etc/init.d/httpd
# config: /etc/sysconfig/httpd
if [ -f /etc/sysconfig/httpd ]; then
        . /etc/sysconfig/httpd
# Set HTTPD=/usr/sbin/httpd.worker in /etc/sysconfig/httpd to use a server

EDIT 4
Output of sh -x /etc/init.d/httpd start > /tmp/apache.debug 2>&1
EDIT 5
After running the commands by @quanta:
[root@web06 ~]# ps -ef | grep httpd
root     16303     1  0 08:29 ?        00:00:00 /usr/sbin/httpd.worker
apache   16305 16303  2 08:29 ?        00:00:37 /usr/sbin/httpd.worker
apache   16307 16303  2 08:29 ?        00:00:35 /usr/sbin/httpd.worker
root     20415 20381  0 08:56 pts/1    00:00:00 grep httpd

A: Don't know why the first check ps -ef | grep httpd still shows /usr/sbin/httpd but since I see the belows in the debug:
+ /bin/bash -c 'ulimit -S -c 0 >/dev/null 2>&1 ; /usr/sbin/httpd.worker'
...
+ success 'httpd.worker startup'

I'm pretty sure that your Apache is running in worker mode, and the second check prove that:
[root@web06 ~]# ps -ef | grep [h]ttpd
root     16303     1  0 08:29 ?        00:00:00 /usr/sbin/httpd.worker
apache   16305 16303  2 08:29 ?        00:00:37 /usr/sbin/httpd.worker
apache   16307 16303  2 08:29 ?        00:00:35 /usr/sbin/httpd.worker

DON'T use httpd -V to check the mode which Apache is running in, because:
# which httpd
/usr/sbin/httpd

Use apachectl -V (uppercase) instead:
Server version: Apache/2.2.3
Server built:   Oct 20 2011 17:03:44
Server's Module Magic Number: 20051115:3
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   64-bit
Server MPM:     Worker
  threaded:     yes (fixed thread count)
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/worker"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/etc/httpd"
 -D SUEXEC_BIN="/usr/sbin/suexec"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

or /server-info:
$ lynx -dump http://yourdomain.com/server-info | grep -i mpm
   MPM Name: Worker
   MPM Information: Max Daemons: 1 Threaded: yes Forked: yes
   Server Built With: -D APACHE_MPM_DIR="server/mpm/prefork" -D
          AcceptMutex - Valid accept mutexes for this platform and MPM


text:
Q: vuelidate error message show up after form submission I'm  using vuelidate for form validation in vuejs3 and composition api.
After submit form, I call validate. If validation passes, the form fields should be emptied and vuelidate should be reset.
I currently do that like so:
const submitForm = () => {
  if (!v$.value.$validate()) {
    console.log(`Error : ${form} `)
    return
  }
  // there will be an axios post request here:
  console.log(form)
  v$.value.$reset()
  Object.keys(form).forEach(v => form[v] = "")

}

For some reason, v$.value.$reset() is called also when the form is invalid (so validation passes even when forms are invalid) and Object.keys(form).forEach(v => form[v] = "") causes validation errors so that when the form is submitted correctly, all error messages show up.
How to clear the form without reloading the page and reset vuelidate only after submission without errors?

A: We can use this.$v.$reset(); to clear the error messages and it works fine for me


text:
Q: Bootstrap-Table - Set specific background-color based on cell value I am using bootstrap-table and I would like to color certain columns red or green based on the value that they are having.
I am having the following table:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link href="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.css" rel="stylesheet">

Products

        Transaction Date
        Buy/Sell
        Total Transaction
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $95,001,513.81
        Details

Is there a way to style each row like the following:

I tried to set a data-element on my tr-tag however, as I have many tables that need to get styled ist there an easier way with css?
I appreciate your replies!

A: With your current HTML, you could use something like this to get the value of the appropriate cell, reformat the string into a float, and change the background color based on this value.
$('#table tr').each(function () {
    let value = this.children[2].innerHTML;

    // omit dollar signs and commas with replace and return a float
    value = parseFloat(value.replace(/\$|,/g, ''));

    // compare values and adjust styling
    value > 90000000.50 ? this.style.backgroundColor = 'lightgreen' : '';
    value < 10000000.75 ? this.style.backgroundColor = 'salmon' : '';
});

A: Is this What you need?
The reason for using class instead of manually telling to check 'nth' cell is because, May be in future the order column in table or the number of column in the table may vary, so its recommenced to use a selector to implement this

$('.trans').each(function() {
  if (parseFloat($(this).text().replace(/\$|,/g, '')) <= 100000000.00) {
    $(this).parent().css({
      'background-color': '#89e289'
    })
  } else {
    $(this).parent().css({
      'background-color': '#f08080'
    })
  }

});
//If you want to check Sell/Product cell do:

$('.sales').each(function(){
  if($(this).text() == 'Sell'){
    $(this).parent().css({'background-color' : '#89e289'})
  }
  else{
     $(this).parent().css({'background-color' : '#f08080'})
  }
 });
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link href="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.css" rel="stylesheet">

Products

        Transaction Date
        Buy/Sell
        Total Transaction
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Purchase
        $95,001,513.81
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

        8/18/2016
        Sell
        $195,001,513.81
        Details

A: Unfortunately you cannot set base color or styles of any elements in your HTML, depending on the content they have with CSS. This is something you must look over with javascript.
Why this? Because CSS is a frontend styling "modifier", that edits property of HTML without looking at its content and what there is written. It simply applies styles. With JavaScript however, you can edit the content by taking it, analyzing it, and changing its style.
I took your code and edited a little the content of it to modify and show you how you can deal with this in javascript. You can do that in more efficient ways but I went for simplicity and the DOM to make you understand at best

for (let i = 0; i < 11; i++) {
    let price = document.getElementsByClassName('price')[i].innerText;
    console.log(price)
    if (price <= 100){
        document.getElementsByClassName('price')[i].style.backgroundColor = 'red'
    } else if (price > 100) {
        document.getElementsByClassName('price')[i].style.backgroundColor = 'blue'
    }
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

Products

        Transaction Date
        Buy/Sell
        Total Transaction
        Details

        8/18/2016
        Sell
        80
        Details

        8/18/2016
        Purchase
        90
        Details

        8/18/2016
        Purchase
        700
        Details

        8/18/2016
        Purchase
        900
        Details

        8/18/2016
        Sell
        500
        Details

        8/18/2016
        Sell
        200
        Details

        8/18/2016
        Purchase
        300
        Details

        8/18/2016
        Purchase
        100
        Details

        8/18/2016
        Sell
        100
        Details

        8/18/2016
        Sell
        100
        Details

        8/18/2016
        Sell
        100
        Details


text:
Q: Getting error 'unknown field hostPath' Kubernetes Elasticsearch using with local volume I am trying to deploy elastic-search in kubernetes with local drive volume  but  I get the following error, can you please correct me.
using ubuntu 16.04
kubernetes v1.11.0
Docker version 17.03.2-ce
Getting error 'unknown field hostPath' Kubernetes Elasticsearch using with local volume
error: error validating "es-d.yaml": error validating data: ValidationError(StatefulSet.spec.template.spec.containers[1]): unknown field "hostPath" in io.k8s.api.core.v1.Container; if you choose to ignore these errors, turn validation off with --validate=false

This is the yaml file of the statefulSet:
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: es-data
  labels:
    component: elasticsearch
    role: data
spec:
  serviceName: elasticsearch-data
  replicas: 1
  template:
    metadata:
      labels:
        component: elasticsearch
        role: data
    spec:
      initContainers:
      - name: init-sysctl
        image: alpine:3.6
        command:
        - sysctl
        - -w
        - vm.max_map_count=262144
        securityContext:
          privileged: true
      containers:
      - name: es-data
        image: quay.io/pires/docker-elasticsearch-kubernetes:6.3.0
        env:
        - name: NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: CLUSTER_NAME
          value: myesdb
        - name: NODE_MASTER
          value: "false"
        - name: NODE_INGEST
          value: "false"
        - name: HTTP_ENABLE
          value: "true"
        - name: ES_JAVA_OPTS
          value: -Xms256m -Xmx256m
        - name: PROCESSORS
          valueFrom:
            resourceFieldRef:
              resource: limits.cpu
        resources:
          requests:
            cpu: 0.25
          limits:
            cpu: 1
        ports:
        - containerPort: 9200
          name: http
        - containerPort: 9300
          name: transport
        livenessProbe:
          tcpSocket:
            port: transport
          initialDelaySeconds: 20
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /_cluster/health
            port: http
          initialDelaySeconds: 20
          timeoutSeconds: 5
        volumeMounts:
        - name: storage
          mountPath: /es
        volumes:
      - name: storage

A: You have the wrong structure. volumes must be on the same level as containers, initContainers.
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  name: es-data
  labels:
    component: elasticsearch
    role: data
spec:
  serviceName: elasticsearch-data
  replicas: 1
  template:
    metadata:
      labels:
        component: elasticsearch
        role: data
    spec:
      initContainers:
      - name: init-sysctl
        image: alpine:3.6
        command:
        - sysctl
        - -w
        - vm.max_map_count=262144
        securityContext:
          privileged: true
      containers:
      - name: es-data
        image: quay.io/pires/docker-elasticsearch-kubernetes:6.3.0
        env:
        - name: NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: CLUSTER_NAME
          value: myesdb
        - name: NODE_MASTER
          value: "false"
        - name: NODE_INGEST
          value: "false"
        - name: HTTP_ENABLE
          value: "true"
        - name: ES_JAVA_OPTS
          value: -Xms256m -Xmx256m
        - name: PROCESSORS
          valueFrom:
            resourceFieldRef:
              resource: limits.cpu
        resources:
          requests:
            cpu: 0.25
          limits:
            cpu: 1
        ports:
        - containerPort: 9200
          name: http
        - containerPort: 9300
          name: transport
        livenessProbe:
          tcpSocket:
            port: transport
          initialDelaySeconds: 20
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /_cluster/health
            port: http
          initialDelaySeconds: 20
          timeoutSeconds: 5
        volumeMounts:
        - name: storage
          mountPath: /es
      volumes:
      - name: storage

You can find example here.

A: Check your format, hostPath is not supposed to be under container part, 'volume' is not in it's position.


text:
Q: Read file in 8086 until the end of the file MOV AH,3DH
MOV DX,OFFSET(FNAME)
MOV AL,0  ; 0 MEAN FOR READING PURPOSE             ;OPEN
INT 21H
MOV HANDLE,AX

MOV AH,3FH
MOV BX,HANDLE
MOV DX,OFFSET(BUFFER)                            ;READ
MOV CX,30
INT 21H

MOV AH,3EH
MOV DX,HANDLE                                     ;CLOSE
INT 21H

Now here the program reads only 30 letters from the file. I need is to read the whole file without knowing how many letters in it so how much letter it has the program will read them all.

A:
MOV AH,3FH
MOV BX,HANDLE
MOV DX,OFFSET(BUFFER)                            ;READ
MOV CX,30
INT 21H

This is the code that you need to replace with a loop that reads successive chunks of the file until there is nothing left.
The 3Fh DOS call not only informs you via the carry flag about possible errors, but it also returns in the AX register the number of bytes that were actually read.
ReadMore:
    mov dx, offset BUFFER
    mov cx, 5           ; Your chunk apparently has 5 bytes
    mov bx, HANDLE
    mov ah, 3Fh         ; DOS.ReadFile
    int 21h             ; -> AX CF
    jc  ReadError
    cmp ax, cx          ; Compares RECEIVED BYTES with REQUESTED BYTES
    jb  PartialRead
WholeChunk:

    ... Whatever you need to do with 5 bytes ...

    jmp     ReadMore
PartialRead:
    test    ax, ax
    jz      EndOfFile
PartialChunk:

    ... Whatever you can do with 1, 2, 3, or 4 left-over bytes ...

EndOfFile:
    mov bx, HANDLE
    mov ah, 3Eh         ; DOS.CloseFile
    int 21h
    ...

Please notice the typo in next snippet. The handle goes in the BX register!

MOV AH,3EH
MOV DX,HANDLE                                     ;CLOSE
INT 21H


text:
Q: C Interface as an API with Boost backend I'm working on a C++ library and was wondering about compatibility within it's own API and ABI. I stumbled upon this (Creating Library with backward compatible ABI that uses Boost) which gave some helpful tips.
The problem I'm facing is trying to create a C interface that doesn't use STL/Boost and somehow get the same functionality as the backend which does use them. Some of my interface functions require allowing the user to bind function pointers. Normally I'd use boost bind/function for this but now I can't.
An example to illustrate the problem:
PRIVATE/INTERNAL:
class TestClass
{
public:
    typedef boost::function<void (void)> FuncType;

public:
    TestClass( FuncType f ) : m_Func(f)
    {
    }

    void operator()()
    {
        m_Func();
    }

private:
    boost::function<void (void)> m_Func;
};

void* createTestClass(...)
{
    TestClass* fooHandle = new TestClass(boost::bind(...));
    return fooHandle;
}

PUBLIC INTERFACE:
extern "C" void* createTestClass(...);

CLIENT'S CODE:
void doSomething()
{
}

class DoStuffClass
{
public:
    void Stuff() {}
};

createTestClass(&doSomething);

DoStuffClass stuff;
createTestClass(&DoStuffClass::Stuff, &stuff);

I can probably make this work for simple function pointers but for member functions is there a way? What would I put in the ... sections?
Cheers!

A: If you're going to try to define your own delegates to wrap C++ member functions, free functions etc., I suggest you take a look at "5 years later, is there something better than the "Fastest Possible C++ Delegates"?.  The discussion is quite nice and the accepted answer proposes a neat trick to reduce all callbacks to a pair of void* and some free function R(void*,...) that invokes a member function or free function and whatnot.
I've used a similar technique to implement wrappers for Win32 API callbacks.  Here's an example (take a look at the Timer::function<> and Timer::method<> inner types).  Using this technique, you can expose a C interface like:
/* type of callback functions passed through the C interface.
   Obviously, C++ templates won't be of any help here, you need
   to typedef all the function signatures. */
typedef void(*Callback)(void*,int, int);

/* Example function that uses one of the callbacks. */
extern "C" void* createTestClass(Callback,void*);

// Enhanced interface for passing object methods bound to
// a specific instance instead of the basic C-style callback.
#ifdef __cplusplus
    template<typename T, void(T::M)(int,int)>
    inline
    void * createTestClass2(T& object,method<T,M> method)
    {
        // '&object' converts to 'void*' and 'method' object
        // converts to 'void(void*,int,int)' function pointer.
        return createTestClass(&object, method);
    }
#endif

The role of the proposed mechanism is just generation of the void(void*,int,int) functions that wrap member function calls so that they have the right signature.  Everything else is just plain C function pointers and can be freely passed to your C API while preserving the ABI.
Just be careful exceptions don't leak from your C++ callback functions.  See "Passing C++ exceptions across a C API boundary" for a more detailed discussion of the topic.

Update (working example)
Here's a full working example (tested with Visual Studio 2008).
library.h (public interface for C or C++ clients with stable ABI)
#ifndef _library_h_
#define _library_h_

#ifdef __cplusplus
extern "C" {
#endif

typedef int(*Callback)(void*,int,int);

void* createTestClass(Callback,void*);

#ifdef __cplusplus
}
#endif

#endif /* _library_h_ */

library.c (library implementation)
This demonstrates a C implementation, but you could have a C++ file instead and use std::function<>, boost::function<> or other to use the callback.
#include "library.h"

void* createTestClass(Callback callback, void* context)
{
    callback(context, 1, 2);
    return 0;
}

library.hpp (enhanced interface for C++ clients, builds on public ABI)
This is the enhanced interface for C++ clients.  It adds support for using member functions instead of plain int(void*,int,int) free functions.  If you only plan to support C++ clients, then this can be in the same file as your C-style interface.
#ifndef _library_hpp_
#define _library_hpp_

#include "library.h"

template<typename T, int(T::*M)(int,int)>
class MethodCallback
{
    static int wrapper(void* context, int x, int y)
    {
        return (static_cast<T*>(context)->*M)(x, y);
    }
public:
    operator Callback () const
    {
        return &wrapper;
    }
};

template<typename T, int(T::*M)(int,int)>
void* createTestClass(T& object, MethodCallback<T,M> method)
{
    return createTestClass(static_cast<Callback>(method), static_cast<void*>(&object));
}

#endif //  _library_hpp_

main.cpp (test program)
Here's a simple demo on using the interface:
#include "library.hpp"
#include <iostream>

namespace {

    class Foo
    {
    public:
        int bar(int x, int y)
        {
            std::cout
                << "Foo::bar(" << x << "," << y << ")"
                << std::endl;
            return 1;
        }
    };

}

int main(int, char**)
{
    Foo foo;
    void* instance = ::createTestClass
        (foo, MethodCallback<Foo, &Foo::bar>());
    // ...
}

You should expect this program to output Foo::bar(1, 2) since the registered callback function will invoke foo.bar(1,2).


text:
Q: Using a PNP over an NPN to activate a solenoid I am working on a circuit that controls a solenoid through the use of an Arduino. One question I had was if there was any advantage to using a PNP transistor over an NPN transistor? From class, I know that PNP's are usually better for pulling devices high and NPNs are better for pulling devices low, although I am unsure why this is the case.
For reference, I want to use an Arduino to control the transistor that activates the solenoid. So when the Arduino outputs a HIGH signal, the solenoid should activate, and at LOW signal, it shouldn't do anything. After searching around online, it seems that a general schematic for that would look like this (asides from the BJT):

It seems like an NPN would be the best choice for this scenario, but I don't really understand how connecting the solenoid to ground would activate it? It seems to logically make more sense to have the solenoid connected to ground all the time, then when it's time to activate the solenoid, simply pull up the solenoid using a PNP. However due to the inverse behavior of a PNP to an NPN, it would take a little more work then just having the Arduino output a HIGH signal.

A: It's mostly about convenience.
Low-side drive like the NPN shown can be controlled directly by ordinary logic levels yet can manage a higher controlled voltage (like the +12V shown in the example.)
A PNP (or P-FET) can be used to switch on the high side, if the switch supply is the same or lower than the logic level.
Example:

simulate this circuit – Schematic created using CircuitLab
Otherwise, read on.
For higher-than-logic voltages like the example, a high-side drive PNP needs a level shifter (such as another NPN) to translate the voltage up. The shifter ensures that the PNP base is pulled up high enough to reliably turn off the device.
Example:

simulate this circuit
(Some notes. R3 isn't strictly necessary, it pulls the Q1 base up to +12 when Q2 is off to improve noise immunity. R2 should be sized based on the required Q1 saturation current.)
Same goes for MOSFETs: a low-side N-FET can be switched with logic; a high-side P-FET needs a level shifter if it's switching a voltage higher than the logic level.
And here's the high-side switch, with MOSFETs:

simulate this circuit
NPNs (and their N-FET cousins) offer somewhat better current handling capability than the P-type devices, but only slightly so given modern process technology.

A:
any advantage to using a PNP transistor over an NPN transistor?

It's largely a matter of economics and efficiency. In general, for a fixed price point, NPN and N-channel devices can carry more current, and for a fixed current capacity, NPN and N-channel devices are cheaper. For example, take the 2N440x, TO-92, 600mA, 40V. The 4401 is NPN, $0.293; the 4403 is PNP, $0.299. Other devices can have more dramatic differences - wider price gaps, or even availability only in NPN and not PNP.
That aside, take a read through this for example. NPN devices have faster charge carrier (electron) mobility; more convenient reference voltage (ground) when in the most common configuration, common emitter; and less die area.

A: A logic 'high' or 'low' is relative to the polarity of the reference.
Should the reference be negative, 'high' would be positive and 'low' negative.
Likewise, should the reference be positive, 'low' would be positive and 'high' negative.
In the present context, an NPN transistor would be used, should the ground be negative.

Accordingly, a PNP transistor would be used, should the ground be positive.

The configuration is the same in either case.

A:
It seems to logically make more sense to have the solenoid connected to ground all the time, then when it's time to activate the solenoid, simply pull up the solenoid using a PNP.

Why is that? Keep in mind the solenoid doesn't "know" which end is ground. "Ground" is a concept people made up to simplify discussion about a circuit. Electronic components know nothing about it.
Your circuit could be redrawn like this:

simulate this circuit – Schematic created using CircuitLab
Now the solenoid is connected to ground all the time, but this circuit is identical to the one in your question. The choice of what to call "ground" is arbitrary, and while this particular choice is non-conventional and confusing to talk about because it violates the conventions of what "ground" is typically, it's electrically identical.
This is because "voltage" is measuring electric potential difference, and because it's difference means it doesn't matter which point we decide to call "0V" or "ground". All the solenoid cares about is that there's a 12V difference between its terminals.
Now of course you could build the circuit with a PNP, like so:

simulate this circuit
Some ICs (usually digital logic) have open-drain outputs like this, or you can replace M1 with a discrete MOSFET or an NPN transistor. Some microcontrollers might have them, but the AVR on an Arduino does not.
The only change really is you might want to increase the value of R1, since the base current would otherwise be higher due to the additional voltage. But given the above explanation about the arbitrary nature of ground, is there any particular advantage to this solution?

A: One reason you would want 'high side' switching is driving a load in an automotive application. Often, controllers are purely driving loads with a single wire, where the return path is a chassis ground. You may not have the option of controlling ground. In that case, PNP BJT or P Channel MOSFETS are easier to use than bootstrapped N Channel devices.
In that case, level shifted drives, such as shown by @hacktastical in the second and third drawing, would suit very well.
Sometimes the domain of the problem you are trying to solve will constrain the solutions you will bring to bear.

A: Although it has been said several times, I will try to say it even more simply and clearly.
The simple truth is that, in most cases, the input sources and next loads are connected with one (negative) of their two terminals to the negative terminal of the power supply assigned as a zero reference point ("ground"). The transistor should be also connected to this point with its "negative terminal"; so it should be NPN type.


text:
Q: Subclassing a subclass of a (generic) builder I'm trying to implement a builder object with multi-level inheritance. I took some inspiration from Subclassing a Java Builder class and this is my (simplified) code:
public class StackOverflow {
    public static class Builder<T extends Builder<T>> {
        public Builder() {}

        public T doA() {
            System.out.println("A");
            return (T) this;
        }
    }

    public static class BuilderSubclass <T extends BuilderSubclass<T>>
            extends Builder<BuilderSubclass<T>> {

        public BuilderSubclass() {}

        public T doB() {
            System.out.println("B");
            return (T) this;
        }
    }

    public static class BuilderSubclassSubclass
            extends BuilderSubclass<BuilderSubclassSubclass> {

        public BuilderSubclassSubclass() {}

        public BuilderSubclassSubclass doC() {
            System.out.println("C");
            return this;
        }
    }
}

I would like do something like this:
new StackOverflow.BuilderSubclassSubclass().doA().doC().doB()
However, when I call new StackOverflow.BuilderSubclassSubclass().doA(), the returned object is not a BuilderSubclassSubclass but a BuilderSubclass<BuilderSubclassSubclass>. I know why this is the case: Builder's generic type is BuilderSubclass<BuilderSubclassSubclass> which is assigned in the class signature of BuilderSubclass.
Any ideas on how I can avoid this problem?
Update: I guess I could avoid using the builder pattern, and instead call the functions like this:
StackOverflow.BuilderSubclassSubclass builder = new StackOverflow.BuilderSubclassSubclass();
builder.doA();
builder.doB();
builder.doC();

In which case the code becomes:
public class StackOverflowBatchHelperFunctions {
    public static class Builder {

        public Builder() {
        }

        public void doA() {
            System.out.println("A");
        }
    }

    public static class BuilderSubclass extends Builder {
        public BuilderSubclass() {
            super();
        }

        public void doB() {
            System.out.println("B");
        }
    }

    public static class BuilderSubclassSubclass extends BuilderSubclass {
        public BuilderSubclassSubclass() {
            super();
        }

        public void doC() {
            System.out.println("C");
        }
    }
}

However I think this is less "pretty", so I would still love to see an answer to the initial problem.

A: You should replace public static class BuilderSubclass<T extends BuilderSubclass<T>> extends Builder<BuilderSubclass<T>> with public static class BuilderSubclass<T extends BuilderSubclass<T>> extends Builder<T>.


text:
Q: How to web scrape date from a website and store that date in database using php and mysql? I have been looking around on the internet for the ways to get dates of an event and then store that date into the database, but I was not able to find much.
I was able to get the dates from the website, but I don't know how to store it.
I want to get dates only from the website and then store it in the format of Y-m-d. Please if you know any way to do this, tell me.
Link: https://www.brent.gov.uk/events-and-whats-on-calendar/?eventCat=Wembley+Stadium+events
<?php

$curl = curl_init();
$all_data = array();

$url = "https://www.brent.gov.uk/events-and-whats-on-calendar/?eventCat=Wembley+Stadium+events";

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($curl);

$event = array();

preg_match_all('/
(.*?)<\/h3>/si',$result,$match);
$event['title'] = $match[1];

print_r($event['title']);

echo $all_data;
?>

A: don't use regex to parse html, use a proper HTML parser, for example DOMDocument.
a quick inspection of the site reveals that all the dates are in h3 children of the only article element on the page, you can use that to identify them. after extracting their dates, you can use strtotime() to convert it to an unix timestamp, then you can use date() to convert it to to the Y-m-d format, eg
$result = curl_exec($curl);
$domd=@DOMDocument::loadHTML($result);
$dateElements=$domd->getElementsByTagName("article")->item(0)->getElementsByTagName("h3");
foreach($dateElements as $ele){
    var_dump(date("Y-m-d",strtotime($ele->textContent)));
}

as for how to store the results in a mysql database, try writing php mysql tutorial -w3schools in google, or read the PDO section here: http://www.phptherightway.com/#pdo_extension

A:         <?php

        $db_host = "localhost";
        $db_username = "username";
        $db_pass = "password";
        $db_name = "name";

        // Run the actual connection here
        $con = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
        if ($con->connect_errno) {
            die("Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error);
        }

        $curl = curl_init();

    //The Website you want to get data from
        $url = "https://www.brent.gov.uk/events-and-whats-on-calendar/?eventCat=Wembley+Stadium+events";

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($curl);
        libxml_use_internal_errors(true);

        $domd=@DOMDocument::loadHTML($result);

        //Getting the date from the site

        $dateElements=$domd->getElementsByTagName("article")->item(0)->getElementsByTagName("h3");
        foreach($dateElements as $ele){
            $data = (date("Y-m-d",strtotime($ele->textContent)));

        // echo "
".$data;

//checking if the date match with database date
           $sql = "SELECT * FROM event_table WHERE date = '$data'";
            $result = $con->query($sql);

        if ($result->num_rows > 0) {

            // output data of each row, if date match echo "Data is there";
            while($row = $result->fetch_assoc()) {
                  echo  "Data is there";
            }
        }
//if date is not there then inster it into the database
        else {
           $results = mysqli_query($con, "INSERT INTO event_table (id, date) VALUES ('',' $data')");
            echo "data uploaded";
        }

        }
        ?>


text:
Q: Update null values column with values from the same column based on a query I have a table that has 2 columns, SSN and StateID.  There are duplicate rows with the same SSN, but not all rows have a StateID.  I want to select the rows that have a null StateID, and update it with the row with a matching SSN, and has a StateID.
Example of data
SSN           StateID
123456789      XYZ
123456789
123456789
000000001      ABC
000000001

I want to update the null values in StateID with the row value that does not have a null value.

A: First, you should fix your data model.  It is a bad idea to replicate data across multiple rows.  You should have a table with row per state and SSN and then use a join to connect them.
That said, in most databases you can do:
update t
    set stateid = (select max(t2.stateid) from t t2 where t2.ssn = t.ssn)
    where t.stateid is null;