text:
Q: Sorting a vector of (double precision) reals and obtain their In C++ would like to sort a lengthy (2^20) vector of reals, obviously sort() does the trick. Having used R before I was used to the nice order() function which yields the permutation that leads to the sorted vector.
Example:
x = {24, 55, 22, 1}

Then the permutation
perm = {3, 2, 0, 1}

Maps the original x to the sorted x in ascending order.
I can probably implement some bubble sort which does not only sort x but performs the same transpositions on the vector {0,1,2,...} and outputs both, but I believe someone must have thought about it and especially have done it efficiently.

A: I would say the best way would be to create a vector of ints 0..N and then sort that array with a comparison function that compares the corresponding elements of the vector you're trying to find the sorted permutation of.  Something like:
#include <vector>
#include <algorithm>

template<class T> class sorter {
    const std::vector<T> &values;
public:
    sorter(const std::vector<T> &v) : values(v) {}
    bool operator()(int a, int b) { return values[a] < values[b]; }
};

template<class T> std::vector<int> order(const std::vector<T> &values)
{
    std::vector<int> rv(values.size());
    int idx = 0;
    for (std::vector<int>::iterator i = rv.begin(); i != rv.end(); i++)
        *i = idx++;
    std::sort(rv.begin(), rv.end(), sorter<T>(values));
    return rv;
}

This minimizes the allocation overhead, as we don't create any large temporary object that we sort and then extract the final permution -- the same vector that is being returned is the temp for sorting.

A: You can use std::sort to sort the list of pairs {(24, 0), (55, 2), (22, 0), (1, 1)}. It isn't particularly pretty, but I usually do something like this:
#include <vector>
#include <algorithm>
#include <utility>

typedef std::pair<double, int> Pair;

struct CmpPair
{
    bool operator()(const Pair& a, const Pair& b)
    { return a.first < b.first; }
};

void sortingPermutation(
    const std::vector<double>& values,
    std::vector<int>& permutation)
{
    std::vector<Pair> pairs;
    for (int i = 0; i < (int)values.size(); i++)
        pairs.push_back(Pair(values[i], i));

    std::sort(pairs.begin(), pairs.end(), CmpPair());

    typedef std::vector<Pair>::const_iterator I;
    for (I p = pairs.begin(); p != pairs.end(); ++p)
        permutation.push_back(p->second);
}

Here is the test:
#include <iostream>

int main()
{
    std::vector<double> values;
    values.push_back(24);
    values.push_back(55);
    values.push_back(22);
    values.push_back(1);

    std::vector<int> permutation;
    sortingPermutation(values, permutation);

    typedef std::vector<int>::const_iterator I;
    for (I p = permutation.begin(); p != permutation.end(); ++p)
        std::cout << *p << " ";
    std::cout << "\n";
}

A: Edit
Better than before approach without using helper vectors: (source on ideone):
#include <vector>
#include <algorithm>
#include <iostream>

template<class Vals>
void sortingPermutation(const Vals& values, std::vector<int>& v){
  int size = values.size();
  v.clear(); v.reserve(size);
  for(int i=0; i < size; ++i)
    v.push_back(i);

  std::sort(v.begin(), v.end(), [&values](int a, int b) -> bool {
    return values[a] < values[b];
  });
}

int main()
{
    std::vector<double> values;
    values.push_back(24);
    values.push_back(55);
    values.push_back(22);
    values.push_back(1);

    std::vector<int> permutation;
    sortingPermutation(values, permutation);

    typedef std::vector<int>::const_iterator I;
    for (I p = permutation.begin(); p != permutation.end(); ++p)
        std::cout << *p << " ";
    std::cout << "\n";
}

I am using lambda from C++0x, but it can be replaced with simple functor object:
template<class T>
struct CmpPairs{
  CmpPairs(const std::vector<T> &v): v_(v) {}
  std::vector<T> v_;
  bool operator()(int a, int b){ return v_[a] < v_[b]; }
};

template<class T>
CmpPairs<T> CreateCmpPairs(const std::vector<T> & v) { return CmpPairs<T>(v); }
//in sortingPermutation:
std::sort(v.begin(), v.end(), CreateCmpPairs(values));

Source of old solution with std::map: ideone


text:
Q: How to get pass error : TypeError: addtrans() missing 1 required positional argument: 'self' i created a button function 'addtrans" that will create another pop up window and collect some info from user entered into a entry box. That function is a button command. When i click button nothing comes up except the error.
def addtrans(self):
    newWin = Toplevel(root)
        width = 600
        height = 400
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height,
                                (screenwidth - width) / 2, (screenheight - height) / 2)
        newWin.geometry(alignstr)
        newWin.resizable(width=False, height=False)
        self.lbl1 = Label(newWin, text="Enter amount in Euros :", fg='red')
        self.lbl1.place(x=150 , y=50)
        self.euros = Entry(newWin, width=20)
        self.euros.place(x=300, y=50)
        self.lbl2 = Label(newWin, text="CATEGORY :", fg='green')
        self.lbl2.place(x=150 , y=80)
        self.cat_entry = Entry(newWin, width=20)
        self.cat_entry.place(x=299, y=80)
        self.place_entry = Label(newWin, text=" ENTER NAME OF PLACE :")
        self.place_entry.place(x=140, y=120)
        self.txtfld2 = Entry(newWin, width=20)
        self.txtfld2.place(x=299, y=120)
        self.submit_btn=Button(newWin, text="SUBMIT RECORD TO DATABASE", command=submit)
        self.submit_btn.place(x=280, y=160)

A: Assumptions your code like this:
class Example(object):
    def __init__(self, root, command):
        self.root = root
        self.command = command

    def addtrans(self):
        root = self.root
        command = self.command
        newWin = Toplevel(root)
        width = 600
        height = 400
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height,
                                (screenwidth - width) / 2, (screenheight - height) / 2)
        newWin.geometry(alignstr)
        newWin.resizable(width=False, height=False)
        self.lbl1 = Label(newWin, text="Enter amount in Euros :", fg='red')
        self.lbl1.place(x=150 , y=50)
        self.euros = Entry(newWin, width=20)
        self.euros.place(x=300, y=50)
        self.lbl2 = Label(newWin, text="CATEGORY :", fg='green')
        self.lbl2.place(x=150 , y=80)
        self.cat_entry = Entry(newWin, width=20)
        self.cat_entry.place(x=299, y=80)
        self.place_entry = Label(newWin, text=" ENTER NAME OF PLACE :")
        self.place_entry.place(x=140, y=120)
        self.txtfld2 = Entry(newWin, width=20)
        self.txtfld2.place(x=299, y=120)
        self.submit_btn=Button(newWin, text="SUBMIT RECORD TO DATABASE", command=command)
        self.submit_btn.place(x=280, y=160)

You could instantiate and call like this:
import tkinter

win = tkinter.Tk()
example = Example(win, lambda: print("submit!"))
example.addtrans()
win.mainloop()

If you click "SUBMIT RECORD TO DATABASE" button it will print "submit!"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run cakephp code as a localhost? Instead of http://localhost/cakephp I'm able to run my code as http://localhost/CakePHP but I need to run this as http://localhost.
For this, I moved my all files of CakePHP project (/var/www/html/CakePHP) to /html directory and remove empty "CakePHP" directory. Now my whole code placed in html directory.
but getting the following message:
URL rewriting is not properly configured on your server.
I have enabled the rewrite module. Please check my .htaccess file directive, Am I do anything wrong?
1st File: cat /var/www/html/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

2nd File: cat /var/www/html/webroot/.htaccess
<IfModule mod_rewrite.c>
    RewriteEngine On
   # RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

A: Your htaccess in your root directory should look like the following
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^(\.well-known/.*)$ $1 [L]
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>


text:
Q: Universal Windows 10 Emulator not starting up OS The Windows phone emulator running Windows 10 has been working since I've installed it and last time I used the emulator was a few days ago. Now for some reason when I load my application emulator does not load the OS.
here's the steps I go throuogh to run the app :
-Run "Mobile Emulator 10.0.10586.0 720p 5 inch 1GB (which is my usual emulator to run)"

*

*Message box saying "Configuring  Windows Phone for debugging ... "

*Another message box appears saying "Click "Retry" to run the emulator in elevated mode. :

You do not have permission to modify internal Hyper-V network adapter settings, which are required to run the emulator

*

*Click retry on the message box

*"Are you sure you want to run Windows Phone Packages?" Click Yes

*Configuring Windows Phone for debugging box still running

*Phone emulator runs but stuck on "OS is starting..."

*Message box appears after leaving it running for roughly 15 mins :

"The emulator is unable to connect t the device operation system :
  Couldn't set up the UDP port. Some Functionality might be disabled.
  will add this to the steps"

I've followed the instructions from forums to go to Hyper-V Manager and delete the virtual switches and virtual machines - which doesn't work. And I also have Hyper-V enabled on windows features.
Any other solutions would be appreciated, Thanks in advance!
UPDATE : so I've left it running just to see if it works eventually, now another message box appears saying :

The emulator is unable to connect to the device operation system : Couldn't set up the UDP port. Some functionality might be disabled.

UPDATE : So I managed to fix it .. a little. It works for the other apps I have as well as newly created universal windows projects. But this specific app doesn't . I notice that this specific one has the "Configuring Windows Phone for debugging" message pop up whereas the other ones don't.

A: Why not start fresh?
New OS, new install, everything from scratch.
And don't forget to not play with UAC, OS permissions, the firewall, and do not install anything which would install virtual network adapters. Like OpenVPN, USB modems (including an iPhone), etc.
This is a solution, because your problem could be anything.


text:
Q: I am utilizing customtkinter to create a toplevel, but when I try to run it as toplevel and not with main.loop(), it crashes with error I am working on a GUI program utilizing tkinter and customtkinter. I seem to be getting an annoying error while trying to create this popUpBox. Essential I use it during a script run to open up a pop up box with radio buttons to make a selection. It works fine if I mainloop it, but if i try to run it in the main GUI with mainloop, it crashes, and if I try to run it as topLevel, I get the error at the bottom.
import tkinter
import customtkinter

class equipPopUp(customtkinter.CTkToplevel):
    def __init__(self,titleName,staff,labelFound=''):
        super().__init__()
        self.rfrBTNList=[]
        self.printBTNList=[]

        self.labelFound = labelFound
        self.staff = staff

        if self.staff == 0:
            self.status = 'Student'
        elif self.staff == 1:
            self.status = 'Staff'

        self.titleName = titleName

        #### Main Window ###
        self.title(f"{titleName}")
        window_width = 750
        window_height = 600
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()
                # find the center point
        center_x = int(screen_width/2 - window_width / 2)
        center_y = int(screen_height/2 - window_height / 2)
        self.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

        self.btn1 = tkinter.StringVar()
        self.btn2 = tkinter.StringVar()
        self.btn3 = tkinter.StringVar()

        self.label_radio_group = customtkinter.CTkLabel(master=self,
                                                        text="Please Select Request Equipment:")
        self.label_radio_group.grid(row=0,column=0,sticky='nw')

        if self.labelFound == 'N':
            z = 0
            Equipment_Requested = ["Print Return Label at SCA", "Email Electronic Return Label", "Email Electronic Return Label"]
            for i in Equipment_Requested:
                z+=1
                self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                                text= i,
                                                                variable=self.btn3,
                                                                value=z)
                self.radio_button.grid(row=z,column=0,sticky='nw')

            x = 0
            Equipment_Requested = [f"Replacement {self.status} Kit", f"Replacement {self.status} Printer", "Charger"]
            for i in Equipment_Requested:
                x+=1
                self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                                text= i,
                                                                variable=self.btn1,
                                                                value=x,
                                                                command=self.submitButton)
                self.radio_button.grid(row=x,column=1,sticky='nw')
        else:
            x = 0
            Equipment_Requested = [f"Replacement {self.status} Kit", f"Replacement {self.status} Printer", "Charger"]
            for i in Equipment_Requested:
                x+=1
                self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                                text= i,
                                                                variable=self.btn1,
                                                                value=x,
                                                                command=self.submitButton)
                self.radio_button.grid(row=x,column=0,sticky='nw')

    def createLabelBtns(self):
        y=0
        ra=self.label_radio_group2 = customtkinter.CTkLabel(master=self,
                                                        text="Please Select Reason for Return:")
        self.label_radio_group2.grid(row=0,column=2,sticky='nw')
        self.rfrBTNList.append(ra)
        rlm = ["Print Return Label at SCA", "Email Electronic Return Label", "Email Electronic Return Label"]
        for i in rlm:
            y+=1
            rb=self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                            text= i,
                                                            variable=self.btn3,
                                                            value=y)
            self.radio_button.grid(row=y,column=2,sticky='nw')
            self.rfrBTNList.append(rb)

    def createRFRBtns(self):
        y=0
        ra=self.label_radio_group2 = customtkinter.CTkLabel(master=self,
                                                        text="Please Select Reason for Return:")
        self.label_radio_group2.grid(row=0,column=2,sticky='nw')
        self.rfrBTNList.append(ra)
        equipment_reason_for_return = ["Display", "OS/MB", "Keyboard", "Camera", "Audio/Mic", "Battery", "Physical Damage"]
        for i in equipment_reason_for_return:
            y+=1
            rb=self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                            text= i,
                                                            variable=self.btn2,
                                                            value=y)
            self.radio_button.grid(row=y,column=2,sticky='nw')
            self.rfrBTNList.append(rb)

        self.my_button = customtkinter.CTkButton(master=self, text="Submit", command = self.destroy)
        self.my_button.grid(row=8,column=2,sticky='nw')

    def createPrinterChoices(self):
        y=0
        ra=self.label_radio_group3 = customtkinter.CTkLabel(master=self,
                                                        text="Please Select Reason for Return of Printer:")
        self.label_radio_group3.grid(row=0,column=2,sticky='nw')
        self.printBTNList.append(ra)
        equipment_reason_for_return = ["Hardware", "Software"]
        for i in equipment_reason_for_return:
            y+=1
            rb=self.radio_button = customtkinter.CTkRadioButton(master=self,
                                                            text= i,
                                                            variable=self.btn2,
                                                            value=y)
            self.radio_button.grid(row=y,column=2,sticky='nw')
            self.printBTNList.append(rb)

        self.my_button = customtkinter.CTkButton(master=self, text="Submit", command = self.destroy)
        self.my_button.grid(row=8,column=2,sticky='nw')

    def submitButton(self):
        if self.btn1.get()=='1':
            for widget in self.printBTNList:
                widget.grid_remove()
            self.createRFRBtns()
        if self.btn1.get()=='2':
            for widget in self.rfrBTNList:
                widget.grid_remove()
            self.createPrinterChoices()
        if self.btn1.get()=='3':
            for widget in self.rfrBTNList:
                widget.grid_remove()
            for widget in self.printBTNList:
                widget.grid_remove()
            self.my_button = customtkinter.CTkButton(master=self, text="Submit", command = self.returnStuff)
            self.my_button.grid(row=8,column=2,sticky='nw')

    def submitButton2(self):
        self.destroy

    def printSubmitBTN(self):
        # print("Printer"+self.btn2.get())
        pass

    def returnStuff(self):
        return self.btn1.get(),self.btn2.get(),self.btn3.get()

    def start(self):
        self.mainloop()
        print(type(self.btn1.get()))
        print(type(self.btn2.get()))
        print(type(self.btn3.get()))
        return self.btn1.get(),self.btn2.get(),self.btn3.get()

The error I am receiving is
rlm,ERI,RFRI = equipPopUp('Equipment Requested',staff,'N')
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1652, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str

I am using
staff=1
rlm,ERI,RFRI = equipPopUp('Equipment Requested',staff,'N')

I can't figure out what is causing it. I have looked into that particular error, and from what I gather, somewhere I am supposedly trying to mix a str and int but I simply can't figure out where it think's I am doing that.
I am using python version 3.9.13

A: The problem is this line:
rlm,ERI,RFRI = equipPopUp('Equipment Requested',staff,'N')

I don't know why you think equipPopUp(...) is returning a tuple. Since it's a class, it's returning a single object. Trying to convert the result to a tuple is causing the error.
You can get the exact same error on the second line of this code:
popup = equipPopUp('Equipment Requested',staff,'N')
rlm,ERI,RFRI = popup

So, to make the error go away, don't try to convert the instance of equipPopUp to a tuple.


text:
Q: Django CreateView- ModelForm with many-to-many InlineFormset ValueError I'm struggling with such a problem:
I have models:
class ForecastType(models.Model):
    client = models.ForeignKey(Client, related_name="weatherforecast_client")

    created_by = models.ForeignKey(Forecaster, related_name="weatherforecast_created_by")
    modified_by = models.ForeignKey(Forecaster,
                                    related_name="weatherforecast_modified_by",
                                    blank=True,
                                    null=True)

    creation_date = models.DateTimeField(auto_now_add=True)
    modification_date = models.DateTimeField(auto_now=True)

    weather_forecasts = models.ManyToManyField('WeatherForecast')

    STATUS_CHOICES = (
        ("D", "Draft"),
        ("A", "Active"),
        ("H", "History"),
    )
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default="D")

class OneDayForecast(ForecastType):
    def __str__(self):
        return f"Prognoza pogody dla: {self.client}, wykonana dnia: {self.creation_date}"

class WeatherForecast(models.Model):
    begin_date = models.DateTimeField(blank=True, null=True)
    finish_date = models.DateTimeField(blank=True, null=True)
    forecast_type = models.ForeignKey('ForecastType', null=True, blank=True)
    description = models.TextField(max_length=300, blank=True, null=True)

I also have ModelForm and InlineFormset:
class OneDayForecastForm(ModelForm):
    class Meta:
        model = OneDayForecast
        exclude = ('weather_forecasts',)

WeatherForecastFormset = inlineformset_factory(OneDayForecast, WeatherForecast, exclude=('forecast_type',), extra=2)

and finally an CreateView:
class OneDayForecast(ForecasterRequiredMixin, CreateView):
    template_name = "forecaster/one_day.html"
    success_url = reverse_lazy("forecaster:dashboard")
    model = OneDayForecast
    form_class = OneDayForecastForm

    def get(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        weather_forecast_form = WeatherForecastFormset()
        return self.render_to_response(
            self.get_context_data(form=form, weather_forecast_form=weather_forecast_form)
        )

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        weather_forecast_form = WeatherForecastFormset(self.request.POST)
        if form.is_valid() and weather_forecast_form.is_valid():
            return self.form_valid(form, weather_forecast_form)
        else:
            return self.form_invalid(form, weather_forecast_form)

    def form_valid(self, form, weather_forecast_form):
        self.object = form.save(commit=False)

        for weather_form in weather_forecast_form:
            weather_object = weather_form.save()
            self.object.weatherforecast_set.add(weather_object)

        self.object.save()
        form.save_m2m()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, weather_forecast_form):
        return self.render_to_response(
            self.get_context_data(form=form, weather_forecast_form=weather_forecast_form)
        )

After trying to submit my Form with it's InlineFormset I receive this error:
Request Method: POST
Request URL:    http://localhost:8000/forecaster/my-clients/6/one_day/
Django Version: 1.11
Exception Type: ValueError
Exception Value:
Unsaved model instance <OneDayForecast: Forecast for: client1> cannot be used in an ORM query.

Problem probably lies in commit=False in form_valid method but I have no clue how to repair it.
Does anyone know to solve this?
Thanks.

A: Okay, so I think that there are a couple problems here, both in your post and form_valid() methods.  I've referred to my own implementations of inline formsets to see what you do differently.
First of all, I believe that the first line of the post method should be self.object = self.get_object().
Second, weather_forecast_form = WeatherForecastFormset(self.request.POST) should be weather_forecast_form = WeatherForecastFormset(self.request.POST, instance=self.object).
Notice the relationship here between the object we get and then using it at the instance in the formset.  That's all for the post method.
Now, in my own implementation, I have many formsets, so I loop through each formset as follows (you can use exactly the same code if you put your formset into a list and pass it to form_valid):
def form_valid(self, form, formsets):
    self.object = form.save()
    for formset in formsets:
        formset.instance = self.object
        formset.save()
    return HttpResponseRedirect(self.get_success_url())

Notice that we fully save the parent form here, including committing it.  We then save all formsets.  If you wanted to keep your single formset, you can easily change the above code to the following:
def form_valid(self, form, weather_forecast_form):
    self.object = form.save()
    weather_forecast_form.instance = self.object
    weather_forecast_form.save()
    return HttpResponseRedirect(self.get_success_url())

The error that you report at the bottom of your question is a direct result of form.save(commit=False). What is happening there is that you are "pretend" saving the parent, and then trying to fully save the children.  The database doesn't have record of the parent, so it spits out that error.  Committing before saving many to many records is a must (at least in my experience).


text:
Q: When creating a new Rails application, why is there a Gemfile.lock file without running bundle install? And, how does the system install all the gems for the application without going through the bundle install process?
Note: This question is about the process of creating a new application. Not the same question as In Rails, why there is a new Gemfile.lock when no bundle or bundle install was run? (and a new Gemfile timestamp too) .

A: Gemfile.lock is a snapshot of the gems and their versions created when you run bundle install.  As explained in the Checking Your Code into Version Control section of the Bundler rationale:

Gemfile.lock makes your application a single package of both your own
  code and the third-party code it ran the last time so you know for sure
  that everything worked. Specifying exact versions of the third-party
  code you depend on in your Gemfile would not provide the same
  guarantee, because gems usually declare a range of versions for their
  dependencies.

Gems can be installed outside of bundler by RubyGems (e.g. gem install gem_name) but it's best to use RVM which allows you to install separate versions of Ruby and manage individual gemsets for each application as explained in the RVM best practices.

A: When you do rails new <app>, as part of setup it runs bundle install for you.


text:
Q: USQL Extract subset of files I have a USQL question. I have a daily job that is outputting files to a directory in the following format
/MyOutput/{YYYY}/{MM}/{DD}/file.csv
I have a second job now that I want to run that will use the most recent 30 files produced by the first job. I can't figure out how to best do this though.
I know I can do wildcards in the extractor but I prefer not to extract all files and then use a select/where to remove the ones I don't want as extracting all files could get really costly if I'm keeping years worth of these files.
So is there a nice way in usql to say extract only the most recent x files? Or what options do I have here?
Thanks,
John

A: If you use a date pattern it will do what you want.
@rows =
    EXTRACT
      ...,
      date DateTime
    FROM /MyOutput/{date:YYYY}/{date:MM}/{date:dd}/file.csv;

SELECT * FROM @rows WHERE date > '2018-5-3'

Will read only the files matching the date range - it won't read all of them in first.


text:
Q: sending mail to any website using java servlet I am using javamail api in java servlet to send mail. It seams to send mail only to gmail Id's, whereas I want it to be able to send to any email ID. Do I require different property value here? I followed http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ to develop the code. The property values are:
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");

A: No , There is no need to change configurations what you have ,Here it will act as server(Gmail) from there you can send mail to any mail servers(yahoo,hotmail and etc..).

A: You can send mail to any email ids. You can mention them in TO address or CC or BCC, check your authentications are correct.
Here is an detailed example from an existing post how to send an email from jsp/servlet?
Hope this can help you


text:
Q: Get data from two tables and insert in one table through HQL I have two entity classes Student.java and Course.java and they have many to many relationship between them I want to add one entry into their @JoinTable through hql like this :
insert into student_course(student_id,course_id) values('" + courseId + "','" + studentId + "')".

I want to use hql instead of sql. Any ideas?

A: You can try a solution like this
 insert into student_course(student_id,course_id)
 select c.student_id,c.course_id from Student s join s.Course c


text:
Q: Can't replace an item inside of an array Wrighting an Angular application.
In this code I'm trying to replace an item at a specific number in array.
for (i=0;i<this.marked.length;i++) {
    this.index = this.marked[i].ind;
    this.newSongs[this.index] = this.marked[i].name;
}

This is what this.marked looks like:
{
    ind: index,
    name: songName
}

So why the result is this?
['name1', 2: 'name3']

instead of:
['name1', 'name2', 'name3']

Sorry, guys, it's actually this.marked[i].ind;
I deleted it accidentally. The problem isn't solved

A: I think you just need to replace
this.index = this.marked[i]

by
this.index = this.marked[i].ind

A: Khalid and Joel gave you the right tip. You need to use:
this.index = this.marked[i].ind

Here's a angularJs fiddle for you. Hope this will help
https://jsfiddle.net/trollr/3adngkmx/
function SongCtrl($scope) {
  $scope.songs = [
        {
            ind: 1,
            name: "Tessie"
        },
        {
            ind: 2,
            name: "Kiss Me I'm Shitfaced"
        },
        {
            ind: 3,
            name: "The State of Massachusets"
        }
    ];

    $scope.replace = function(index, value) {
        for (i=0;i<$scope.songs.length;i++) {
            var currentIndex = $scope.songs[i].ind;
            if(currentIndex == index) {
                 $scope.songs[i].name = value;
            }
        }
    }
}

A: I noticed that I was trying to run my code inside of a loop. So when I pulled it out It worked correctly.


text:
Q: ts(2339) Error with Generic useFetchData hook I have a problem with my useFetchData hook when I want to make it generic. Everything is fine if there are explicit types, but after turn it into generic function, I got an error in one place: "Property 'data' does not exist on type 'unknown'."
Here are my types
interface User {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  avatar: string;
}

type Users = User[];

export interface People {
  page: number;
  per_page: number;
  total: number;
  total_pages: number;
  data: Users;
  support: {
    url: string;
    text: string;
  };
}

Here is the hook itself
function useFetchData<DataType, ResponseType>(
  url: string
): {
  dataX: DataType | null;
  done: boolean;
} {
  const [dataX, setDataX] = useState<DataType | null>(null);
  const [done, setDone] = useState(false);

  useEffect(() => {
    fetch(url)
      .then((resp) => resp.json())
      .then(({ data }: ResponseType) => { //here is the error
        setDataX(data);
        setDone(true);
      })
      .catch((err) => {
        throw new Error(err);
      });
  }, [url]);

  return {
    dataX,
    done,
  };
}

function CustomHookComponent() {
  const { dataX, done } = useFetchData<Users, People>(
    'https://reqres.in/api/users?page=2'
  );

  return (/*some stuff*/)
}

A: You need to tell TypeScript that ResponseType has a data property which you do with Generic Constraints
So your function declaration would be something like:
function useFetchData<DataType, ResponseType extends {data: DataType}>(
  url: string
): {
  dataX: DataType | null;
  done: boolean;
} {
  // more code here
}


text:
Q: Bootstrap 4 Tabs inside drop-down menu I am using boostrap 4 drop down menu with tabs inside. Here is the codepin
I found this link useful to stop click event propagation so that the drop down menu does not close on click inside itAvoid dropdown menu close on click inside

But clicking on tabs does not work.
  code pin:boostrap 4 tabs inside drop down menu
is there any solution or another approach so that tabs work inside drop down menu

HTML

     Navbar

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
</button>

                 Home

                     (current)

                 Features

                 Pricing

                 Dropdown link

                                 –A–

                                 –B–

                                 –C–

                                         Collapsible Group Item A

                                    [Tab content A]

                                         Collapsible Group Item B

                                    [Tab content B]

                                         Collapsible Group Item C

                                    [Tab content C]

JS
$('.dropdown-menu').on("click.bs.dropdown", function (e) { e.stopPropagation(); e.preventDefault(); });

Is there possible solution ?

A: The simplest way is to wrap it inside a form since the form will prevent the Dropdown from closing on click...

    ...

             <form>

                      Dropdown link

                     ....

            </form>

    ...

https://www.codeply.com/go/GzekeuWnSg
The other method is using jQuery to like this:
$('.dropdown-menu .nav-tabs .nav-link').on("click.bs.dropdown", function (e) {
    $(this).tab('show');
    e.stopPropagation();
});

https://www.codeply.com/go/iEDxVGTzAZ


text:
Q: Expected number of times a result comes up: Proof of formula If I am flipping a fair coin, and want to know the expected number of heads after $n$ flips, then I immediately know the answer is $\frac{n}{2}$. Similarly, with a fair die, the number of $5$'s that come up after $n$ rolls is on average $\frac{n}{6}$. Presumbably, the general form of this rule is as follows:
$$
\text{Expected number of times a result comes up}=P(\text{result}) \times\text{Number of trials}
$$
This is much less labour intensive than working out the weighted average in another way. To compute the average number of $5$'s that come up after $n$ rolls, I could work out:
$$
\left(P(\text{Zero $5$'s coming up}) \times0\right)+\left(P(\text{One $5$ coming up}) \times1\right)+\left(P(\text{Two $5$'s coming up}) \times2\right)+...+\left(P(\text{$n$ $5$'s coming up}) \times n\right)
$$
Is it possible to use this second, more labour intensive result, to prove the first?

A: Yes it's definitely possible. The number of 5s in $n$ rolls of a dice will follow a binomial distribution with parameters $n$ and $1/6$. This means that for $k \leq n$,
$$
\mathbb{P}(X = k) = \binom{n}{k}p^k(1-p)^{n-k},
$$
where $p = 1/6$. So then you can look at
\begin{align}
\mathbb{E}(X) &= \sum_{k=0}^n \binom{n}{k}p^k(1-p)^{n-k} k.
\end{align}
Write out the binomial coefficient
$$
\binom{n}{k} = \frac{n!}{(n-k)!k!}
$$
and then take out a factor of $np$ to get:
\begin{align}
&n p\sum_{k=1}^n \frac{(n-1)!}{(k-1)!(n-k)!}p^{k-1}(1-p)^{n-k}.
\end{align}
Now we will re-write the sum over an index $j = k-1$. So when $k=1$, we get $j=0$. And when $k=n$, we get $j=n-1$ (after all there are only $n$ terms in the sum however we write it). So we get
\begin{align}
& n p\sum_{j=0}^{n-1} \binom{n-1}{j}p^{j}(1-p)^{n-1 -j}  \\
&= n p\bigl(p + (1-p)\bigr)^{n-1}  \\
&= np.
\end{align}


text:
Q: Why the column type still "object" after I change it to numeric? I need to convert the type of the column "sentiment" into numeric in the dataframe 'auto_df_dropped'. After code pd.to_numeric(auto_df_dropped['sentiment']), nothing changing. It's still object? What's wrong here? Thanks!
Before conversion:
auto_df_dropped.info()

......sentiment 6861 non-null object......

After Conversion:
auto_df_dropped.info()

......sentiment 6861 non-null object......


text:
Q: Can't set up config.py in Flask I am trying to set up config.py for using CLIENT_ID and CLIENT_SECRET. This is not an error when these environments variable in def xxxx(). Then it is used as current_app.config('XXXX') but this can't be called outside def xxxx().
Error:

This typically means that you attempted to use functionality that needed
  to interface with the current application object in some way. To solve
  this, set up an application context with app.app_context().  See the
  documentation for more information.

auth.py
import functools
import pdb
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for, current_app
)
import slack
from app.db import (
    get_or_create_team, get_or_create_user, get_or_create_team_user
)
from flask_login import login_user, logout_user, current_user, LoginManager

bp = Blueprint('auth', __name__, url_prefix='/auth')
client_id = current_app.config['CLIENT_ID']
client_secret = current_app.config['CLIENT_SECRET']

config.py
# client
CLIENT_ID='XXXXXXXXXXXXXXXX'
CLIENT_SECRET='XXXXXXXXXXXXXXXX'

A: from:
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for, current_app
)

client_id = current_app.config['CLIENT_ID']
client_secret = current_app.config['CLIENT_SECRET']

to:
from os import environ

client_id = environ.get('CLIENT_ID')
client_secret = environ.get('CLIENT_SECRET')


text:
Q: Macro to associate vlookups on multiple cells with image clicks I am trying to develop a macro that after click on a picture, will do v-lookups on a bunch of cells in a given row.
For example:

*

*If I click on a cell in Row 10 and then I click on a picture of a poodle (located somewhere in the sheet, not in Row 10), row 10 will be populated with  "animal" in one cell, in the next cell "dog", and in the next cell "poodle"

*And then I click on a cell in Row 11, and then I click on a picture of a palm tree (located somewhere in the sheet), row 11  will be populated with "plant" in one cell, in the next cell "tree", and in the next cell "palm tree"
Any ideas?
Thanks!

A: Put some images on your sheet and in the Click event for each one, call the LookupSelection sub with the name of the item contained in the image:
Private Sub imgPalm_Click()
    LookupSelection ("Palm Tree")
End Sub

Private Sub LookupSelection(name As String)
    Dim lookupRange As Range
    Set lookupRange = Sheet1.Range("I3:K5") 'Range for vlookup
    Dim selectedRow As Integer
    selectedRow = Selection.Row
    Dim type1, type2 As String '

    type1 = Application.WorksheetFunction.VLookup(name, lookupRange, 2)
    type2 = Application.WorksheetFunction.VLookup(name, lookupRange, 3)

    Sheet1.Cells(selectedRow, 1) = name
    Sheet1.Cells(selectedRow, 2) = type1
    Sheet1.Cells(selectedRow, 3) = type2
End Sub

You need a lookup table somewhere (I used I3:K5). The finished thing should look something like this:

Good luck!

A: Create a macro in a regular module to handle the image clicks, and assign it to all of your images' "onaction" property using Right-click >> Assign macro  (or in code)
Sub ImageClick()
  Dim rngLookup As Range
  Dim ImgName As String
  ImgName = Application.Caller

  Set rngLookup = ThisWorkbook.Sheets("Lookup").Range("A2:D20")
  With Selection.Cells(1).EntireRow
    .Cells(1).Value = ImgName
    .Cells(2).Value = Application.VLookup(ImgName, rngLookup, 2, False)
    .Cells(3).Value = Application.VLookup(ImgName, rngLookup, 3, False)
    .Cells(4).Value = Application.VLookup(ImgName, rngLookup, 4, False)
  End With
End Sub

As Chris suggested, use a lookup table to fill the values in the selected row: in this case though it's based on the name of the image on the sheet.


text:
Q: Excel: return name of column with highest value in a non-continuous array I have looked up many answers to find the highest value in a column, and return the column name.  However, every answer is dependent on using a continuous array and uses the INDEX function.  This is not possible for me. I need to look at the values in 17 different columns, all 415 columns away from the next.  It looks something like this:
A B C D E F G H I J K L M N O
1 3 5----7 1 2----8 2 4----6 0 9
I need to compare the values in columns A, E, I and M and have it tell me that since I has a value of 8, Column I is my answer.  Then I need it to compare columns B, F, J, and N, and have it tell me column B is the highest column of that group.  And finally, that of columns C, G, K and O, column O is the highest.
I am doing this for 100 million cells, 17 groups, of 415 columns each for 14,300 rows.

A: I would recommend installing Microsoft PowerQuery. Then using it to write your column comparisons, creating a new sheet in the process. You will need a significant chunk of RAM available though for a large query like that.

A: to find the maximum value in A2, E2, I2 and M2 and then the header in row 1 for the matching column you could use this formula
=INDEX(CHOOSE({1,2,3,4},A$1,E$1,I$1,M$1),MATCH(MAX(A2,E2,I2,M2),CHOOSE({1,2,3,4},A2,E2,I2,M2),0))


text:
Q: call to undefined function error in php I am trying to get friend-list from facebook using Graph API and PHP I have tired  below code its showing error

Error : Undefined function d() in D:\xampp\htdocs\kenshinkan-new\kenshinkan\facebook.php on line 37

How to fix this error ?

<?php

    //facebook application configuration
    $fbconfig['appid' ] = "45675467245672462456262";
    $fbconfig['secret'] = "afdgadgdagdagadfg";

    try{
        include_once ('.\facebook-php-sdk-master\src\facebook.php');
    }
    catch(Exception $o){

        print_r($o);

    }
    $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
    ));

    $user       = $facebook->getUser();
    $loginUrl   = $facebook->getLoginUrl(
            array(
                'scope'         => 'email'
            )
    );

    if ($user) {
      try {
        $user_profile = $facebook->api('/me');
        $user_friends = $facebook->api('/me/friends');
        $access_token = $facebook->getAccessToken();
      } catch (FacebookApiException $e) {
        d($e);
        $user = null;
      }
    }

    if (!$user) {
        echo "";
        exit;
    }

    $total_friends = count($user_friends['data']);
    echo 'Total friends: '.$total_friends.'.
';
    $start = 0;
    while ($start < $total_friends) {
        echo $user_friends['data'][$start]['name'];
        echo '
';
        $start++;
    }

?>

A: Your error is right here..
catch (FacebookApiException $e) {
        d($e);  //This is your error. What do you suppose function d() would do?
        $user = null;
      }

A: Well, either adding the d() function, or removing the d($e); call to the function (which is not there)?
Also, you'll only be able to retrieve those friends which are also using your app, not all.

A: It looks like d() - is a short-hand function to dump/log exception.
It's definitely created by that person, who's code you took :)
You can remove this line or define that function. Could be smth like:
function d($e) {
  error_log($e->getMessage());
}

error_log() — Send an error message to the defined error handling routines (see http://php.net/manual/en/function.error-log.php)


text:
Q: AS2, Referencing a Changing Object Name so I was wondering if there was a way to reference different objects on stage with he same method to save repeating lots of lines of code. This is what I have right now
function bossKilled(i:Number):Void {
  trace("Boss Killed!");
  kills ++;
  _root.bossDeath.gotoAndPlay(2);
  _root["pirate"+i+"Active"] = false;  //name of variable would be pirate1Active
  _root["pirate"+(i+1)+"Active"] = true;  //name of variable would be pirate2Active
  bossDeath._x = _root["pirate"+i+"Active"]._x;
  bossDeath._y = _root["pirate"+i+"Active"]._y; }

However, this reference does not actually affect the variables. I was wondering if this was possible, and if so, what am I doing wrong?
Thanks.

A: Not sure what you try to achieve ... pirate1Active is a BOOL. A BOOL has no _x or _y property (nor any other).
If you are not sure where to find your objects in the object tree, you can use the debugger or add some traces on the MCs timeline, like trace (_parent);
Consider switching to AS3, it is much more object oriented and has better tools support.


text:
Q: Making hamburger menu y-overflow: scroll when height exceeds vh I have a hamburger menu that displays when hovered over (when the site is less than 865px wide), but the issue I'm trying to work out right now is how to make the menu turn into a y-scroll when it overflows the vh, since it's position: sticky; you can notice when setting the page dimensions to be that of a mobile phone, that the hamburger menu overflows the vh, but I can't figure out how to get it to scroll when overflowing since its sticky.
Suggestions?
see code:
#header {
    display: grid;
    position: sticky;
    top: 0;
    grid-template-columns: 20% 80%;
    grid-template-rows: 50% 50%;
    width: 100vw;
    height: 7rem;
    z-index: 10;
    horizontal-overflow: hidden;
    background-color: black;
}
.headerLogo {
    grid-area: 1 / 1 / 3 / 2;
    align-self: center;
    margin-left: 1rem;
    height: 4.8rem;
}
#hamburger {
    align-self: center;
    justify-self: end;
    grid-area: 1 / 2 / 3 / 3;
    height: 3.25rem;
    padding: 2rem 1.5rem;
}
#header a:hover {
        color: lightgray;
}
#header a {
        text-decoration: none;
        color: white;
}

@media only screen and (min-width: 865px) {

    /* Primary Larger Menu */
    #menu1 {
        grid-area: 2 / 2 / 3 / 3;
        justify-self: end;
        margin-top: 0.5rem;
        margin-right: 2.5rem;
        display: grid;
        grid-template-rows: 2rem 3rem;
        grid-template-columns: 5rem 5rem 7rem 6rem 5.5em 6rem;
        align-items: center;
        justify-items: center;
    }
    .menu1 {
        padding-bottom: 1rem;
    }
    #mmObj1 {
    grid-area: 1 / 1 / 2 / 2;
    }
    #mmObj2 {
    grid-area: 1 / 2 / 2 / 3;
    }
    #mmObj3 {
    grid-area: 1 / 3 / 2 / 4;
    }
    #mmObj4 {
    grid-area: 1 / 4 / 2 / 5;
    }
    #mmObj5 {
    grid-area: 1 / 5 / 2 / 6;
    }
    #mmObj6 {
    grid-area: 1 / 6 / 2 / 7;
    }
    .dropdownGrid {
        align-self: start;
        display: grid;
        background-color: black;
        align-items: center;
        justify-items: center;
        visibility: hidden;
    }
    #techDropdown {
        grid-area: 2 / 3 / 3 / 4;
        width: 6.5rem;
        grid-template-columns: 6.5rem;
        grid-template-rows: 2.2rem 2.2rem 2.2rem 2.2rem;
    }
    #mmObj3:hover ~ #techDropdown {
        visibility: visible;
    }
    #techDropdown:hover {
        visibility: visible;
    }
    #serviceDropdown {
        grid-area: 2 / 1 / 3 / 2;
        width: 11rem;
        grid-template-columns: 11rem;
        grid-template-rows: 2.2rem 2.2rem 2.2rem;
    }
    #mmObj1:hover ~ #serviceDropdown {
        visibility: visible;
    }
    #serviceDropdown:hover {
        visibility: visible;
    }
    #marketsDropdown {
        grid-area: 2 / 2 / 3 / 3;
        width: 12rem;
        grid-template-columns: 12rem;
        grid-template-rows: 2.2rem 2.2rem 2.2rem 2.2rem 2.2rem 2.2rem 2.2rem 2.2rem;
    }
    #mmObj2:hover ~ #marketsDropdown {
        visibility: visible;
    }
    #marketsDropdown:hover {
        visibility: visible;
    }
    #hamburger {
        visibility: hidden;
    }
}

/* Secondary Smaller Menu Above Primary*/
.menu2 {
    grid-area: 1 / 2 / 2 / 3;
    justify-self: end;
    align-self: start;
    margin-top: 1rem;
    margin-right: 3rem;
    color: white;
}
.menu2 ul {
    margin: 0;
}
.menu2 li {
    font-size: 0.80rem;
    display: inline-block;
    padding-left: 0.5rem;
}
.menu2 p {
    font-size: 0.80rem;
}
.menu2 a {
    text-decoration: none;
    color: white;
}

/*mobile menu*/
@media only screen and (max-width: 865px) {
    #mmObj1 {
        grid-area: 1 / 1 / 2 / 2;
    }
    #mmObj2 {
        grid-area: 3 / 1 / 3 / 2;
    }
    #mmObj3 {
        grid-area: 5 / 1 / 6 / 2;
    }
    #mmObj4 {
        grid-area: 7 / 1 / 8 / 2;
    }
    #mmObj5 {
        grid-area: 8 / 1 / 9 / 2;
    }
    #mmObj6 {
        grid-area: 9 / 1 / 10 / 2;
    }
    #menu1 {
        grid-area: 3 / 2 / 3 / 3;
        align-self: start;
        justify-self: end;
        display: grid;
        grid-template-rows: 2.5rem 6.5rem 2.5rem 15rem 2.5rem 8rem 2.5rem 2.5rem 2.5rem;
        grid-template-columns: 15rem;
        align-items: center;
        justify-items: end;
        background-color: black;
        visibility: hidden;
    }
    .menu1 {
        margin-right: 1.5rem;
        font-size: 1.25rem;
    }
    .dropdownGrid {
        display: grid;
        align-self: start;
        align-items: center;
        justify-items: end;
        margin-right: 1.5rem;
        grid-template-columns: 12rem;
    }
    #serviceDropdown {
        grid-area: 2 / 1 / 3 / 2;
        grid-template-columns: 15rem;
        grid-template-rows: 1.75rem 1.75rem 1.75rem;
    }
    #tsubObj1 {
        grid-area: 1 / 1 / 2 / 2;
    }
    #tsubObj2 {
        grid-area: 2 / 1 / 3 / 2;
    }
    #tsubObj3 {
        grid-area: 3 / 1 / 4 / 2;
    }
    #hamburger:hover ~ #menu1 {
        visibility: visible;
    }
    #menu1:hover {
        visibility: visible;
    }
    #serviceDropdown {
        grid-area: 2 / 1 / 3 / 2;
    }
    #marketsDropdown {
        grid-area: 4 / 1 / 5 / 2;
        grid-template-rows: 1.75rem 1.75rem 1.75rem 1.75rem 1.75rem 1.75rem 1.75rem 1.75rem;
    }
    #techDropdown {
        grid-area: 6 / 1 / 7 / 2;
        grid-template-rows: 1.75rem 1.75rem 1.75rem 1.75rem;
    }
    .menu2 {
        visibility: hidden;
    }
}

        ###
        ###
        ###
        Our Work
        About Us
        Contact Us

            ###
            ###
            ###
            ###

            ###
            ###
            ###

            Market 1
            Market 2
            Market 3
            Market 4
            Market 5
            Market 6
            Market 7
            Market 8

 Blog

|

 Request a Quote

|

 Submit RFx

|

 24/7 Support: ###

codepen: https://codepen.io/roomwillow/pen/VwmMPoJ

A: You need to give a fixed-height to your menu1 container inside the mobile media query and then apply an overflow-y:scroll to it. So your additional css for mobile view menu1 will be something like :-
#menu1{
height:250px;
overflow-y:scroll;
}


text:
Q: Killing a process on a Windows machine How can I kill processes on a Windows machine? Ctrl + Alt + Del only works for the whole system, but I need it for a single process.

A: For Windows XP, Vista, 7:
Basic options overview:
If you know the name:
taskkill /IM (program).exe

If you know the PID:
taskkill /PID ###

Kill all processes by one user (Quinn in this instance):
taskkill /FI "USERNAME eq Quinn"

Taskkill options:

*

*/F - force kill with no confirmation

*/IM - by program name

*/PID - by process ID number

*/FI - by filter:
Filter Name     Valid Operators     Valid Value(s)
-----------     ---------------     --------------

STATUS          eq ne               RUNNING | NOT RESPONDING
IMAGENAME       eq ne               Image name
PID             eq ne gt lt ge le   PID value
SESSION         eq ne gt lt ge le   Session number
CPUTIME         eq ne gt lt ge le   CPU time in the format of hh:mm:ss.
MEMUSAGE        eq ne gt lt ge le   Memory usage in KB
USERNAME        eq ne               User name in [domain\]user format
MODULES         eq ne               DLL name
SERVICES        eq ne               Service name
WINDOWTITLE     eq ne               Window title

Modifiers:

*

*eq: equals

*ne: not equal

*gt: greater than

*lt: less than

*gt: greater than or equal

*le: less than or equal

A: Open task manager, go to the process Tab, highlight the process, hit "end process" button.

A: Besides the Windows Task Manager already suggested here,
I'll recommend keeping Process Explorer by Mark Russinovich handy.
It is more elegant as described in this How-To-Geek article.

it gives you so much more information than the default task manager, including a tree view of all the processes so you can see which processes launched other processes. You can look at pretty much every piece of data concerning a process, including associated registry key handles, open files, dlls. There's even a search function.

Also see the Wikipedia page, Process Explorer.
I always wonder why Microsoft has not yet replaced the default Task Manager with this yet.

A: Note the process ID of the process you wish to kill. From the command line type:
taskkill /PID PROCESS ID HERE

Or use Ctrl + Alt + Del and select it from the list.


text:
Q: Faliure to Use Cors in WebApi in .Net Core 3.1 I have a requirement to access my .NET Core 3.1 WebApi from an origin other than that which it is served from. However, when I follow the guidance from Microsoft I still get the following JavaScript error on the client-side:

Access to fetch at 'http://localhost:50679/merchants' from origin 'http://localhost:64237' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

In my Startup class, my ConfigureServices method looks like this:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins("http://localhost:64237");
                });
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        services.AddControllers();
    }

...and my Configure method looks like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

I have then used the EnableCors attribute on the controller method I am calling like so:
[EnableCors("CorsPolicy")]

I have seen several posts on StackOverflow concernaing Cors but none of the have helped as I have seen nothing I am doing incorrectly - however, most of them are not specific to .NET Core 3.1. I have also done a sense check and set breakpoints to check that all of the above code is being run.
Can anyone please explain why I am not able to use Cors in this situation please?

A: You can try removing the app.UseCors("CorsPolicy") and app.UseEndpoints(...) block from Startup.cs as it applies CORS policies to all the apps endpoints via CORS Middleware, whereas [EnableCors("CorsPolicy")] enables it over a controller, action method, etc.
Per Microsoft you should not use both approaches at the same time:

We recommend against combining policies. Use the [EnableCors]
  attribute or middleware, not both in the same app.

// Remove this piece of code
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

And also update your policy by using:
options.AddPolicy(
    "CorsPolicy",
    builder =>
    {
        builder.
            WithOrigins("http://localhost:64237").
            AllowAnyHeader().
            AllowAnyMethod();
    });

A: I suppose you should add some other permissions
builder.AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .WithOrigins("http://localhost:64237");


text:
Q: Battery monitoring with a NSTimer I've got problems monitoring battery. In the foreground I can only get the level once and it seems that I don't get the change in the background either.
If I put a new UIViewController in front of the one monitoring and then get back again the battery level is updated.
-(void)startMonitoringBattery
{
     [UIDevice currentDevice].batteryMonitoringEnabled = YES;

     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(batteryStateDidChange:)
                                                     name:UIDeviceBatteryStateDidChangeNotification
                                                   object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(batteryLevelDidChange:)
                                                     name:UIDeviceBatteryLevelDidChangeNotification
                                                   object:nil];

     batteryCheckTimer = [NSTimer scheduledTimerWithTimeInterval:(10.0)
                                                             target:self
                                                           selector:@selector(batteryCheck)
                                                           userInfo:nil
                                                            repeats:YES];
}

- (void)batteryStateDidChange:(NSNotification *)notification
{
     [self batteryCheck];
}

- (void)batteryLevelDidChange:(NSNotification *)notification
{
     [self batteryCheck];
}

When this method is called I want to get the current battery level and not the one that it was when I started monitor.
- (void)batteryCheck
{
     float STOP_AT_BATTERY_LEVEL = 50.0;
     float currentBatteryLevel = [UIDevice currentDevice].batteryLevel;

     if([UIDevice currentDevice].batteryLevel <= STOP_AT_BATTERY_LEVEL)
     {
          // STOP BATTERY CONSUMING TASK
     }
}

Questions:

*

*Why doesn't batteryStateDidChange and batteryLevelDidChange get called more than once?

*Why can't I get the current battery level, with a timer, from [UIDevice currentDevice].batteryLevel even if I've set batteryMonitoringEnabled to true?

*Is it possible to monitor battery while the app is in background or the phone is locked? The app is running in background because I record GPS data all the time.


text:
Q: generalisations of module maps For an algebra $A$ over a field $\mathbb{K}$, consider left modules $E,F$. The two obvious collections of maps to take from $E$ to $F$ are the left module maps ${}_A\mathrm{Hom}(E,F)$ and the linear maps ${}_\mathbb{K}\mathrm{Hom}(E,F)$. However, I am looking for another naturally defined collection of linear maps which are more general than module maps. Ideally these generalised maps should have some sort of categorical structure. They could be dependent on choosing some additional structure on $A$. Is there any such construction in the literature?
This question is motivated by noncommutative geometry, starting with the 1-forms $\Omega^1$ on an algebra. There we can consider the right vector fields $\mathcal{X}^R=\mathrm{Hom}(\Omega^1,A){}_A$ and the left vector fields $\mathcal{X}^L={}_A\mathrm{Hom}(\Omega^1,A)$. However for a star algebra the natural idea of a real (self adjoint) vector field (e.g. considered as a deformation of a smooth manifold) does not fit in either of these cases, but possibly in some intermediate case between being a right and a left module map. In fact the star operation swaps right and left vector fields, but the intersection of these right and left vector fields is too small to be useful.


text:
Q: Django schedule: Difference between event.get_occurrence() and event.get_occurrences()? Based on django-schedule. I can't find the guy who made it.
Pardon me if I'm missing something, but I've been trying to get an events occurrences, preferably for a given day.
When I use event.get_occurrence(date), it always returns nothing. But when I use event.get_occurrences(before_date, after_date), suddenly the occurrences on the previously attempted date show up.
Why won't this work with just one datetime object?

A: This difference is probably in the actual design of these two methods. Frankly, get_occurrence is rather flawed, in general. A method like this should always return something, even if it's just None, but there's scenarios where it doesn't return at all. Namely, if your event doesn't have an rrule, and the date you passed get_occurrence isn't the same as your event's start, then no value is returned.
There's not really anything that can be done about that. It's just flawed code.

A: Based on the above comment especially in the case when the event doesn't return and occurrence, the following snippet below can force the retrieval of an occurrence especially when you are sure that it exists
from dateutil.relativedelta import relativedelta

def custom_get_occurrence(event,start_date):
    occurrence = event.get_occurrence(start_date)
    if occurrence is None:
        occurrences = event.get_occurrences(start_date, start_date+relative_delta(months=3)
        result = filter(lambda x: x.start==start_date,occurrences)
        occurence = result[0]

The above code resolves issue that might occur when the default get_occurrence doesn't return a result.


text:
Q: Excel database values to SQL Server and different tables I got an Excel file with data which I want to import into a database in Microsoft SQL Server 2008 Express edition.
I do this with right click on a database -> task -> import data.
After this, my data from Excel is loaded in the database in one table.
But I want to seperate the columns from the Excel file into different tables.
So instead of loading all Excel data into one database and table, I want to load the Excel data into one database, but in different tables.
For example: Save column 1,2,3 from Excel in table A, and save column 4,5,6 from Excel in table B.
Anyone that knows how to do this?

A: I followed the suggestion of @bendataclear:
"Personally I would just import into a temporary table then write INSERT INTO X SELECT queries to move in the correct columns."


text:
Q: How do I format [future, non-current] dates in Eleventy + Nunjucks? I'm building a site with a CMS (Netlify) for a local band, and they have future gig dates they will put on the site. So far the dates show up as very long non-formatted strings that include the time and time zone. I'm trying to figure out how to format the dates to be simpler (day, date, time for example).
I've tried plugins like nunjucks-date but I'm a little confused about how to use a plugin (and filters) in this case.
My repo: https://github.com/mollycarroll/serapis-eleventy-2
Example gig entry:
---
layout: gig
venue: Cedar Lake Cellars
date: 2022-05-28
time: 6pm
city: Wright City, MO
---

Gig template:

{{ venue }}

{{ city }} {{ date }} {{ time }}

config.yml for the CMS:
  - name: 'gigs'
    label: 'Shows'
    folder: 'src/gigs'
    create: true
    slug: '{{month}}-{{day}}-{{venue}}'
    fields:
    - { label: 'Layout', name: 'layout', widget: 'hidden', default: '_includes/gig.njk' }
    - { label: 'Date', name: 'date', widget: 'date', default: '' }
    - { label: 'Time', name: 'time', widget: 'string', default: '' }
    - { label: 'Venue', name: 'venue', widget: 'string', default: '' }
    - { label: 'City', name: 'city', widget: 'string', default: '' }

Thanks for any help.

A: First, you should create a filter, let's say src/filters/date.js with the following content:
const { DateTime } = require("luxon");

// Add a friendly date filter to nunjucks.
// Defaults to format of LLLL d, y unless an
// alternate is passed as a parameter.
// {{ date | friendlyDate('OPTIONAL FORMAT STRING') }}
// List of supported tokens: https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens

module.exports = (dateObj, format = 'LLLL d, y') => {
  return DateTime.fromISO(dateObj, { zone: "Europe/Amsterdam", locale: "en" }).toFormat(format);
};

Make sure you check Luxon documentation for details. Then add the filter in .eleventy.js:
module.exports = function(eleventyConfig) {
  ...
  eleventyConfig.addFilter("date", require("./src/filters/date.js"));
  ...
};

Now you can use it in Nunjacks with a default value {{ date }}, in this example 'LLLL d, y', or any value you need at a certain position on your website {{ date | date('dd. LLLL yyyy.') }}. This can be very useful if you need at some point just month and year or just day and month.
You can even create multiple language filters, like dateEn.js and dateDe.js, and format each to its own language if you have a multilingual site.
Hope this helps.
EDIT: In order for this filter to work the dateObj should be in ISO 8601 format.


text:
Q: What does \ mean while calling a function in C? I was looking some code, and saw that it used a \ to separate lines while calling a function, does this mean something? Or is it just to be more readable?
        function(\
        lets_say_this_a_long_attribute, \
        and_this_is_another_attribute_with_a_long_name_or_operations, \
        attribute);

A: From the C Standard (5.1.1.2 Translation phases)

*Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to
  form logical source lines. Only the last backslash on any physical
  source line shall be eligible for being part of such a splice. A
  source file that is not empty shall end in a new-line character, which
  shall not be immediately preceded by a backslash character before any
  such splicing takes place.

For example these physical lines
i\
n\
t\
 x;

form the logical line
int x;

Here is a demonstrative program.
#include <stdio.h>

int main(void)
{
    i\
n\
t\
 x = 10;

    p\
r\
i\
n\
t\
f
    ( "%d\n",
    x );

    return 0;
}

Its output is
10

This technique is used for writing macros like for example #define.


text:
Q: Functions that take DataArrays and Arrays as arguments in Julia I'd like to write a function that can take both a DataArray and a standard Array in Julia. Actually, I'd like to write to methods for a function -- one that takes two vector-like structures as parameters and one that takes two matrix-like parameters.
Since Arrays and DataArrays are basically the same, only that a DataArray allows for NA values, I really do not want to write 4 versions of each function, just to incorporate all different combinations of Array and DataArray parameters. Right now, I use the following six (!) functions, to  achieve my goal:
function covar_to_intensity{T<:Number}(covariates::Array{T, 1}, coefficients::Array{T, 1})
  try
    return(exp(covariates' * coefficients)[1])
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

function covar_to_intensity{T<:Number}(covariates::Array{T, 2}, coefficients::Array{T, 2})
  try
    return(exp(covariates * coefficients))
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

function covar_to_intensity{T<:Number}(covariates::DataArray{T, 1}, coefficients::DataArray{T, 1})
  try
    return(exp(covariates' * coefficients)[1])
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

function covar_to_intensity{T<:Number}(covariates::DataArray{T, 2}, coefficients::DataArray{T, 2})
  try
    return(exp(covariates * coefficients))
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

function covar_to_intensity{T<:Number}(covariates::Array{T, 1}, coefficients::DataArray{T, 1})
  try
    return(exp(covariates' * coefficients)[1])
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

function covar_to_intensity{T<:Number}(covariates::Array{T, 2}, coefficients::DataArray{T, 2})
  try
    return(exp(covariates * coefficients))
  catch
    error("Multiplication of covariates and coefficients not possible.")
  end
end

I'm aware that this might be an inefficient way to compute these products, but I also have a general interest regarding how to write functions taking both Arrays and DataArrays.
Thanks!

A: In general, you can define methods for AbstractArray:
function covar_to_intensity{T<:Number}(covariates::AbstractVector{T}, coefficients::AbstractVector{T})
  try
     return exp(covariates * coefficients)
  catch
    error("Multiplication of covariates and coefficients not possible.")
   end
end

function covar_to_intensity{T<:Number}(covariates::AbstractMatrix{T}, coefficients::AbstractMatrix{T})
  try
     return exp((covariates' * coefficients)[1])
  catch
    error("Multiplication of covariates and coefficients not possible.")
   end
end


text:
Q: How to switch between In-App-Purchase subscriptions? I have an app in App Store using In-App Purchase with non consumable type. Last week my client wanted to switch the In-App Purchase type from Non-consumable to Non-renewable subscription (user have to manually renew for each month). I have searched in Google and cannot find any solution. So, ccould anyone help,

*

*How to switch between these types?

*What are the changes need to be done in App Store connect page and my project side?

*How to notify the users those who are purchased the products already with non-cosumable type?


text:
Q: 'Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead.' I have only upgraded to Laravel ^6.0 from 5.8*.
On running $ composer require laravel/passport
I have got error message "Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead."
I have installed laminas-json
Will that suffice?

A: https://www.zend.com/blog/what-status-zend-framework-transition-laminas
everything zend framework is being transitioned to laminas open source project. There's a lot of projects going to be popping up these messages as zend.

A: The update to use laminas/laminas-diactoros was made in v8.2.0. Using a more recent version of laravel/passport will solve the questioned issue.


text:
Q: Change picture onmouseover only once I need to change picture on mouse over only once. So when mouse over - change picture and STOP, never get back to default image, keep the new one. I need this because default image is gif animated and mouse over is static png pictire and as people hold the mouse for a second animated picture comes back. Atleast to delay for 5 seconds onmouseout action.
Right now I use this javascript.
function onHover()
{
$("#menuImg").attr('src', 'images/mouseover_picture.png');
}

function offHover()
{
$("#menuImg").attr('src', 'images/default_picture.png');
}

html :
<img src="map.gif" id="menuImg" alt="info" width="415" height="380" usemap="#Europe" border="0" onmouseover="onHover();" onmouseout="offHover();" />

A: Yes, you can use the one() handler to fire it only once.
$('#menuImg').one('mouseenter', function() {
  $(this).attr('src', 'images/mouseover_picture.png');
});

Here's a very basic jsFiddle example showing it used with an alert.

A: For jQuery you can use the .one() function to trigger the event only once.
jsFiddle
$('#menuImg').one('mouseover', function () {
    $(this).attr('src', 'https://www.google.com.au/images/srpr/logo4w.png');
});

As pure JS solution, detach the event handler by assigning null to it.
jsFiddle
var img = document.getElementById('menuImg');
img.onmouseover = function () {
    this.setAttribute('src', 'https://www.google.com.au/images/srpr/logo4w.png');
    img.onmouseover = null;
};


text:
Q: Using Apple icons with iOS 6 With the release of iOS 6 I'd like to revisit the original question here: Access to Apple's built in Icons?
For example, when you hit the 'action' button to share a photo, now instead of an action sheet with buttons titled 'Message', 'Mail', etc., now there is a collection view of the icons for mail, messaging, facebook, twitter, etc.
For a 'share' action in my app I'd like to be able to present the same - because it looks better and would provide a consistent user experience. Is the use of these icons still not allowed, even if they are referring to (and would take the user to) the apps they originally belong to?

A: The problem with using UIActivity for sending mail is that you cannot set the subject field's text, recipients, etc. like you can with MFMailComposeViewController
I've been trying to do a workaround to set the subject field, but have not found a solution yet.

A: For just showing the share UI with icons, you probably want UIActivityViewController.
NSString* someText = self.textView.text;
NSArray* dataToShare = @[someText];  // ...or whatever pieces of data you want to share.

UIActivityViewController* activityViewController =
        [[UIActivityViewController alloc] initWithActivityItems:dataToShare
        applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:^{}];

It looks like:

Documentation here.

A: UIActivity class provides built-in activity types for mail, messaging, ...


text:
Q: XHR returning a string float for the ETag response header instead of actual response header I have the following code utilizing XMLHttpRequest:
const xhr = new XMLHttpRequest();

xhr.open('PUT', url);

xhr.addEventListener('readystatechange', () => {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const eTag = xhr.getResponseHeader('ETag');
    console.log({ eTag, headers: xhr.getAllResponseHeaders() });
  }
});

xhr.send(chunk);

When I run this code and look at the response in the Firefox developer tools I see that the response has an ETag header of a long Base64 string:

However, when I look in the console, I see an ETag header that is nowhere near the same:

Object { eTag: "0.07594210872820828", headers: "content-length: 0\r\netag: 0.07594210872820828\r\n" }

Rather than the Base64 string I'm seeing in the devtools, I'm getting a float as a string that doesn't appear to have any relation to the Base64 string. There is only one header that looks anything like ETag:

This is CloudFlare R2 for whatever that's worth. As you can see I have CORS configured so the service responds with Access-Control-Expose-Headers: ETag.
What's going on that the JavaScript code appears to be getting a different value from what is shown in the developer tools?

A: Turns out it was this extension: https://github.com/ClearURLs/Addon
It has an option that is enabled by default: Filters ETag Headers From Requests. Turning that option off fixed the issue.


text:
Q: Viewer and viewer.container event listeners I noticed that both viewer and viewer.container have functions to add and remove events, but not every event work on both.
So what is the difference between them and which events should be used with each object?
Also, is there a way to view what events are registered on each object?

A: viewer.container is the DOM element that contains the viewer canvas. As far as I know there is no direct way to know which events are registered on those objects but since it has to be registered by your own app at some point it shouldn't be too hard to track this down by the mechanism of your choice.


text:
Q: Relationship to find ancestor in SQLAlchemy I have a tree of one-to-many relationships that looks like this:

organization -> operation -> region -> area -> site

The organization is the top level ancestor. A site has an area_id, area has a region_id, and so on up the tree.
For each entity under organization, I'd like to be able to quickly access the organization ancestor through a relationship like site.organization, area.organization, etc.
What would the relationship on each entity look like to make this work?

A: A solution would be to use a composite "secondary" join for those classes that do not have a direct relationship with organization. For example site:
class Site(Base):

    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False,
        innerjoin=True,
        viewonly=True)

while region should just use the table operation as a secondary:
class Region(Base):

    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False,
        innerjoin=True,
        viewonly=True)

The above is a reduced version displaying only the relationship configurations. A concrete example follows:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine("sqlite://")

Base = declarative_base()
Base.metadata.bind = engine

Session = sessionmaker()

class Organization(Base):
    __tablename__ = 'organization'
    id = Column(Integer, primary_key=True)

class Operation(Base):
    __tablename__ = 'operation'
    id = Column(Integer, primary_key=True)
    organization_id = Column(ForeignKey('organization.id'))
    organization = relationship("Organization")

class Region(Base):
    __tablename__ = 'region'
    id = Column(Integer, primary_key=True)
    operation_id = Column(ForeignKey('operation.id'))
    organization = relationship(
        "Organization",
        secondary="operation",
        uselist=False, innerjoin=True, viewonly=True)
    operation = relationship("Operation")

class Area(Base):
    __tablename__ = 'area'
    id = Column(Integer, primary_key=True)
    region_id = Column(ForeignKey('region.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region)",
        uselist=False, innerjoin=True, viewonly=True)
    region = relationship("Region")

class Site(Base):
    __tablename__ = 'site'
    id = Column(Integer, primary_key=True)
    area_id = Column(ForeignKey('area.id'))
    organization = relationship(
        "Organization",
        secondary="join(Operation, Region).join(Area)",
        uselist=False, innerjoin=True, viewonly=True)
    area = relationship("Area")

Base.metadata.create_all()

session = Session()
session.add(Site(area=Area(region=Region(operation=Operation(organization=Organization())))))
session.commit()

site = session.query(Site).options(joinedload(Site.organization)).first()
print(site)
print(site.organization)
print(site.area.organization)
print(site.area.region.organization)
print(site.area.region.operation.organization)


text:
Q: \foreach loop for \tikzset I have the following code for drawing circles whose different radius. As seen in code there are two different pic statement (d1 and d2).
\documentclass[margin=3mm]{standalone}
\usepackage{tikz,pgf}
\begin{document}

\begin{tikzpicture}

%  \foreach \b in {1,2}{
    \tikzset{
        d1/.pic={
            \foreach \r in {1,...,4}{
                \draw[red,thick](\r,0) circle (\r);
            }
        }
    }
    \tikzset{
        d2/.pic={
            \foreach \r in {1,...,4}{
                \draw[black,thick](3*\r,0) circle (\r);
            }
        }
    }
%  }

    \pic at (0,0) {d1};
    \pic at (0,0) {d2};

    \end{tikzpicture}

\end{document}

Output of the code:

Is it possible to one pic statement for d1 and d2 using \foreach? For example:
\documentclass[margin=3mm]{standalone}
\usepackage{tikz,pgf}
\begin{document}

\begin{tikzpicture}
   \pgfmathsetmacro{\k}{1}
  \foreach \b in {1,2}{
    \tikzset{
        d\b/.pic={

        \ifnum\b=2 \pgfmathsetmacro{\k}{2} \fi
            \foreach \r in {1,...,4}{
                \draw[red,thick](\k*\r,0) circle (\r);
            }
        }
    }
    }

    \pic at (0,0) {d1};
    \pic at (0,0) {d2};

    \end{tikzpicture}

\end{document}

It seems that b counter in \foreach loop does not pass into the tikzset. How can I solve this problem?

A: You could just make the pic depend on an argument that indicates the color.
\documentclass[margin=3mm]{standalone}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\def\ColorList{{"black","red","blue"}}

    \tikzset{
        d/.pic={\pgfmathsetmacro{\mycolor}{\ColorList[#1]}
            \foreach \r in {1,...,4}{
                \draw[\mycolor,thick]({\r*(1+2*#1)},0) circle (\r);
            }
        }
    }

  \foreach \b in {0,1,2}{
    \pic at (0,0) {d=\b};
  }
\end{tikzpicture}

\end{document}


text:
Q: Resolve URL from database query in ASP.net When I go to get my images from my database in ASP.net and it loads in to the boundfield all I see is
this
     ~\Images\Husqvarna-HU700L.jpg
or
     ~\Images\Husqvarna-95600L.jpg

instead of the image because it's not in the root.
My site is not going to be in the root directory and I need to figure out how to resolve the url to an absolute. Would it be a link or some C# method?


text:
Q: How to compare the vertices of two triangles in a meshed object in a 3d space I have vertices of two triangles in a 3d meshed object of coordinates represented as a,b,c in a 3d space.
These are drawn in Auto Cad and saved down as meshes.
I want to compare the both the table to find a similarity score.
Triangle 1

a
b
c

-12.500000
12.500000
15.000000

-12.500000
12.500000
15.000000

5.467900
5.28516
-15.00000

Triangle 2

a
b
c

12.500000
12.500000
-15.000000

12.500000
12.500000
-15.000000

-5.017247
-6.668717
15.000000

I want to identify the similarity score between them


text:
Q: Remove Header React Navigation v5 I can't seem to configure header to be null in the new version of React Navigation. I can set it to transparent, using the headerTransparent option, but this it looks like the header is still there, as the screen still requires a name.
Here is what I had initially, using the template that comes with a new Expo application
And this is what it looks like with the header as transparent. Which is essentially what I want to see but the title is still forced in there.
I don't want a header with my navigation, but that looks like the default behavior. I tried looking through the documentation to see if there was such a prop to delete the header but encountered a 404 page for options: https://reactnavigation.org/docs/en/navigation-options.html
I'm new to React Native, so there may be something I am misunderstanding. But the documentation is unclear on this and I couldn't find a stackoverflow question directly addressing this.
Here is my App.js
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import BottomTabNavigator from './navigation/BottomTabNavigator';
import useLinking from './navigation/useLinking';

const Stack = createStackNavigator();

........

<NavigationContainer ref={containerRef} initialState={initialNavigationState}>
  <Stack.Navigator>
    <Stack.Screen name="root" component={BottomTabNavigator} options={{headerTransparent: true}}/>
  </Stack.Navigator>
</NavigationContainer>

Here is my BottomTabNavigator.js, which is very similar to the template code that expo provides.
import * as React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import TabBarIcon from '../components/TabBarIcon';
import HomeScreen from '../screens/Home';
import SearchScreen from '../screens/Search';

const BottomTab = createBottomTabNavigator();
const INITIAL_ROUTE_NAME = 'Home';

export default function BottomTabNavigator({ navigation, route }) {
  navigation.setOptions({ headerTitle: getHeaderTitle(route) });
  return (
    <BottomTab.Navigator initialRouteName={INITIAL_ROUTE_NAME}>
      <BottomTab.Screen
        name="Home"
        component={HomeScreen}
        options={{
          title: 'Home',
          tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="md-home" />
        }}
      />
      <BottomTab.Screen
        name="Search"
        component={SearchScreen}
        options={{
          title: 'Search',
          tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="md-search" />,
        }}
      />
    </BottomTab.Navigator>
  );
}

function getHeaderTitle(route) {
  const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;

  switch (routeName) {
    case 'Home':
      return 'How to get started';
    case 'Appointments':
      return 'Your appointments';
    case 'Search':
      return 'Search for services';
    case 'Account':
      return 'Account'
  }
}

A: In your scenario, you have two options. Either you can disable header for all screens or you can disable header for the selected screen only.
For disable header for all-around your application edit your app.js like this
App.js
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import BottomTabNavigator from './navigation/BottomTabNavigator';
import useLinking from './navigation/useLinking';

const Stack = createStackNavigator();

........

<NavigationContainer ref={containerRef} initialState={initialNavigationState}>
  <Stack.Navigator screenOptions={{headerShown: false,}}>
    <Stack.Screen name="root" component={BottomTabNavigator}/>
  </Stack.Navigator>
</NavigationContainer>

You need to pass screenOptions into Stack.Navigator and make headerShown:false
Assume that you want to disable header on specific screen only, then this example will help you
<Stack.Navigator ...>
 ...
  <Stack.Screen
    name="Landing"
    component={LandingScreen}
    options={{
      headerShown: false, // change this to `false`
    }}
  />
...
</Stack.Navigator>

Hope you have clear idea about this :)

A: Setting headerMode: none as a default prop will remove it from any screen.
const Stack = createStackNavigator();
Stack.Navigator.defaultProps = {
    headerMode: 'none',
};

Also, I think that you can set the screenOptions's headerShown prop to false as a defaultProp too, but it would be like hiding the header on each screen rather than doing it once.

A: In react navigation V5, do add options={{ title: "Sign Up", animationEnabled: false, headerShown: false }}
  <AuthStack.Screen
  name="SignupScreen"
  component={SignupScreen}
  options={{ title: "Sign Up", animationEnabled: false, headerShown: false }}
/>

A: Remove in one screen:
      <Stack.Screen
              name="SignIn"
              component={SignInScreen}
              options={{
                headerShown: false,
              }}
            />

Remove in all stack:
     <Stack.Navigator
        screenOptions={{
         headerShown: false
        }}
        >


text:
Q: Send multipart with restkit 0.23.3: response mapping is empty I am trying to post an object (Walk) to my server.
[[RKObjectManager sharedManager] postObject:walk path:urlPath
                                 parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                     NSLog(@"It Worked: %@", mappingResult );

                                     if(mappingResult.count==0) {
                                         [self alertStatus:@"Error" :@"Erreur" :0];
                                         return;
                                     }...

The problem is that mappingResult is always empty.
In the log I have the following:
The response:
restkit.object_mapping:RKMapperOperation.m:320 Examining keyPath '<null>' for mappable content...
2015-01-11 22:49:56.250 XXXX restkit.object_mapping:RKMapperOperation.m:300 Found mappable data at keyPath '<null>': {
    errors = "<null>";
    message = success;
    reason = "<null>";
    result = "<null>";
    status = SUCCESS;
}
2015-01-11 22:49:56.251 XXXX D restkit.object_mapping:RKMapperOperation.m:403 Finished performing object mapping. Results: {
}
2015-01-11 22:49:56.255 XXXX T restkit.network:RKObjectRequestOperation.m:218 POST 'http://XXXX' (200 OK / 0 objects) [request=2.0944s mapping=0.0100s total=2.1111s]:
response.headers={
    "Cache-Control" = "no-cache, no-store";
    Connection = "Keep-Alive";
    "Content-Type" = "application/json";
    Date = "Sun, 11 Jan 2015 21:48:28 GMT";
    Expires = "Thu, 01 Jan 1970 00:00:00 GMT";
    "Keep-Alive" = "timeout=15, max=99";
    Pragma = "no-cache";
    "Transfer-Encoding" = Identity;
}
response.body={"status":"SUCCESS","message":"success","reason":null,"result":null,"errors":null}
2015-01-11 22:49:56.258  XXXX It Worked: <RKMappingResult: 0x1685b750, results={
        }>

I added this responseDescriptor:
RKResponseDescriptor * descriptor = [RKResponseDescriptor responseDescriptorWithMapping:[ResponseModel defineResponseRequestMapping]
                                             method:RKRequestMethodPOST
                                        pathPattern:nil
                                            keyPath:nil
                                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:descriptor];

I tried with different pathPattern but it's not working.
The mapping:
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[ResponseModel class]];

[mapping addAttributeMappingsFromDictionary:@{
                                              @"status":   @"status",
                                              @"reason":   @"reason",
                                              @"message":   @"message",
                                              @"errors":   @"errors",
                                              @"result":   @"result"

                                              }];

Anyone can help me why  my mappingResult is always empty even through I have no error from Restkit?
Thank you very much for the help!

A: Thank you for your message.
I just found the solution on this link: RestKit POST response with wrong mapping.
RestKit use the same mapping for the response than for the request. You have to force it.
Thank you


text:
Q: udev rules is not working I want to set the key repeat rate using xset r rate 150 90 when the keyboard is plugged in but the very basic rule I created is not working.
/etc/udev/rules.d/10-keyboard.rules
ACTION=="add", RUN+="echo hello > /home/s1n7ax/hello"

After the rule is added I reloaded the rules sudo udevadm control --reload. When the keyboard is unplugged and re-plugged in, rule is not fired (a new firefox instance is not created). Manually triggering the rules is also doesn't fire the rule sudo udevadm trigger.
Permissions are as follows for the rule.
-rwxr-xr-x 1 root root 39 May  4 19:30 10-keyboard.rules

What is the issue here?


text:
Q: how are quantum entangled states mantained? when ever I search for this question I always get articles on how to make a quantum entangled  pair, and not how it's kept or mantained. if i were to entangle a pair of electrons, how would I keep the particles entangled for long distances?

A: Short answer
I theory, it is easy to maintain the entanglement of two particles: just do nothing.
In practice, doing nothing is much harder than it sounds. You need to isolate both particle, so that their entangled degree of freedom (typically the spin for an electron) does not interact with anything else. It is hard to do with electrons, since they are charged and interact with the environment. That's why most entanglement experiments use photons: they do not interact much, and travel fast, allowing do demonstrate long distance entanglement even if they live shortly.
When one needs to keep entanglement for some time, electrically neutral material systems (cold atoms, crystal defects, etc) an relatively complicated protocols can be used.
An explicit protocol involving entangled states of NV centres in diamond
I give below, an explicit protocol¹ considered by experimentalists to create and maintain entanglement in NV-centres in diamond. As you could easily guess from the description, this protocol is specific for this kind of experimental system, and has to be seen as an example, and a way to convince you that there is no short simple answer to your question (beyond "keep your system isolated"). If one is concerned by entanglement in cold atom vapours, neutrons, or supraconducting qubits, the protocols will look different, at least superficially, but is often as complex.
Let us look, for example, at a protocol to entangle two NV-centres in diamonds located far away (a system recently used for a Loophole free test of Bell's inequalities).
At each location, an entangled state can be created between the spin of an electron and a photon. To maintain the entanglement, the state of each electron spin state can be mapped, through carefully crafted microwave pulses, to a more isolated nuclear spin state. The two photons are measured together in an intermediate place, effectively teleporting one photon to the spin entangled with the other. After photon measurement, the two nuclear spins are entangled, and can be maintained as long as the nuclear spins doe not interact with (chemical or isotopical) impurities in diamond (i.e. a few ms at room temperature). To perform measurements on the entangled states, one needs to use microwave pulses map the nuclear spin state to the electronic spin state, and then optically probe the NV centres.
Footnote:
¹: All the element of this protocol have been demonstrated in various combinations, but I don't think the whole protocol above has been demonstrated yet. I know however that it is on the roadmap of several research groups.


text:
Q: Display inline block adds uncontrollable vertical margins It seems that I've already got my problem in previous similar case, but now I've got same problem even after setting font-size and line-height of parent div to 0 and removing any potentially harmful white space.
In the sample (http://jsfiddle.net/vDsR4/2/) I expect height of the header to be exactly 40px, but i'm getting extra 5px of height and can't see any reason for them. (Works similarly in latest Chrome & FF) .

Solved (partially): as noted in answers, the most probable reason for such behaviour is vertical-alignment = baseline (the default one). Now I notice that '[*]' icon is rendered below 'My Title'. To workaround the problem (as soon as all containing elements are supposed to be of the same height) setting vertical-align=top does the job. What is not yet clear to me - why smaller font has more space under baseline than the larger font.

.pagehdr-slice {
    padding: 0 32px;
    height: 40px;
    line-height: 40px;
    background-color: #2980BA;
    border-bottom: 3px solid #3273a2;
}

.pagehdr-titlebox {
    color: #AAD0E8;
    width: 200px;
    border-right: 1px solid red;
    font-size: 0;
    line-height: 0;
}

.pagehdr-title-icons, .pagehdr-title {
    display: inline-block;
    height: 40px;
    line-height: 40px;
    font-family: Arial;
    font-weight: bold;
}

.pagehdr-title-icons {
    font-size: 25px;
}

.pagehdr-title {
    font-size: 40px;
}

[*]

My Title

A: Try:
.pagehdr-title-icons {vertical-align: top;}

http://jsfiddle.net/isherwood/vDsR4/4/
I'm struggling to explain this solution, but I think it has to do with the variation in font size between the two elements inside the header.

A: In latest Chrome, your header has an height of 43px that comes from the border you set (border ADD to the size, and are not contains in it).
If it doesn't solve your problem, try settings height at each level (so add an height to the children), that may help ; you also can set an overflow: hidden; on your header that would hide the extra-content, but it should be solved without it. ;)

A: or add a float:left; in the .pagehdr-title-icons, .pagehdr-title class:
.pagehdr-title-icons, .pagehdr-title {
    display: inline-block;
    height: 40px;
    line-height: 40px;
    font-family: Arial;
    font-weight: bold;
    float:left; /*add this to align both */
}


text:
Q: Configure webpack to generate separate vendor js files for each entry I have multiple js apps in one application. Each js app has different dependency on js libraries and each js app is an entry for webpack. Current webpack setting is generating just one vendor.bundle.js.
How can I configure webpack to generate separate vendor bundle js files for each entry?
Expecting Output:

*

*vendor.bundle.js

*vendor~app1.bundle.js

*vendor~app2.bundle.js

*app1.bundle.js

*app2.bundle.js

webpack config
module.exports = {
    entry: {
     'app1': './src/AppOne.js',
     'app2': './src/AppTwo.js'
    },

    output: {
        path: path.resolve(__dirname, './resources/js/dist'),
        filename: '[name].bundle.js'
    },

    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    name: 'vendor',
                    chunks: 'initial',
                    minChunks: 2
                }
            }
        }
    }
}

A: Removing the optimization block
or
Using chunks: 'all' seem to work.
optimization: {
    splitChunks: {
            chunks: 'all'
        }
},


text:
Q: Save HTML form and values offline for later processing I have an offline HTML form (see example below) which will have several tick options. The user gets the form sent by email, which he has then to fill offline and send the filled form back for later processing. How could this be implemented? I mean saving the html file when filled does not store the value. Any suggestions, ideas?
<form>

    <input type="checkbox" id="check1" name="check1" value="ns">
    Is A correct?

    <input type="checkbox" id="check2" name="check2" value="ns">
    Is B correct?

    <button type="submit">Subscribe</button>

</form>

Best
Muleque

A: You can use local storage to store the data from the HTML form.
Here is the full implementation example for that.
Html Local Storage Implementation


text:
Q: Loading notification image Im using the following code to load image into notification.
Notification status = new Notification.Builder(this).build();

 Glide.with( MainActivity.act ) // safer!
                        .load( MainActivity.localTrackList.get(MainActivity.currentOffset).getPath() )
                        .asBitmap()
                        .into( status.iconLevel );

But its throwing error .

Error:(63, 25) error: no suitable method found for into(int) method
  GenericRequestBuilder.into(Y) is not applicable (inferred type does
  not conform to upper bound(s) inferred: Integer upper bound(s):
  Target) method GenericRequestBuilder.into(ImageView) is not
  applicable (argument mismatch; int cannot be converted to ImageView)
  method BitmapRequestBuilder.into(ImageView) is not applicable
  (argument mismatch; int cannot be converted to ImageView) where Y is a
  type-variable: Y extends Target declared in method into(Y)

How can I be able to load images in notification ?