text:
Q: Firebase database update is removing child data I am writing an event list app, It has a hierarchy of Event > Part > Step.  After I've created an event, I can "go into" the event and see the list of "parts" which contain a list of "steps".
The way I've structured my database is so that I have an object sorted by user ID to show the events and its details, then if I click on that event, I go into it, now looking at a parts object.  The parts object looks something like this:
parts:
    eventID1:
        partID1:
            startDateTime:value,
            endDateTime:value,
            title:value,
            ...
        partID2:
            startDateTime:value,
            endDateTime:value,
            title:value,
            ...
        etc.

This works well, I pull all parts per event ID.  The problem comes with steps.  When I add a step to a part, I put it in two places (using update); one in a steps table and one in the part itself, adding a new key:value to the part
the steps object looks like this:
steps:
    eventID1:
        partID1:
            stepID1:
                title:value,
                startDateTime:value,
                etc.
            stepID2:
                title:value,
                startDateTime:value,
                etc.

And finally (the problem area) the part object is updated to look like this:
parts:
    eventID1:
        partID1:
            startDateTime:value,
            endDateTime:value,
            title:value,
            ...
            steps:
                stepID1:
                    title:value,
                    startDateTime:value,
                    etc.
                stepID2:
                    title:value,
                    startDateTime:value,
                    etc.
        partID2:
            startDateTime:value,
            endDateTime:value,
            title:value,
            ...
        etc.

I've added the steps within the parts above (again, using update).  The problem is now when I edit the part's title or date, It returns as updated but there are no steps within.  It erases the steps.
Each event, part and step have the same structure, so I've combined all of this into a single function (using ionic 3/angular4)
  update(action, type, eid, pid, sid, title, location, startDateTime) {
    console.log("Firebase Database Receiving: ", action, type, eid, pid, sid, title, location, startDateTime);
    let key = (action === "add") ? this.ref.push().key : null;
    console.log(key);
    let update;
    let object = {
      startDateTime: startDateTime,
      startDateTimeEpoch:  moment(startDateTime).format("X"),
      endDateTime: startDateTime,
      endDateTimeEpoch:  moment(startDateTime).format("X"),
      title: title,
      type: type,
      roles: {
        [this.firebaseAuthentication.uid]: "admin",
      },
      location: {
        title: location,
        street: '',
        city: '',
        state: '',
        zip: '',
        timeZone: ''
      },
    };
    if(type === "events"){
      key = (key) ? key : eid;
      if(action !== "delete") {
        update = {
          ['events/' + key]: object,
          ['roles/' + this.firebaseAuthentication.uid + '/' + key]: object
        }
      } else {
        console.log("delete event", key);
        update = {
          ['events/' + key]: null,
          ['roles/' + this.firebaseAuthentication.uid + '/' + key]: null,
          ['parts/' + key]: null,
          ['steps/' + key]:null
        }
      }
    } else if(type === "parts") {
      key = (key) ? key : pid;
      if(action !== "delete") {
        update = {
/************ . Here is the update object . ***********/
          ['parts/' + eid + '/' + key]: object
        }
      } else {
        update = {
          ['parts/' + eid + '/' + key]: null,
          ['steps/' + eid + '/' + key]: null
        }
      }
    } else if(type === "steps") {
      key = (key) ? key : sid;
      if(action !== "delete") {
        update = {
          ['parts/' + eid + '/' + pid + '/steps/' + key]: object,
          ['steps/' + eid + '/' + pid + '/' + key]: object
        }
      } else {
        update = {
          ['parts/' + eid + '/' + pid + '/steps/' + key]: null,
          ['steps/' + eid + '/' + pid + '/' + key]: null
        }
      }
    }
    console.log(object, update);
    return new Promise((resolve, reject) => {
/**************** . Finally the actual update function ************/
      this.ref.update(update).then(success => {
        resolve(success);
      }, error => {
        reject(error);
      });
    });
  }

This basically iterates through, the specific action/type combination is edit/part.
From what I've read about firebase's update(), it should not be destructive to any data within the object that it's not touching.  This is acting like set() should, but I do not want that obviously.
Any thoughts? Frank?

A: From what I gather from your code the update function works as I would expect (from experience rather than documentation ). What I mean to say is that updating on a key by setting it to an object does exactly that, it sets the key value to the object you passed. An example:
users:

*

*nik

*

*age:18

*id:1

*george

*

*age:29

*id:2

let obj={age:24};
calling update({nik:obj}) would actually set nik to have the value of the object you provide (thus deleting id). Stands to reason right? Well firebase does say about update:

If you want to write to multiple children of a database location at the same time without overwriting other child nodes, you can use the update method as shown below:

What might be not clear is that it means other child nodes at the same level with the key you are updating (that would be george).

A: It's the 'null' causing it, as per my usage of firebase so far that I can update the object and remove key pair from the object in a single update call.
object: {

 key1: value1,

key2: null // this key will be removed as it is set to null

}

Hopefully this helps someone


text:
Q: Linq select where date is yesterday I've got as far as this:
DateTime yesterday = DateTime.Today.AddDays(-1);
YesterdaysRegistrations = db.tblForumAuthors.Where(c => c.Join_date == yesterday).Count();

There definitely records that have the join date of yesterday, but this returns 0 all the time!  Can anyone tell me if I'm doing this correctly?

A: You don't have to strip off the time, you just have to make sure you don't do an exact match.
Try this instead:
DateTime today = DateTime.Today; // read once, avoid "odd" errors once in a blue moon
DateTime yesterday = today.AddDays(-1);
YesterdaysRegistrations = db.tblForumAuthors.Where(
    c => c.Join_date >= yesterday
      && c.Join_date < today).Count();

A: AddDays keeps the Hour/Minute/Second components. You either have to use (if c.Join_date is only the date component):
DateTime yesterday = DateTime.Today.AddDays(-1).Date;

Otherwise, you compare for range:
DateTime yesterday = DateTime.Today.AddDays(-1).Date;
DateTime yesterdayEnd = DateTime.Today.Date.AddSeconds(-1);
db.tblForumAuthors.Where(c => c.Join_date >= yesterday && c.Join_date < yesterdayEnd)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix an issue with SQL server query that contains a conditional case to use 'group by' when using the field ***SAMPLE QUERY REVISED FOR SIMPLICITY
I'm running a conditional query in SQL Server and having this issue when wrapping this specific CASE condition within the GROUP BY query.
I simulate the query to one that can be simplified and I appreciate your help on this:
DECLARE @orders_table TABLE(
i_date DATE,
customer_id INT,
customer_score INT,
orders INT
);

INSERT @orders_table
VALUES
('2022-11-28', 100, 3, 1),
('2022-11-28', 101, 7, 4),
('2022-11-29', 102, 6, 1),
('2022-11-30', 103, 1, 5)

DECLARE @group_by_customer_id BIT = 1;
SELECT
i_date,
CASE WHEN @group_by_customer_id = 1 THEN customer_id ELSE NULL END,
CASE WHEN @group_by_customer_id = 1 THEN CASE WHEN customer_score > 5 THEN customer_score ELSE 0 END ELSE NULL END,
SUM(orders)
FROM
@orders_table
GROUP BY
i_date,
CASE WHEN @group_by_customer_id = 1 THEN customer_id ELSE NULL END,
CASE WHEN @group_by_customer_id = 1 THEN customer_score ELSE NULL END;

The 'aggregate' issue is thrown as I'm using the condition of "WHEN customer_score > 5" within the query. I just need to figure out how to achieve the result of using each line just according to the case when @group_by_customer_id for e.g.
Column '@orders_table.customer_score' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 19
Column '@orders_table.customer_score' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

The 'columns' and the 'group by' are identical according to the case.
The problematic line is this one:
CASE WHEN @group_by_customer_id = 1 THEN CASE WHEN customer_score > 5 THEN customer_score ELSE 0 END ELSE NULL END,

And it works perfectly if I remove the nested CASE:
CASE WHEN @group_by_customer_id = 1 THEN customer_score ELSE NULL END,

The result I'm trying to achieve is:

I do NOT want to switch to dynamic SQL...
Thanks


text:
Q: Python dll Extension Import I created extensions for my Python and created a abcPython.dll. How can I import this dll into my Python scripts?
I get an error message when I try to import it usin the following command
>>>import abcPython
>>>Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     ImportError: No module named abcPython
>>>

I manually created a system environment variable named PYTHONPATH which stores the path to the abcPython.dll, but still the error remains.
How can I fix this?

A: Aarrgghh! Yet another 2.X/3.X gotcha. RTFErrorMessage:
ImportError: dynamic module does not define init function (PyInit_abcPython)
Note the prefix: it's not init, it's PyInit_
See the 3.1 docs ... "The initialization function must be named PyInit_name(), where name is the name of the module"

A: Follow Building C and C++ Extensions on Windows carefully - in sub-section 7, it says:

The output file should be called spam.pyd (in Release mode) or spam_d.pyd (in Debug mode). The extension .pyd was chosen to avoid confusion with a system library spam.dll to which your module could be a Python interface
  ...
Changed in version 2.5: Previously, file names like spam.dll (in release mode) or spam_d.dll (in debug mode) were also recognized.

Try the renaming your DLL to use a .pyd extension instead of .dll.
(thanks, Peter Hansen)
The reference points to a C example, which explicitly includes an INIT function,
PyMODINIT_FUNC initexample(void). The resulting DLL should be renamed example.pyd :
#include "Python.h"

static PyObject *
ex_foo(PyObject *self, PyObject *args)
{
    printf("Hello, world\n");
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef example_methods[] = {
    {"foo", ex_foo, METH_VARARGS, "foo() doc string"},
    {NULL, NULL}
};

PyMODINIT_FUNC
initexample(void)
{
    Py_InitModule("example", example_methods);
}

A: Simple renaming of .dll to  .pyd did not help. I was using SWIG to create the extension module. I created a .pyd instead of creating a .dll module and that solved the issue.

A: As an example: Imagine you have compiled OpenCV and have several *.dll and the cv2.pyd file.
You need to copy those files to 'DLLs' folder within the python directory.
Then import the module to check wether it is ok.


text:
Q: Shortest Confidence interval for $\beta^2$ let $x_1,x_2, \ldots, x_n$ be a random sample from distribution under function distribution:
$$F(x)= \left( \frac{x}{\theta} \right)^\beta, \quad 0 \leq x \lt \theta.$$
Where $β$ is unknown but $θ$ is known. find a shortest confidence interval in level $(1-\alpha)$ for $\beta^2$.

A: I give you a solution, but this is surely not the solution wanted by your teacher (as this looks like homework?).
I guess $F(x) =  \left( {x\over\theta} \right)^\beta$ is the cumulative distribution function (CDF).
Let $Y = \max_i X_i$. Its CDF is
$$G(y) = P(Y < y) = P\left(\cap_i X_i < y\right) =\prod_i P(X_i < y) = F(y)^n =\left( {y\over\theta} \right)^{n\beta}.$$
Let $q_1$ and $q_2$ be the quantiles of order $\alpha\over2$ and ${1-\alpha\over 2}$. $G(q_1) = {\alpha \over 2}$ leads to $n\beta (\log q_1 - \log \theta) = \log\left({\alpha\over 2}\right)$ hence $\log(q_1) = \log(\theta) + {1\over n\beta} \log\left({\alpha\over 2}\right)$, and $G(q_2) = 1-{\alpha\over 2}$ leads to $\log(q_2) = \log(\theta) + {1\over n\beta} \log\left(1-{\alpha\over2}\right)$.
From $P(\log q_1 < \log Y < \log q_2) = 1-\alpha$ you get
$$P\left(\log\left({\alpha\over 2}\right) < n\beta(\log Y-\log\theta) < \log\left(1-{\alpha\over2}\right)\right) = 1-\alpha,$$
hence (as $\log Y < \log \theta$)
$$ P\left({ \log\left({\alpha\over 2}\right)  \over n (\log Y -\log\theta)} > \beta > {\log\left(1-{\alpha\over2}\right) \over n (\log Y -\log\theta)} \right) = 1-\alpha.$$
To get the shortest CI replace $q_1$ and $q_2$ by quantiles $\xi$ and $1-\alpha+\xi$ and seek $\xi$ that minimizes the length of the interval.  To get a CI on $\beta^2$ take the square (everything is positive, so $x\mapsto x^2$ is monotonic).
PS If you get some other anwser by an other way, please share


text:
Q: remove value using grepl I am trying to remove retweets (strings that start with RT) from a dataset, but my grepl command doesn't seem to work right.
this works fine:
grepl("[^rt|RT][:alnum]",c("RT hi","rt boo","rtlolo","im goodRT"),ignore.case=T)
this fails. Why?
data<-structure(list(data = c("RT @4MySquad: This makes me sick!\\n#whiteprivilege\\n#BlackLivesMatter \\n#Policestate https:\\/\\/t.co\\/nDL0AHwWTd",
                              "RT @weaselzippers: D.C. Police Want Help Identifying #BlackLivesMatter Supporters Who Beat And Left Hero Marine For Dead\\u2026 https:\\/\\/t.co\\/tbmO\\u2026",
                              "RT @vicegandako: #PrayForMannyPacquiao #LoveWins", "\\Dig out of the binaries of right and wrong\\ - #BlackLivesMatter at Mizzou",
                              "Even Democrats think #Bernie 's ideas are unrealistic #insane #UNLV #BigBangTheory #Hillary2016 #blacklivesmatter https:\\/\\/t.co\\/ITDyXoAvtK",
                              "RT @eelawl1966: Former NAACP President Ben Jealous endorses Bernie Sanders\\n#BlackLivesMatter #BLM #Bernie2016 \\n https:\\/\\/t.co\\/Qom1KMwLHs",
                              "#SayNoToHillary #NoMoreClintons #FeelTheBern #BernieSanders #BlackLivesMatter #Disabled4Bernie #Women4Bernie... https:\\/\\/t.co\\/I8F21ilJgv",
                              "RT @JoshuaMannery: #BlackLivesMatter \\ud83d\\udc4a\\ud83c\\udffd https:\\/\\/t.co\\/tcEITKKGhd",
                              "lang:und", "@FoxNews Did he not say, \\Yes\\? Hopefully this story won't gain traction bc it's not reflective of the #blacklivesmatter movement",
                              "President Barack Obama Is Doing Big Things With Cuba + #BlackLivesMatter https:\\/\\/t.co\\/6gEJreOiUc",
                              "RT @Uberarabic: \\u0644\\u0644\\u0639\\u0644\\u0645 \\u0639\\u0642\\u0648\\u0628\\u0629 \\u0627\\u0644\\u0645\\u062b\\u0644\\u064a\\u064a\\u0646 \\u0641\\u064a \\u062c\\u0645\\u064a\\u0639 \\u0627\\u0644\\u062f\\u0627\\u064a\\u0627\\u0646\\u0627\\u062a \\u0627\\u0644\\u0633\\u0645\\u0627\\u0648\\u064a\\u0629 \\u0647\\u064a \\u0627\\u0644\\u0642\\u062a\\u0644\\n\\n#LoveWins",
                              "RT @AishaYesufu: Let's not forget 219#ChibokGirls still in captivity today 676 days \\n#NeverToBeForgotten #CryingToBeRescued #BringBackOurGi\\u2026",
                              "RT @arctic_matters: Chukchi Sea. #LoveWins https:\\/\\/t.co\\/gH8KZgVZk3",
                              ". @DoubleFine r u joking, tim u know the servers aren't working you dumb asshole #gamergate",
                              "RT @realkingcalii: #BlackLivesMatter Kendrick Lamar \\Alright\\ - https:\\/\\/t.co\\/amlRn0fKsA",
                              "RT @DreamersMOMS: Community representing #CCA & @geogroups making dirty $$$$ w\\/immigrants. #WeAreFlorida #not1more #immigration https:\\/\\/t.c\\u2026",
                              "id_str:700012325831581696", "RT @DreamersMOMS: Con compa\\u00f1eras de Carolina del Norte apoy\\u00e1ndonos en #Tallahassee. #ProteccionNoDeportation #Not1More @grisalonso https:\\/\\/\\u2026",
                              "RT @IkeIsaacson2: Hey #blacklivesmatter this is a hate crime done by racists in your name. https:\\/\\/t.co\\/6uGSXAJcrM"
)), .Names = "data", row.names = c(NA, 20L), class = "data.frame")

data[grepl("[^rt|RT][:alnum]",data,ignore.case=T)]

this question also uses Twitter data, but has a different approach

A: We specify the pattern as characters that start (^) with RT followed by one or more spaces (\\s+) and as the ignore.case = TRUE, it will also get elements that start with rt followed by space.
grepl("^RT\\s+",c("RT hi","rt boo","rtlolo","im goodRT"), ignore.case=TRUE)
#[1] TRUE TRUE FALSE FALSE

grep("^RT\\s+", data$data, ignore.case=TRUE, value = TRUE)
 #[1] "RT @4MySquad: This makes me sick!\\n#whiteprivilege\\n#BlackLivesMatter \\n#Policestate https:\\/\\/t.co\\/nDL0AHwWTd"
 #[2] "RT @weaselzippers: D.C. Police Want Help Identifying #BlackLivesMatter Supporters Who Beat And Left Hero Marine For Dead\\u2026 https:\\/\\/t.co\\/tbmO\\u2026"
 #[3] "RT @vicegandako: #PrayForMannyPacquiao #LoveWins"
 #[4] "RT @eelawl1966: Former NAACP President Ben Jealous endorses Bernie Sanders\\n#BlackLivesMatter #BLM #Bernie2016 \\n https:\\/\\/t.co\\/Qom1KMwLHs"
 #[5] "RT @JoshuaMannery: #BlackLivesMatter \\ud83d\\udc4a\\ud83c\\udffd https:\\/\\/t.co\\/tcEITKKGhd"
 #[6] "RT @Uberarabic: \\u0644\\u0644\\u0639\\u0644\\u0645 \\u0639\\u0642\\u0648\\u0628\\u0629 \\u0627\\u0644\\u0645\\u062b\\u0644\\u064a\\u064a\\u0646 \\u0641\\u064a \\u062c\\u0645\\u064a\\u0639 \\u0627\\u0644\\u062f\\u0627\\u064a\\u0627\\u0646\\u0627\\u062a \\u0627\\u0644\\u0633\\u0645\\u0627\\u0648\\u064a\\u0629 \\u0647\\u064a \\u0627\\u0644\\u0642\\u062a\\u0644\\n\\n#LoveWins"
 #[7] "RT @AishaYesufu: Let's not forget 219#ChibokGirls still in captivity today 676 days \\n#NeverToBeForgotten #CryingToBeRescued #BringBackOurGi\\u2026"
 #[8] "RT @arctic_matters: Chukchi Sea. #LoveWins https:\\/\\/t.co\\/gH8KZgVZk3"
 #[9] "RT @realkingcalii: #BlackLivesMatter Kendrick Lamar \\Alright\\ - https:\\/\\/t.co\\/amlRn0fKsA"
#[10] "RT @DreamersMOMS: Community representing #CCA & @geogroups making dirty $$$$ w\\/immigrants. #WeAreFlorida #not1more #immigration https:\\/\\/t.c\\u2026"
#[11] "RT @DreamersMOMS: Con compa\\u00f1eras de Carolina del Norte apoy\\u00e1ndonos en #Tallahassee. #ProteccionNoDeportation #Not1More @grisalonso https:\\/\\/\\u2026"
#[12] "RT @IkeIsaacson2: Hey #blacklivesmatter this is a hate crime done by racists in your name. https:\\/\\/t.co\\/6uGSXAJcrM"


text:
Q: Why is sudo by default asking for the password of the user that ran it? I'm wondering why does sudo actually NEED the password, when the user has already logged in?
The fact that the user has managed to run sudo means that the user has passed authentication and is authorized to do that.
So why does sudo need to ask for authentication again?
NOTE: I'm not actually trying to disable the password; just asking from curiosity.

A: sudo asks for your password by default.  It is not recommended, but you may bypass passwords for users/groups for all, or limited commands, if you chose to do so.
Here is why sudo asks for a password by default:
Linux is a multi-user system, and the easiest way to see this is to look at the root user, vs your own user.  Major system-critical components are protected by being accessible by only root.  This is why people suggest you create an alternate user than root when doing daily tasks.  Imagine the following command run as both users (root and you):

*

*apt-get purge ubuntu-desktop    #DO NOT RUN THIS
If you're cruising around as root, you've just removed ubuntu-desktop;  If you're logged in as a normal user, you'll get an error.
Now, imagine how many different programs you run, and how connected to the internet they all are.  Each of these clients/internet-connectable programs that you run are attack vectors or ways for people to gain entry into your machine.
Let's say that there is a new exploit for your favourite browser firefox that allows the attacker to gain shell.  Would you rather the user have YOUR shell, or your ROOT shell?
This is why sudo asks you for your password.

A: The user you are logged in as does not have all of the abilities necessary to perform all commands, this is to protect the system from accidental or intentional damage.  Normally root and your username will have different passwords and only the system administrator will know the root password.  It is a little different on a 1 user system where your username and root's password tend to be the same.  So while it may been like you already have been authorized this is not the full picture...

A: Your account is member of the wheel/sudo group which allows you to perform super user commands, but it's not an "administrative" account like root.
It is possible to use your root account to log on, removing the need to sudo. However, that practice is discouraged since it would expose the system to serious threats.


text:
Q: How to cascade delete replies from a post when deleting a post? I allow my users to sort by reply count and have it indexed so the operation is fast. I maintain the reply count of posts with the following SQL (there is also an equivalent set of two functions for the incrementing half):
CREATE TRIGGER post_reply_count_decrement_update
BEFORE DELETE ON
public.convo_reply for each row execute function trigger_function_decrement_reply_count();

-
CREATE OR REPLACE FUNCTION public.trigger_function_decrement_reply_count()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
   UPDATE post SET reply_count = reply_count - 1 WHERE post.convo_id = OLD.convo_id;
   RETURN OLD;
END;
$function$;

I am now trying to run this command: DELETE FROM convo WHERE convo_id = 1000031;
Unfortunately, it's not working, and is giving me this error:
SQL Error [23503]: ERROR: insert or update on table "post" violates foreign key constraint
"post_convo_id_fk"
  Detail: Key (convo_id)=(1000031) is not present in table "convo".
  Where: SQL statement "UPDATE post SET reply_count = reply_count - 1 WHERE post.convo_id = OLD.convo_id"
PL/pgSQL function trigger_function_decrement_reply_count() line 3 at SQL statement
SQL statement "DELETE FROM ONLY "public"."convo_reply" WHERE $1 OPERATOR(pg_catalog.=) "convo_id""

I believe this is occurring because the convo entry is deleted and then the value returns NULL in the trigger, so then the trigger errors out.
However, this is a non-problem, because the reply count is going to be set to 0 in a moment anyways after the post is deleted. Perhaps there is a way to just disable the trigger somehow while this is running? (although I still want it to be running for other posts of course)
I also would like to keep the trigger reasonably fast, because it runs every time a reply is created or destroyed.

A: You could try disabling specific trigger before running query
ALTER TABLE public.convo_reply DISABLE TRIGGER post_reply_count_decrement_update;

or catch violation
EXCEPTION WHEN others THEN
....

or check if the post exists, change the overall logic. Run trigger on post table for example, change table where your index is created...


text:
Q: Designing a simple fan + resistor system for heating air I have a research application that requires a steady supply of heated air. My current plan is to 3D-print a small tank (6" x 6" x 4") to which a muffin fan will be fastened. The fan will blow air across a 20W resistor into the tank to heat the air. The heated air will continuously leave the tank through an exit port and travel to the application for which the air is needed. The exiting air will need to be maintained at 37C +/- 1C.
Here is a schematic of the device:

To get the correct temperature, I will adjust the fan speed (variable CFM). This is my attempt at calculating the necessary fan speed:
Ambient air temp: T1 = 25C

Final air temp: T2 = 37C

Resistor power: P = 20 W

Heat capacity of air: c = 1 J/gK

Density of air: d = 1.15 g/L

air flow rate: f = P/[(c)(d)(T2-T1)] = 20/[(1)(1.15)(37-25)]

= 1.45 L/s = 3.1 CFM

This is not my area of expertise so I was wondering if I could get some feedback on my proposed method. Do the calculations seem sound? Do you foresee any issues with this system as a whole?

A: Since it is the fan that will deliver the air via the exit port tube I would suggest that you will not want to vary the fan speed as that will cause a variation in the air flow out of the exit port.
Instead you should setup a PWM driver to vary the duty cycle of the power to the resistor. This PWM duty cycle would be controlled through a feedback system that monitors the air temperature at the exit port of the box. This scheme allows the fan speed to be kept constant and permits a consistent air flow in the exit tube.
One of the easiest methods of monitoring the air temperature at the exit port is to place a 1N4148 diode onto the air stream that is biased with a constant 1mA of current. Then measure the forward voltage drop across the diode with an opamp gain circuit and an A/D converter.

A: All of the energy output of the resistor will end up in the exit airflow, regardless of fan speed (to first order).
Your plan is to vary the output temperature by controlling the air flow rate, that is, the mass of air the energy is diluted in. Most people (myself included) would have adopted a fixed fan speed, and varied the amount of power being delivered by the resistor.
While basically equivalent, the two schemes have different features, none of which make either approach a no-brainer.

*

*The variable airflow method will have a slightly lower latency from control input to temperature output, especially if a big fat resistor is used for the heater, many small resistors in parallel would be faster in that case. Latency is important for stability with feedback control, though I would expect most of the latency will come from the physical transport, then heating the tank, tube, and components in line to the monitored exit.

*Set against that, the variable fan speed method will have variable latency, due to changing the transit time for the tube. If you are servoing the temperature at the output, this could cause you loop tuning and stability problems, unless you tune for the lowest fan speed.

*The variable fan speed will act as an audible monitor of what the loop is doing. That may be useful, or irritating, or inaudible above the lab.

*The fluid dynamics around the experiment may well be sensitive to fan speed. I might be concerned that having got layout right at one speed, things could change at another.

*Power control uses less energy. Set the airflow to the minimum required, then the resistor output is automatically controlled to the minimum output. Though at 20w and presumably mains powered, this is a small consideration.

*Apparent overshoot is built-in to the flow regulated system. Consider a flow regulated shower. Let's say the water is too hot. I turn the flow up, and until the cooler water reaches the shower head, I feel even hotter as the faster flow delivers heat to my skin faster, but doesn't cool down until after the transit latency. Depending on whether heat is being lost continuously from your experiment, this effect may or may be relevant.
I must confess I thought I'd find more reasons in support of the (for most people) 'normal' way of power control.
If the plastic tube on the barb is intended to be the air supply to your experiment, then it looks a very poor match of fan and fan load resistance. That's a high-flow low-head fan, and it will be essentially stalled into that thin long tube.


text:
Q: Как проверить возвращаемый объект? Есть такая функция:
function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.addEventListener('load', () => resolve(img));
    img.addEventListener('error', reject); // don't forget this one
    img.src = url;
  });
}

Как сделать чтобы при наличии картинки происходило это :
$('.wrapper').append('
' + i + '
');

A: loadImage(url).then(address => $('.wrapper').append('
' + i + '
'))


text:
Q: Grafana loki - Bigtable - Requested column family not found I installed Loki distributed helm chart in my GKE cluster which uses GCS and Bigtable.
When I check loki ingester pod, I have following error:

level=error ts=2023-01-06T13:01:59.107018356Z caller=flush.go:146 org_id=fake msg="failed to flush user" err="store put chunk: rpc error: code = NotFound desc = Error while mutating the row '08:fake:d19362:logs' (projects//instances/mybigtable/tables/loki_index_2766) : Requested column family not found.

I have followed the docs https://grafana.com/docs/loki/latest/upgrading/#240, accordingly prepared the configmap. Here is the file:
---
# Source: loki-distributed/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
data:
  config.yaml: |
    auth_enabled: false
    chunk_store_config:
      max_look_back_period: 672h
    compactor:
      retention_enabled: true
      shared_store: filesystem
    distributor:
      ring:
        kvstore:
          store: memberlist
    frontend:
      compress_responses: true
      log_queries_longer_than: 5s
      tail_proxy_url: http://loki-loki-distributed-querier:3100
    frontend_worker:
      frontend_address: loki-loki-distributed-query-frontend:9095
    ingester:
      chunk_block_size: 262144
      chunk_encoding: snappy
      chunk_idle_period: 30m
      chunk_retain_period: 1m
      lifecycler:
        ring:
          kvstore:
            store: memberlist
          replication_factor: 1
      max_transfer_retries: 0
      wal:
        dir: /var/loki/wal
    limits_config:
      enforce_metric_name: false
      retention_period: 30d
      max_cache_freshness_per_query: 10m
      reject_old_samples: true
      reject_old_samples_max_age: 168h
      split_queries_by_interval: 15m
    memberlist:
      join_members:
      - loki-loki-distributed-memberlist
    query_range:
      align_queries_with_step: true
      cache_results: true
      max_retries: 5
      results_cache:
        cache:
          enable_fifocache: true
          fifocache:
            max_size_items: 1024
            ttl: 24h
    ruler:
      alertmanager_url: https://alertmanager.xx
      external_url: https://alertmanager.xx
      ring:
        kvstore:
          store: memberlist
      rule_path: /tmp/loki/scratch
      storage:
        local:
          directory: /etc/loki/rules
        type: local
    runtime_config:
      file: /var/loki-distributed-runtime/runtime.yaml
    schema_config:
      configs:
      - from: 2023-01-01
        store: bigtable
        object_store: gcs
        schema: v12
        index:
          prefix: loki_index_
          period: 168h

    server:
      http_listen_port: 3100
    storage_config:
      gcs:
        bucket_name: gcs-logs
      bigtable:
        instance: loki-indexes
        project: myproject-id
      boltdb_shipper:
        active_index_directory: /loki/boltdb-shipper-active
        cache_location: /loki/boltdb-shipper-cache
        cache_ttl: 24h
        shared_store: gcs

        #active_index_directory: /var/loki/index
        #cache_location: /var/loki/cache
        #cache_ttl: 168h
        #shared_store: filesystem

      filesystem:
        directory: /var/loki/chunks
    table_manager:
      retention_deletes_enabled: true
      retention_period: 672h

I am not able to push log index to bigtable. It seems table_manager needs to be updated but not sure with what?
The loki distributed service account is annotated with IAM service account, for workload identity rights to push towards object stores.
---
# Source: loki-distributed/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: loki-loki-distributed
  labels:
    helm.sh/chart: loki-distributed-0.67.0
    app.kubernetes.io/name: loki-distributed
    app.kubernetes.io/instance: loki
    app.kubernetes.io/version: "2.6.1"
    app.kubernetes.io/managed-by: Helm
  annotations:
    iam.gke.io/gcp-service-account: <iam-sa-account>@<project-id>.iam.gserviceaccount.com
automountServiceAccountToken: true

Any suggestion?


text:
Q: I'm receiving Flash install popups intermittently when navigating in Chrome browser I practice very safe security measures.  I run Windows 7 Ult 64-bit.  This question refers to fake Adobe Flash Upgrade popups on Chrome.
I know these popups are malware so I don't click on them.  When they've appeared I used the task manager to kill the process without touching the dialog box.
I've scanned my system repeatedly with three different programs and they all come up clean.  Also, I installed a browser checker extension that pronounces Chrome clean as well.  However, this popup asking me to install Flash keeps recurring.  It hasn't happened in Firefox, only Chrome.  I don't use any others.
Can a virus window popup occasionally on a clean system?  Are my virus checkers mistaken and I have a virus?  How can I get this to stop?  This has me stumped.

A: Can a virus window popup occasionally on a clean system?
Yes.  If the system is web browsing, and the system is clean of malware, the web content may still contain HTML code that causes the browser to pop up a window.  This can happen even if the system has no malware on it.
Are my virus checkers mistaken and I have a virus?
Maybe.  My guess is, no.  However, I'm basing that on rather little information, and so I could be wrong.
One thing you may wish to do is to run Process Hacker or Process Explorer to confirm that the offending advertisement is coming from the Chrome process.  Both software has a way to identify which process a window is coming from.  (Process Hacker involves dragging an icon; I think Process Explorer involves clicking on an icon.)
If the problem is indeed within Chrome, you might want to try erasing your Chrome Profile, or uninstalling Chrome, and seeing if either approach fixes the issue.  Even if that doesn't fix the issue, the good news is that the rest of your system is likely uninfected.
How can I get this to stop?
Ultimately, the answer is: you have to apply a solution that fixes the problem.
Let me give a hypothetical cause.  Your ISP is modifying HTTP traffic.  Before scoffing at such an unrealistic idea, know that major ISPs have been known to do that (search for "super cookie").  It could be that some advertising network is involved, as advertisement networks are known to be used my malware distributors.  IF that is the case, changing settings on your computer is unlikely to fix the problem.
If your router firmware had a vulnerability, and your router is now infected, then changing settings on your computer is unlikely to fix the problem.
Those are just two examples.  Modern systems are complex enough that there are lots of pieces, and so lots of potential areas where something could go wrong.  So, there is no one simple series of straight-forward steps that will guarantee the quickest resolution to this issue.  You can follow some advice, which might work, or might not.  If some advice resulted in the problem still existing, that doesn't mean that the advice was bad/senseless, because sometimes some possibilities are basically just as likely as other possibilities, especially when there is little solid detail available.
Your best course of action is to start following some good/likely advice, like what Ramhound suggested, but know that this might take some time/exploration to fully resolve, especially since we are talking about experiencing the Internet (which involves multiple computers/devices, networks, companies, etc.)  If simpler fixes aren't resolving the issue, some "more advanced" steps may eventually be needed, like network sniffing and reviewing the HTTP content/traffic.  Prepare for the possibility that this might take some time (and effort) to get resolved.  (Or, if you're sufficiently fortunate/lucky, it might not.)


text:
Q: install4j: What is the best way, to start my application over a link? I have a Java application. It is only a JAR file with some additional libs. Under Windows it's enough to make a doubleclick on it, if there are no problems with the installed JRE.
Now I want to make an installer with install4j. I am not able to use java.exe or javaw.exe for a simple link. If I do that, no link is created while the installation. At hits time I use directly the JAR file, but I am sure this will not work on each computer.
I searched for solutions on the internet, but I didn't find the answer I want.
Should I create a Launcher over install4j (EXE file), or should I use a batch file, or is there a better way? I think the best way would be a simple link with 'javaw.exe -jar MyApp.jar'?

A: The simplest and most robust approach is to create a launcher. This way, you let install4j deal with finding a JRE, generating platform-specific launch shortcuts, etc. The install4j 'Launcher' wizard is quite intuitive so you should be able to whip up a solution within an hour or two.

Alternatively, if you just want to script a shortcut to 'javaw.exe -jar MyApp.jar', there is little value in adding the install4j dependency.


text:
Q: My JavaScript pixel-drawing function cannot accept a width value of more than 9 I have had this function for a long time. I made it myself. For like half the time it wouldn't work at all, but then after a while I managed to fix it. However, this is not the reason this is here.

/*pixelPrint() is a function that allows you to print pixel art from specified data in a new format. This programming language is parsed into JavaScript and executed as so. You may take this function, but keep the credits.*/
function pixelPrint(indata){
    /*
    *           The Flux Brothers
    *       Major_Flux and Minor_Flux
    *           June 2021 product
    *           pixelPrint 1.0
    *
    * Free license use only if these credits are
    * included in this product. Removal of credits
    * will void your free license of use until you
    * return an exact copy of this license to this
    * product. You may grab this out of anyone's
    * project as long as they have this license on
    * it and they didn't tinker with the code.
    *
    * Do not tinker with the code or you will null
    * its ability to function assuming it does at
    * all with your setup. Email Major_Flux or any
    * person who knows him if you want to tinker
    * with the code if your setup doesn't allow it
    * to work so that a cross-browser/OS fix can be
    * put up for others to benefit from.
    */
    try{
        var colors = indata.split(";");
        var sizeData = colors[0];
        var pixWidth;
        var pixHeight;
        if(sizeData.indexOf("*") == 1){
            pixWidth = sizeData.split("*")[0];
            pixHeight = sizeData.split("*")[1];
        }else{
            return("
Error: size data not valid
");
        }
        if(pixWidth.indexOf(" ") > 0 || pixHeight.indexOf(" ") > 0){
            return("
Error: size data have spaces in them
");
        }
        var internals = "";
        var colorKey = 0;
        for(var y = 0; y < pixHeight; y++){
            internals = internals + "
";
            for(var x = 0; x < pixWidth; x++){
                colorKey++;
                internals = internals + "	";
            }
            internals = internals + "
";
        }
        var outdata;
        if(internals != "" && internals != null && internals != undefined && internals.indexOf("<") >= 0){
            outdata = "
" + internals + "
";
        }else{
            outdata = "
Error: var internals is somehow empty
";
        }
        if(outdata != indata){
            return(outdata);
        }else{
            throw("Data was not processed");
        }
    }catch(err){
        alert(err);
    }
}

This HTML is not part of any of the problem, just the JS. This HTML is to display what it does.

Usage: [width]*[height];color;color...

Example: 2*2;#dddddd;#aaaaaa;#aaaaaa;#777777, produces a 2 by 2 square with a pixelated outset effect to it.

Try it out below:

<input id="code" type="text"/><button onclick="document.getElementById('result').innerHTML = pixelPrint(document.getElementById('code').value);">Try</button>

Do not worry about the chopped up rows, I am sure you can find a CSS-based fix when you put the free function on your website.

The reason I put it here is that the width cannot be a two or more digit number, limiting it to only 1-9. Can you please figure out what is going on?

A: if(sizeData.indexOf("*") == 1)

this will only trigger if the * is the second character in the string, ie if there is only one digit.
Instead try
if(sizeData.indexOf("*") !== -1)

(trigger if a * is found anywhere in the string)


text:
Q: How to download files that were created by a slackbot? I created a bot which collects info from users in a workspace. It stores this info in a csv file on the local server. How do I download said file? I got this bit of code from Stack Overflow, attempted to contact the author but didn't get any response.
import requests
url = 'https://slack-files.com/T0JU09BGC-F0UD6SJ21-a762ad74d3'
token = 'xoxp-TOKEN'
requests.get(url, headers={'Authorization': 'Bearer %s' % token})

How do I obtain the URL & token of the file? What is the token? Is it the OAuth token of the bot?
Say I wished to download the file named stats.csv from the server that was created by the slackbot and I don't have it's URL, how would I download it?

A: I would not recommend to patch together the URL for downloading the file yourself, because Slack might change it and then your code breaks.
Instead, first get the current URL of the file by calling the API method files.info with the file ID. Then use property url_private as URL for download. Alternatively you can also call files.list to get the list of all files with IDs and their URLs.
To ensure you have access to the file its best to use the token from it's creator, e.g. your slackbot.
I also included the code to save the downloaded data to file and some rudimentary error handling. Note that the token is excepted to be set as environment variable names SLACK_TOKEN. This is much safer than putting it directly into the code.
Here is a complete example:
import os
import requests

token = os.environ['SLACK_TOKEN']
file_id = "F12345678"

# call file info to get url
url = "https://slack.com/api/files.info"
r = requests.get(url, {"token": token, "file": file_id})
r.raise_for_status
response = r.json()
assert response["ok"]
file_name = response["file"]["name"]
file_url = response["file"]["url_private"]
print("Downloaded " + file_name)

# download file
r = requests.get(file_url, headers={'Authorization': 'Bearer %s' % token})
r.raise_for_status
file_data = r.content   # get binary content

# save file to disk
with open(file_name , 'w+b') as f:
  f.write(bytearray(file_data))
print("Saved " + file_name + " in current folder")


text:
Q: Return indices of the two numbers such that they add up to a specific target I have the below question I am trying to solve:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

I have the below array as input - [2, 7, 11, 15] with target = 9.
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
This is my code -
import java.util.Random;

public class TwoSum {

    static int[] numbers = new int[] {2, 7, 11, 15};
    int[] indices = new int[numbers.length];

    public static int[] returnIndices(int target, int[] inputArr) {
        int[] indices = new int[2];
        int randomOne = new Random().nextInt(inputArr.length);
        int randomTwo = new Random().nextInt(inputArr.length);
        while(true) {
            if(target == inputArr[randomOne] + inputArr[randomTwo]) {
                indices[0] = randomOne;
                indices[1] = randomTwo;
                break;
            }
        }
        System.out.println("done");
        return indices;
    }

    public static void main(String[] args) {
        int[] output = returnIndices(9, numbers);
    }

}

Is this the right way to approach my problem?

A: You can use a hashmap to store the first array in the following manner:
   key  value(index in array)
    2 - 0
    7 - 1
    11 - 2
    15 - 3

Next get the target element which is 9, and start traversing your given array from index 0.
Element at index 0 is 2 --> calculate (9-2) = 7 --> check if 7 is a key in the hashmap
Additional Note: You need to take care of the following case:
arr = [3, 2, 1, 1] target = 6 (no answer exists in this case, but by the above method, when you calculate 6-3 = 3 you get index 0 as the answer.)
But this can easily be taken care of by checking whether (target-arr[i] == arr[i]) returns true or not. If it returns true and if the hashmap has two indices stored at the key arr[i], then return it as an answer, else proceed to the next element.

A: There are various ways to solve this question:

*

*Hashmap way - @mettleap answer has covered that one.

*Sort-Array way - I am going to explain its pseudo code to you.

Let us take an example to see it in action first. We are given arr = [5, 2, 1, 9, 7] elements in an array, and we are to find the indices of two elements if we can make 8.
If you look closely, then you will know if we sum 3rd + last element in an array, we will get 8, which means 2 and 4 would be our answer. So How would be land there? Let us go step by step

*

*Maintain a separate array of the same size, it will hold the indices of arr in its initial setup.
[5, 2, 1, 9, 7] = arr
[0, 1, 2, 3, 4] = index_arr

*Now sort arr in increasing order, and also sort the index_arr such that index of elements in arr in their initial setup is still in place.
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr

*Use the below pseudo code:
low  = 0
high = length of arr - 1

while (low < high) {
    sum = arr[low] + arr[high]

    if (sum  == number) {}
        print "index_arr[low]" and "index_arr[high]"
        break the loop and exit
    } else if ( sum < number ) {
        low = low + 1
    } else {
        high = high - 1
    }
}

Let us see psuedo code in action:
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr

Iteration # 01
low = 0 and high = 4
sum = arr[0] + arr[4] = 1 + 9 = 10
10 > 8 , means 'else' will be executed high = high - 1 = 4 - 1 = 3

Iteration # 02
low = 0 and high = 3
sum = arr[0] + arr[3] = 1 + 7 = 8
8 == 8 , means first 'if' condiion will execute, and will indices and exit the loop

Time Complexity  - O(n)
Space Complexity - O(n)

A: I have tried it in c#, It may help..
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            int[] nums = { 2, 7, 11, 15 };
            int target = 9;
            int[] result= TwoSumNumbers(nums, target);
        }

        public static int[] TwoSumNumbers(int[] nums, int target)
        {
            Dictionary<int, int> numsDict = new Dictionary<int, int>();

            for (int i = 0; i < nums.Length; i++)
            {
                int num = nums[i];

                if (numsDict.TryGetValue(target - num, out int index))
                {
                    return new[] { index, i };
                }

                numsDict[num] = i;
            }

            return null;
        }
    }

A: class Solution {
public int[] twoSum(int[] nums, int target) {
    int [] answer = new int[2];
    Map<Integer,Integer> values = new HashMap<Integer,Integer>();
    for ( int i=0; i < nums.length; i++){
        values.put(nums[i],i);
    }
    for ( int i=0; i < nums.length; i++){
        int val = target - nums[i];
        Integer secondIndex = values.get(val);
        if ( secondIndex != null && secondIndex != i){
            answer[0] = i;
            answer[1] = secondIndex;
            return answer;
        }
    }
    return answer;
}

}

A: C# Version
        using System;
        using System.Collections.Generic;
        using System.Text;
        using System.Linq;

        namespace MyBasics
        {
            class ArrayIndexForTarget
            {
                public static void Main()
                {
                    ArrayIndexForTarget find = new ArrayIndexForTarget();
                    int[] arr = new int[] { 9, 2, 3, 9, 10 };
                    int target = 11;
                    var result = find.IndexFinder(arr, target);

                    Console.ReadKey();
                }
             public  int[]  IndexFinder(int[]myArray,int target)
                {
                    int[] arr = new int[2];
                    Dictionary<int, int> dict = new Dictionary<int, int>();

                    for (int p=0; p < myArray.Length; p++)
                    {
                        int numberToFind = target - myArray[p];
                        if (dict.ContainsValue(numberToFind))
                        {
                            arr[0] = dict.FirstOrDefault(x => x.Value == numberToFind).Key;
                            arr[1] = p;
                            return arr;
                        }
                        else
                        {
                            dict.Add(p,myArray[p]);
                        }
                    }
                    return arr;

                }
            }
        }

A: class Solution {
    function twoSum($nums, $target) {
        $lenght = count($nums);
        $indices = array();
        for($i = 0; $i<$lenght-1; $i++){
            for($j=$i+1; $j<$lenght; $j++){
                if(($nums[$i]+$nums[$j]) == $target){
                    $indices[] = $i;
                    $indices[] = $j;

                    return $indices;
                }
            }

        }
    } }

A:  private static int[] findNumbersToAdd(int target, int[] array) {
    int[] answer = {-1, -1};
    int length = array.length;
    for (int i = 0; i < length; i++) {
        int var1 = array[i];
        for (int j = i + 1; j < length; j++) {
            int var2 = array[j];
            if (var1 + var2 == target) {
                answer[0] = i;
                answer[1] = j;
                break;
            }
        }
    }
    return answer;
}

A: Given you aren't focused on performance I would think a brute force approach would be fine. Here is a solution using streams and records.
record IndexPair(int index1, int index2) { };
IntStream.range(0, arr.length).boxed()
    .flatMap(i1 -> IntStream.range(i1, arr.length)
        .filter(i2 -> arr[i1] + arr[i2] == target)
        .mapToObj(i2 -> new IndexPair(i1, i2))
    .forEach(ip -> ...);

If you only want one solution then you could use findAny instead of forEach.

A: I tried this question and implement it using HashMap in Java and it works completely fine.
public class Solution {
public int[] twoSum(final int[] A, int B) {
    HashMap<Integer,Integer> hm=new HashMap<>();

    int index1=Integer.MAX_VALUE;
    int index2=Integer.MAX_VALUE;
    int diff=0;

    for(int i=0;i<A.length;i++){
        diff=B-A[i];
        if(hm.containsKey(diff)){
            index2=i;
            index1=hm.get(diff);
            return new int[] {index1+1,index2+1};
        }else{
            if(!hm.containsKey(A[i])){
                hm.put(A[i],i);
            }
        }
    }
// If Arrays doesnt have such pairs
if(index2 == (Integer.MAX_VALUE) || index1 == (Integer.MAX_VALUE)){
    return new int[] {};
}
return new int[] {index1+1,index2+1};

}
}

A: here is a simple solution with 2 running loops,
assuming the following

*

*you only need 2 numbers to get to the target.

*the solution exists (therefor no need to validate).
 public int[] TwoSum(int[] nums, int target) {
     for (int i=0; i< nums.Length; i++){
         for (int j=i+1; j< nums.Length; j++){
             if (nums[i] + nums[j] == target){
                 return new int[]{i,j};
             }
         }
     }
     return null;
 }

A: public  int[] sumofTwo(int[] numbers, int target)
{

    int[] answer = new int[2];
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i = 0 ; i < numbers.length ; i++)
    {
        if(map.containsKey(target - numbers[i]))
        {
            answer[0] = map.get(target - numbers[i]);
            answer[1] = i;
            return answer;
        }
        else
        {
            map.put(numbers[i],i);
        }
    }
    return null;
}
}

A: public class Main {

public static void main(String[] args) {
int [] arr = {4,7,1,-3,2};

    for(int i=0; i<arr.length-1; i++)
    {
        for(int j=0; j<=arr.length-2; j++)
        {
            if((arr[i]+arr[j+1])==6)
            {
                System.out.println("indices = "+"["+i +","+(j+1)+"]");
            }
        }
     }
  }
}


text:
Q: Process date and time imported from excel in R I have data from hard copy papers that must be first manually inputted in excel files to be later processed in R.
The data contain multiple readings of a variable (Reading) for different subjects (by ID) at different time points (e.g. 08:10, 08:20 etc.) on different dates (18.08.2014, 19.08.2014). A reference starting time (e.g., 08:00) and reference starting date (e.g., 18.08.2014) for each reading series is available.
The excel file that contains the data will look like this
ID  Reading Date        Time    Ref/Start Time  Ref/Start Date
1   12.1    18.08.2014  7:59    8:00            18.08.2014
1   26.34   18.08.2014  8:10    8:00            18.08.2014
1   35.2    18.08.2014  8:20    8:00            18.08.2014
1   30      18.08.2014  8:30    8:00            18.08.2014
1   12      19.08.2014  8:00    8:00            18.08.2014
1   13      19.08.2014  20:00   8:00            18.08.2014
1   12      20.08.2014  8:00    8:00            18.08.2014

These data have to be later processed in R. My goal is to generate a new column that contains the time of each reading in hours after the starting time point of each reading series. so to say to get (y) versus (x) where (x) is the time in hours from the start.
I imported this excel file to R now (saved previously as .csv), but I don't know how should I proceed now to generate the new column in R! should I even insert data in another way in excel first?
I hope that I was successful in clarifying what I need and that I can find a helping hand from somebody.
Many thanks in advance.

A: There are many ways to accomplish this. Here is one.
Assuming that you have the data in a csv file called time_d.csv you can do this:
time_d.csv looks like this:
ID  Reading Date    Time    Ref_time    Ref_date
1   12.1    18.08.2014  07:59   08:00   18.08.2014
1   26.34   18.08.2014  08:10   08:00   18.08.2014
1   35.2    18.08.2014  08:20   08:00   18.08.2014
1   30      18.08.2014  08:30   08:00   18.08.2014
1   12      19.08.2014  08:00   08:00   18.08.2014
1   13      19.08.2014  20:00   08:00   18.08.2014
1   12      20.08.2014  08:00   08:00   18.08.2014

You can see that I have changed the column headings slightly. Then, with the .csv in this format you can do this:
a1=read.csv("time_d.csv") #reads data into R data frame
a1$date_read=paste(a1$Date, a1$Time, sep=" ") #adds a new col to data frame
#by merging two existing cols

a1$date_ref=paste(a1$Ref_date, a1$Ref_time, sep=" ") #adds new col
a1=subset(a1,select=-c(Date,Time)) #removes the no longer needed cols
a1=subset(a1,select=-c(Ref_date,Ref_time)) #removes the no longer needed cols

a1$date_read=as.POSIXct(strptime(a1$date_read,"%d.%m.%Y %H:%M" )) #convert
#to date/time objects

a1$date_ref=as.POSIXct(strptime(a1$date_ref,"%d.%m.%Y %H:%M" ))

a1$Duration=difftime(a1$date_read,a1$date_ref, units="hours") #adds new col
#calculating the time difference in hours

For your particular data the format of date is important for this line:
as.POSIXct(strptime(a1$date_read,"%d.%m.%Y %H:%M" ))
If you change the format of date, then you should change this line code in R, also.
The end result looks like this:
  ID Reading           date_read            date_ref          Duration
1  1   12.10 2014-08-18 07:59:00 2014-08-18 08:00:00 -0.01666667 hours
2  1   26.34 2014-08-18 08:10:00 2014-08-18 08:00:00  0.16666667 hours
3  1   35.20 2014-08-18 08:20:00 2014-08-18 08:00:00  0.33333333 hours
4  1   30.00 2014-08-18 08:30:00 2014-08-18 08:00:00  0.50000000 hours
5  1   12.00 2014-08-19 08:00:00 2014-08-18 08:00:00 24.00000000 hours
6  1   13.00 2014-08-19 20:00:00 2014-08-18 08:00:00 36.00000000 hours
7  1   12.00 2014-08-20 08:00:00 2014-08-18 08:00:00 48.00000000 hours


text:
Q: Slow and fast variables in Non-linear Sigma model I am following Peskin Section 13.3, where they solve the nonlinear sigma model using Polyakov method. This system has Lagrangian
\begin{equation}
\mathcal{L}=\frac{1}{2g^2}|\partial_\mu\vec{n}|^2,\tag{13.67}
\end{equation}
where $\vec{n}$ is a unit vector. To find the renormalization flow of this Lagrangian the authors use a derivation first done by Polyakov where the unit vector field is decomposed in slow and fast variables. The slow vector field $\tilde{n}^i$ is obtained by integrating the Fourier modes of $n^i$ in the range $0<|k|<b\Lambda$ and rescaling the result to get another unit vector. After that the relation between $n^i$ and $\tilde{n}^i$ is given by
\begin{equation}
n^i(x)=\tilde{n}^i(x)(1-\phi^2)^{1/2}+\sum_{a=1}^{N-1}\phi_a(x)e^i_a(x),\tag{13.88}
\end{equation}
where the $e^i_a$ are unit vectors orthogonal to $\tilde{n}^i$ and the $\phi_a$ are expansion coefficients. Until now this expansion is completely general, however the authors state that the coefficients $\phi_a$ are fast variables that only have Fourier components in the range $b\Lambda<|k|<\Lambda$. This make sense intuitively given that $\tilde{n}^i$ is constructed only from slow Fourier components. Nevertheless, I would like to have a more formal derivation that this construction gives $\phi_a$ with Fourier components only exactly in the given range. Can anyone help me with that? I tried to play with the equations without success.


text:
Q: Is it compulsory to learn C/C++ before learning PHP? Can someone PHP Developer tell me? , what is better for me to learn PHP ??
Websites, Tutorials, or any other good information, which is helpful for me to learn PHP..
Thanks alot in advance.

A: No. You can learn whatever language you want first. PHP is arguable easier to learn for a beginner than C or C++, but beginners learn  them as their first language all the time.
Knowing any other programming may help you learn PHP more quickly, but none are required.
PHP.net is a good resource for the standard library, and it provides a language reference as well. That is all I ever needed to use to learn the language from scratch.


text:
Q: Something went wrong. Newbie error package com.example.jonathan.test01;

import android.content.Context;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

    public class Test01Surface extends SurfaceView implements Runnable{

    SurfaceHolder ourHolder;
    Thread ourThread = null;
    boolean isRunning = true;

    public Test01Surface(Context context) {
        super(context);
        ourHolder = getHolder();
        ourThread = new Thread(this);
        ourThread.start();
    }

    @Override
    public void run() {
        while(isRunning){
            if(!ourHolder.getSurface().isValid());
                continue;

            Canvas drawing = ourHolder.lockCanvas();
            drawing.drawRGB(72, 98, 198);
            ourHolder.unlockCanvasAndPost(drawing);
        }

    }
}

I've been getting an Unreachable statement error at the line Canvas drawing = ourHolder.lockCanvas();
I'm just following a tutorial video in Programming Android Applications. Please help me remove this error. I'm thinking that I should change the continue; statement to something else but since I'm new I don't know what to change it to. Or maybe the cause of the error is something else?

A: remove the ; at the end of this line:
if(!ourHolder.getSurface().isValid());

A: continue; is always called and Canvas drawing = ourHolder.lockCanvas(); is unreachable because you have a ";" at the end of the if statement

A: As already said by Jens the fault is the ; at the end of your if statement.
For better readability of your code make it like this: also like this you probably won't do this fault again.
if(!ourHolder.getSurface().isValid()){
  continue;
}


text:
Q: Clicar num buttom e aparecer um prompt Eu tenho um button, e pretendo que, ao clicar, apareça um prompt a perguntar se quer mesmo sair da página, com 2 opções: Confirmar ou cancelar.
Caso clique em confirmar, ele vai para o link do button, caso contrário, o prompt fecha e não acontece nada.
Como posso fazer isso?

A: Você pode fazer com uma tag de link mesmo () e a função confirm do JavaScript. Exemplo:

Sair do site

Detalhando:
É adicionado o evento onclick na tag a que retorna o resultado da função confirm.
A função confirm é nativa do JavaScript, e abre uma janela exibindo o texto passado como parâmetro, um botão de 'OK' e um de 'Cancelar'. Caso o usuário clique em 'OK', a função retorna true. Caso o usuário clique em 'Cancelar', a função retorna false.
Ao retornar false para o evento onclick, ele interrompe a execução da ação padrão do elemento, que no caso da tag a é a chamada para o link indicado no atributo href.

Obs: Semanticamente, o mais indicado para esta ação seria a utilização da tag , pois por definição, indica o link da página atual com outra página. Você pode ler mais sobre a definição e uso da tag a em: https://www.w3schools.com/tags/tag_a.asp

A: Pode fazer colocando o link da página que deve ser direcionada já no JavaScript:

btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  var b = confirm('Tem certeza que quer sair?');
  if (b){
    window.location = "http://pt.stackoverflow.com";
  }
});
<button id="btn">Sair</button>

A: Solução alternativa utilizando um button:

function confirmaSaida() {
  var confirmado = confirm("Deseja realmente sair da página?");

  if (confirmado === true) {
      self.location = "https://www.google.com";
  }
}
<input type="button" value="Sair da página" onclick="confirmaSaida();" />

Colocando o link na tag input:

function confirmaSaida() {
  var confirmado = confirm("Deseja realmente sair da página?");

  if (confirmado === true) {
      self.location = document.getElementById("btn").getAttribute("data-link");
  }
}
<input id="btn" name="btn" type="button" value="Sair da página" onclick="confirmaSaida();" data-link="https://www.google.com" />


text:
Q: A public action method '..' was not found on controller '..' I wanted to put a random image on every viewpage of my mvc project. So i created a method that returns a partialView and call that method in the shared Layout page.
This works fine when I try to login with a correct username and password. The used is loged in and every page contains a random image. But when I  give the invalid combination of username and password. The shared layout page does not find the controller I want to call with my @Html.Action and actualy the login view should be returned with an error message 'invalid combination of username and password' and ofcourse, with the random image.
InnerException:

{"A public action method 'RandomSponsor' was not found on controller 'Project.WebUI.Controllers.HomeController'."}

My Html.Action in shared layout.
@Html.Action("RandomSponsor", "Home")

Method in homecontroller.
    [HttpGet]
[ChildActionOnly]
public ActionResult RandomSponsor()
{
    var model = service.getRandomSponsor();
    return PartialView("RandomSponsor", model);
}

The getRandomSponsor method works fine, this one always returns one random string value that is returned to the RandomSponsor.cshtml view.
RandomSponsor.schtml (only contains the image string)
<img src="~/Content/Images/Advert/@(Model)" alt="a" />

I searched the web for this problem but didn't found a solution, does anyone know the answer to this one?
Might it be something with HttpGet of HttpPost?
Regards.

A: If the executing request is a POST, then it will try to find a method RandomSponsor accepting HttpPost. If this makes sense, you could remove HttpGet and that should do the trick.

A: This will happen if the request is a POST but the controller method is annotated [HttpGet]. For example, you might issue a POST that returns a view containing partial views called with @Html.Action, using controller methods annotated with [HttpGet]. If the original request is a POST, all of the controller methods subsequently called will need to support POST.
To fix it you can use the AcceptVerbs attribute to specify that your controller method accepts both POST and GET:
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]

A: Received this error all of the sudden on several different PartialViews (not all of them) when customizing an install of MVCForum. We had not made any changes to the methods or views concerning the errors so it was really frustrating as to why they were broken.
After trying the other solutions  on this post and others, went back through the changes made and what ended up stopping the errors was that we had changed the bindings in IIS to another domain that had the 'enforce lower case url' URL Rewrite rule enabled.
When we disabled the enforce lowercase rule, the errors stopped and the site worked as it was supposed to. It's not a URL Rewrite issue (I don't think) because we are able to enforce www using it with no errors. It's a lowercase rewrite issue. Didn't matter if we had the lowercase rule before or after the www rule.
This solution probably doesn't apply to many cases of this error, but it worked for us. Hopefully someone else can benefit from such a simple fix.

A: I just solved this issue strangely enough on my local PC, by making sure my entire request path was lower case. So give that a try.

A: This can also happen if you have many layers of calls that start with a POST (I had an action returning a view returning a partial view calling RenderAction), then the call to RenderAction will still look for a POST method
Very similar to this problem that I had here - How to solve "public action method 'methodActionName' was not found on controller 'controllerNameController'"
And if you want to continue to accept the HTTP GET verb and fix the problem of cascading post request into a get request add this to your method
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
Keep in mind that [HttpGet] is the same as [AcceptVerbs(HttpVerbs.Get)]

A: In my case, the same issue was happening randomly with the implicit :
using (Html.BeginForm())

Changing above to :
using (Html.BeginForm("Action","Controller", FormMethod.Post))

fixed this issue.

A: I know this is a pretty old thread - but as it's top Google result I thought I'd add a potentially missing link for MVC.Net 5.2.6.
Scenario
I was attempting to call a child action via @Html.Action("ActionName", new { Id = 123})
and received an error much like the above, but none of the other solutions worked.  I could hit the controller action externally (i.e. HttpGet), but the child action kept throwing the exception and was driving me nuts!
The solution I found
After two-ing and fro-ing for some time, I started playing with my routing attributes.  I had the controller set up as:
[Route("{action}")]
[RoutePrefix("Prefix")]
[RouteArea("AreaName")]

As there was only one public action i wanted, "Index", I removed the {action} and placed an explicit route attribute on the public action and put my ChildActionOnly attribute back on the child.
After I did that, I hit the run and hey presto - the action was hit.
Might be worth a try if you're getting this error while using attribute routing.  Note I did attempt to route the child action and this didn't work.

A: Did you give it a shot with Html.RenderAction? It is typically faster then Html.Action as it interact directly into the response stream as opposed to building a string.
You can view the following topics for more info:

*

*What is the difference (if any) between Html.Partial(view, model) and Html.RenderPartial(view,model) in MVC2?

*Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction
Another thing to note is that for Html.Action or Html.RenderAction, your view doesn't need to be in Shared folder, that is only required if you use Html.Partial or Html.RenderPartial


text:
Q: Android Java String operations not working I've the problem that all string operations doesn't seem to work:
String received_message = new String(lmessage, 0, packet.getLength());

Note: received_message is "start.hello.end"
if (received_message.startsWith("start.") && received_message.endsWith(".end"))
{
    result = 1;
}

received_message = received_message.replace("start.", "");
received_message = received_message.replace(".end", "");

Result:
result is 0, received_message is still "start.hello.end"
--
But this is working correctly:
if (received_message.startsWith("s") && received_message.endsWith("d"))
{
    result = 1;
}

received_message = received_message.replace("s", "");
received_message = received_message.replace(".", "");

It's just working if I make this functions with a single Char.
How can I get it working for whole Strings?

A: The problem was the encoding. The Windows server used Unicode, the Android system used UTF-16 as standard. So the String contained some invisible characters..


text:
Q: Display name from db instead of id not working correctly I am trying to display a name from db instead of id (sittername) but my view it shows the same name in all rows which is wrong.
What I want is to get the name from db for every id in $ids array.
I hope you can help me. I am using MVC in CodeIgniter framework..
My Controller:
$results = $this->Admin_model->getSitter_Requests($config["per_page"], $page);

        foreach ($results as $item)
        {
            $data['data1'] = [];
            $sitter_job_id = $item['sitter_job_id'];

My problem is in this part of code, sittername has only one name which come from the last id in my $ids array. what I want is to get the name from db for every id in $ids array.
    $ids = $item['sitter_id'];

    foreach ((array)$ids as $id)
    {
        if($id != 0 && $id != null){
            $sittername = $this->Admin_model->get_sitter_name($id[0]);
            $data["sittername"] = $sittername;
        }

    }
    }

        $data["results"] = $results;
        $data["links"] = $this->pagination->create_links();

        $this->load->view('admin/superadmin_sitter_requests',$data);

My Model:
public function getSitter_Requests($limit, $start)
    {
        $this->db->select('*');
        $this->db->limit($limit, $start);
        $query = $this->db->get('ps_sitter_jobs');
        if ($query->num_rows() > 0) {
            foreach ($query->result_array() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return array();

    }
function get_sitter_name($id) {

        $this->db->select('fname');
        $this->db->where('id', $id);
        $query = $this->db->get('ps_cms_users');
        return $query->row()->fname;

    }
ps_sitter_jobs table columns:
sitter_job_id                  | int(11)   PRI
sitter_id                      | int(11)   FK from ps_cms_users(id)
seller_sitter_id               | int(11)
token_trans_id                 | varchar(255)
camp_id                        | int(11)
book_id                        | int(11)
sitter_status                  | enum('0','1','2','3','4')
created_date                   | datetime
modify_date                    | datetime
assign_new_sitter_btn_disabled | int(11)
refund_btn_disabled            | int(11)
===================================================
ps_cms_users table columns:
id           | int(11)       PRI
email        | varchar(128)
password     | varchar(128)
fname        | varchar(128)
lname        | varchar(128)
mobile       | varchar(20)
roleId       | int(4)
createdBy    | int(11)
createdDtm   | datetime
updatedBy    | int(11)
updatedDtm   | datetime
partner_type | int(11)
state        | int(11)
city         | int(11)
userDesc     | varchar(255)
==================================================

My View:
if(count($results) > 0){
    foreach ($results as $result){
        $result_id = $result['sitter_job_id'];
    ?>

                <?php echo '#'.$result_id; ?>

                <?php
                if($result['sitter_id'] == 0 || $result['sitter_id'] == null)
                {
                    echo "Sitter Not Assigned yet";
                }
                else
                {
                    echo $sittername;

                }
    }
    ?>

A: Not very easy to fully understand what you're trying to accomplish here, but I think you could use a JOIN instead of looping trough your first results. Here's a suggestion. (I have left out pagination and HTML formatting for the purpose of clarity)
Your Controller
$data["results"] = $this->Admin_model->getSitter_Requests();
$this->load->view('admin/superadmin_sitter_requests', $data);

Your Model (Admin_model.php)
public function getSitter_Requests()
{
    $this->db->join('ps_cms_users', 'ps_cms_users.id = ps_sitter_jobs.sitter_id');
    return $this->db->get('ps_sitter_jobs')->result();
}

Your View (admin/superadmin_sitter_requests)
foreach ($results as $result)
{
    echo 'SITTER_JOB_ID = ' . $result['sitter_job_id'];
    echo 'SITTER_ID = ' . $result['sitter_id'];
    echo 'SITTER_FIRSTNAME = ' . $result['fname'];
}

I hope this helps.


text:
Q: find the frequency of occurences of any given word in a sentence using java I'm trying to find the occurrence of given word in a sentence using java.
My input contains two lines, first line contains one word and second line contains the sentence.
Sample Input:
love
There is only one happiness in this life,to love and be loved.

Sample Output:
1

I tried below below program to print the value 1 - but its printing for each word rather for same word. Can someone please help me to fix this?
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

    public static void main(String args[]) throws IOException {

        String test = "love\n" + "There is only one happiness in this life,to love and be loved.";

        System.out.println(test);

        Map<String, Integer> wordCount = Arrays.stream(test.split("\\s+"))
                .collect(Collectors.toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2));

        // Print word frequencies
        wordCount.forEach((k, v) -> System.out.printf("%s %d\n", k, v));

    }

}

A: This can be fixed with a simple if statement. All you have to do is make sure the current key matches the first line. In order to do this, get the first line by itself before mapping the string.

String test = "love\n" + "There is only one happiness in this life,to love and be loved.";
// Get first line "love"
String word = test.split("\\n")[0];
/*
 * Get second line (the line to be mapped)
 * "There is only one happiness in this life,to love and be loved."
 */
String senctence = test.split("\\n")[1];
System.out.println(test);

Map<String, Integer> wordCount = Arrays.stream(senctence.split("[\\s+]"))
        .collect(Collectors.toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2));

// Print word frequencies
wordCount.forEach((k, v) -> {
    // Check if the key matches the primary input
    if (k.equals(word))
        System.out.printf("%s %d\n", k, v);
});

A: I think first problem was to input key value into count. Try separately:
String key = "love";
String test = "There is only one happiness in this life,to love and be loved.";

Then
    // Print word frequencies
    wordCount.forEach((k, v) -> {
        if(k.equalsIgnoreCase(key))
        System.out.printf("%s %d\n", k, v);
    });


text:
Q: Computing coefficients of polynomials from roots in $O(n\log{n})$ time Suppose I have a univariate polynomial $p$ over a prime-order finite field $\mathbb{F}_q$ whose roots I know.
Suppose that the roots of $p$ are always an $n$-sized subset of $R=\{1,2,\dots,N\}, N < q$ (or, if it helps, $R = \{\omega^0, \omega^1, \dots,\omega^{N-1}\}$ where $\omega$ is an $N$th primitive root of unity in $\mathbb{F}_q$).
I want to stress that roots are subsets of $R$, and not $R$ itself. For example, the roots could be $\{5,9,13,20,21,22,79\}$.
I know I can interpolate $p$ by starting with monomials for each root as leaves of a binary tree: $(x-5), (x-9), \dots, (x-22), (x-79)$. Then, I can "multiply up the tree recursively" and obtain $p$ as the root of the tree. With FFT-based multiplication, I can do this in $O(n\log^2{n})$ time when I have $n$ roots.
My question: Does there exist an $O(n \log{n})$ algorithm to interpolate $p$ given its roots? I realize that, for particular choices of roots, interpolating $p$ is very fast. For example, $p(x) = x^N - 1$ can be interpolated in $O(N)$ time from its $\{\omega^0, \omega^1, \dots,\omega^{N-1}\}$ roots [1]. However, I am interested in faster algorithms for roots that are arbitrary subsets of $\{\omega^0, \omega^1, \dots,\omega^{N-1}\}$.
I am also aware of the relationship between coefficients and roots, but I don't immediately see how this can be leveraged to get a faster algorithm (e.g., previous question here).
[1]: $O(N)$ time because writing $p$ down requires $O(N)$ space in its uncompressed form.


text:
Q: Android studio not running .sh script with Jsch Whenever I try to execute a sh script via Jsh nothing happens , however when I execute it through a normal ssh session it works fine , I haven't been able to get a single sh file to work/run regardless of the contents of the sh file.
I have tried
channelssh.setCommand("/home/exiatron00/Desktop/bash test.sh");
channelssh.setCommand("/home/exiatron00/Desktop/./test.sh");
channelssh.setCommand("/home/exiatron00/Desktop/test.sh");

A: I don't see anything wrong with your command, so I would have to assume it's your setup.
Are you sure you're even logging into your server? I would check your last logs to make sure you are even connecting.
Are you on the same network as the machine you're attempting to connect to? If you aren't on wifi I would assume your machine is hidden behind a NAT.


text:
Q: Injected remote thread crashes when using a large local array? This Windows example creates a remote thread in another process
#include <Windows.h>
#include <Winternl.h>

#define RET_INSTRUCTION 0xC3

DWORD WINAPI shellcode_start(LPVOID lpParameter)
{
    DWORD myStackArray[1000];

    return 0;
}

void InjectShellcode(unsigned char* shellcode, int length, DWORD dwPID)
{
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);
    LPVOID shellcodeAddr = VirtualAllocEx(hProcess, NULL, length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    WriteProcessMemory(hProcess, shellcodeAddr, shellcode, length, NULL);
    HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)shellcodeAddr, NULL, 0, NULL);
    WaitForSingleObject(hThread, INFINITE);
    VirtualFreeEx(hProcess, shellcodeAddr, 0, MEM_RELEASE);
    CloseHandle(hThread);
    CloseHandle(hProcess);
}

int main(int argc, char* argv[])
{
    unsigned char* shellcode_end = (unsigned char*)shellcode_start;
    while (*shellcode_end++ != RET_INSTRUCTION) {};
    unsigned int sizeofshellcode = shellcode_end - (unsigned char*)shellcode_start;

    InjectShellcode((unsigned char*)shellcode_start, sizeofshellcode, 12924);

    return 0;
}

The target process crashes when a large array is defined
DWORD myStackArray[1000];

The shellcode function starts with this prologue
DWORD WINAPI shellcode_start(LPVOID lpParameter)
{
00000001400010F0  mov         qword ptr [rsp+8],rcx
00000001400010F5  push        rbp
00000001400010F6  mov         eax,11A0h
00000001400010FB  call        __chkstk (0140001210h)
0000000140001100  sub         rsp,rax
0000000140001103  mov         rbp,rsp
...

But, if a small array is defined
DWORD myStackArray[500];

the process remains alive with this prologue
DWORD WINAPI shellcode_start(LPVOID lpParameter)
{
00000001400010F0  mov         qword ptr [rsp+8],rcx
00000001400010F5  push        rbp
00000001400010F6  sub         rsp,8D0h
00000001400010FD  mov         rbp,rsp
...

Update
Adding this linker option /Gs8192 prevents the crash and generates this prologue

The number of bytes that local variables can occupy before a stack
probe is initiated.

0000000000400000 48 89 4C 24 08       mov         qword ptr [rsp+8],rcx
0000000000400005 55                   push        rbp
0000000000400006 48 81 EC C0 14 00 00 sub         rsp,14C0h
000000000040000D 48 8D 6C 24 20       lea         rbp,[rsp+20h]
0000000000400012 48 C7 45 00 00 00 00 00 mov         qword ptr [rbp],0

Question
When a remote thread is created, why does the injected process crash for a large array?


text:
Q: Пронумерованный список Как сделать чтобы цифры были жирные.
Пример:

1. ABC
2. abc
3. AaB

A:

Coffee

Tea

Milk


text:
Q: Saving to m-2-m with checkboxes So i'm trying to use [Slauma's Answer][1]
What i have done so far,
Model ViewModelProspectUsers
    public int Id { get; set; }
    public string User { get; set; }
    public IEnumerable<ViewModelUserProspectSelect> Prospects { get; set; }

Model ViewModelUserProspectSelect
    public int ProspectID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }

View UserInProspect
@model OG.ModelView.ViewModelProspectUsers

@using (Html.BeginForm())
{

        @Html.HiddenFor(model => model.Id)
        Prospects for User
@Html.DisplayTextFor(model => model.User)

Please Select Prospects you wish to assign to this User.

            @Html.EditorFor(model => model.Prospects)

    <input type="submit" value="Save changes" />
    @Html.ActionLink("Cancel", "Index")

}

Editor View Located under ChangeUserInfo/EditorTemplates/*_ViewModelUserprospectSelect.cshtml*
@model OG.ModelView.ViewModelUserProspectSelect

@Html.HiddenFor(model => model.ProspectID)
@Html.HiddenFor(model => model.Name)
test
@Html.LabelFor(model => model.IsSelected, Model.Name)
@Html.EditorFor(model => model.IsSelected)

[Get] Method UserInProspect Action
public ActionResult UsersInProspect(int id = 0)
    {
        var data = db.UserProfiles
        .Where(s => s.UserID == id)
        .Select(s => new
        {
            ViewModel = new ViewModelProspectUsers
            {
                Id = s.UserID,
                User = s.UserName
            },
            prospects = s.Prospects.Select(c => c.ProspectID)
        })
        .SingleOrDefault();

        if (data == null)
            return HttpNotFound();

        // Load all companies from the DB
        data.ViewModel.Prospects = db.Prospect
            .Select(c => new ViewModelUserProspectSelect
            {
                ProspectID = c.ProspectID,
                Name = c.ProspectName
            })
            .ToList();

        // Set IsSelected flag: true (= checkbox checked) if the company
        // is already related with the subscription; false, if not
        foreach (var c in data.ViewModel.Prospects)
            c.IsSelected = data.prospects.Contains(c.ProspectID);

        return View(data.ViewModel);

    }

[HttpPost] Method UserInProspect Action
    public ActionResult UsersInProspect(ViewModelProspectUsers viewModel)
    {
        if (ModelState.IsValid)
        {
            var subscription = db.UserProfiles.Include(s => s.Prospects)
                .SingleOrDefault(s => s.UserID == viewModel.Id);

            if (subscription != null)
            {
                // Update scalar properties like "Amount"
                //subscription.Prospects = viewModel.Prospects;
                //subscription. = subscription.
                //List<string> myList = new List<string>();
                //myList = viewModel.Prospects.Cast<String>().ToList();

                //IEnumerable<dbProspect> Isubscription = subscription.Prospects;
                ////or explicit:
                //var iPersonList = (IEnumerable<dbProspect>)myList;

                // or more generic for multiple scalar properties
                // _context.Entry(subscription).CurrentValues.SetValues(viewModel);
                // But this will work only if you use the same key property name
                // in ViewModel and entity

                foreach (var prospect in viewModel.Prospects)
                {
                    if (prospect.IsSelected)
                    {
                        if (!subscription.Prospects.Any(
                            c => c.ProspectID == prospect.ProspectID))
                        {
                            // if company is selected but not yet
                            // related in DB, add relationship
                            var addedProspect = new dbProspect { ProspectID = prospect.ProspectID };
                            db.Prospect.Attach(addedProspect);
                            subscription.Prospects.Add(addedProspect);
                        }
                    }
                    else
                    {
                        var removedProspect = subscription.Prospects
                            .SingleOrDefault(c => c.ProspectID == prospect.ProspectID);
                        if (removedProspect != null)
                            // if company is not selected but currently
                            // related in DB, remove relationship
                            subscription.Prospects.Remove(removedProspect);
                    }
                }

                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        return View(viewModel);
    }

A:
Added Reference to my Controller using
  OG.Views.ChangeUsersInfo.EditorTemplates;

Remove that again. "EditorTemplates" should not be a namespace.

Added Editor Template under
  Views/ChangeUsers/Info/EditorTemplates/ViewModeluserProspectSelect.cs

An "editor template" isn't a C# (.cs) code file but a Razor view (.cshtml). Move the file ViewModelUserProspectSelect.cs to the folder where also ViewModelProspectUsers.cs is and change its namespace to the same for both classes (OG.Models).
(Why is there a subfolder /Info/ in the path??? Or is it a typo and just Views/ChangeUsersInfo/EditorTemplates is meant? I assume that the controller has the name ChangeUsersInfoController, right?)
Then create a new file ViewModelUserProspectSelect.cshtml in the Views/ChangeUsersInfo/EditorTemplates folder that contains the view from the other answer, this one:
@model OG.Models.ViewModelUserProspectSelect

@Html.HiddenFor(model => model.ProspectID)
@Html.HiddenFor(model => model.Name)

@Html.LabelFor(model => model.IsSelected, Model.Name)
@Html.EditorFor(model => model.IsSelected)

And the contentContainer2 div element in your main view should look like this:

Please Select Prospects you wish to assign to this User.

    @Html.EditorFor(model => model.Propects)


text:
Q: Replace value of certain row in csv based on string value of adjacent row How can I replace value of rows in column 'B' if the rows of column 'A' has a (string) supposed I have an existing csv. Like if Dog is in row, change it's adjacent row in column B
I'm looking for something like this:
for i in df['A']:
if i =='Dog','Cat':
//replace value Black in column B to White

Example:
Original CSV
A,B
Dog,Black
Cat,Black
Mouse,Black
Pig,Black

Replaces to:
A,B
Dog,White
Cat,White
Mouse,Black
Pig,Black

Here is my code, nothing shows in my csv, I don't know why
import pandas as pd
import csv

df = pd.read_csv("test.csv")
data = { 'A': [ 'Dog', 'Cat', 'Pig'] }
df = pd.DataFrame(data)
class Description(dict):
     def __missing__(self, key):
         return ''

desc = Description()
desc['Dog'] = 'White'
desc['Cat'] = 'White'
desc['Pig'] = 'White'
df['B'] = df['A'].apply(lambda x: desc[x])

A: Define a UDF and simply apply the function in the A column.
def surnamemap(x):
        if x =="dog":
             return 'Black'
        elif x == "cat":
             return 'White'

 df['B'] = df['A'].apply(lambda x: surnamemap[x])

This should help.

A: This will work:
import pandas as pd
df = pd.DataFrame([["Dog","Black"], ["Cat","White"]], columns=['A', 'B'])
df.loc[df['A'] == "Dog", 'B'] = ["White"]

A: IIUC:
df.loc[df['A'].isin(["Dog","Cat"]), 'B'] = "White"

Then save:
df.to_csv('test.csv')

OR:
df.to_csv('test.csv',index=False)

see what you prefer


text:
Q: JS Drag and Drop: Make a div with specific classname not droppable Im having some trouble implementing drag and drop to my project. Im making a Kanban tool like trello. I have divs that are "lists" and those lists have other divs inside that are "cards". When functioning ideally I would be able to put cards inside different lists, but not a list inside a list. However with my code right now I'm able to drag a list inside a list.
I would like to know how to find the html class of what I'm dragging, so that I can use that to validate.
So what I want to happen is that I can be able to drag a list, but not drop it inside another. I should however be able to rearrange the lists with cards inside, and move cards to different lists.
Thanks!
This is the Javascript:
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list")  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function allowDrop1(ev) {
    ev.preventDefault();
}

function drag1(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" ) {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}
´´´´
And this is a list from the html:
```

 test

 test 2

A: I fixed it! Also added functionality to drag a list inside the list-wrapper of a another list and make them switch places.
Here is the new code:
var dragget;
var source;
var dragged;

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id)
    dragget = event.target.className;
    dragged = event.target;
    source = ev.target.parentElement;
}

function drop(ev) {
    ev.preventDefault();
    if ( ev.target.className == "list" && dragget == "card" )  {
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
}

function drop1(ev) {
    ev.preventDefault();
    if ( event.target.className == "listWrap" && dragget == "list" ) {

        var data = ev.dataTransfer.getData("text");
        source.innerHTML = ev.target.innerHTML;
        ev.target.innerHTML = "";
        ev.target.appendChild(dragged);
    }
}

HTML:

 test

 test 2


text:
Q: Crackling and sound delay in Ubuntu 20.04 Whenever I open any video or audio with my earphone plugged in I get to hear a crackle before I actually hear the audio.
I used to play 2 audios, with one audio in mute and other audio which I want to hear in volume up. When I use this method I don't hear any sort of disturbance.
I tried:

*

*pulse audio kill

*removed speech dispatcher

*nano /etc/pulse/default.pa
Nothing solved the problem.


text:
Q: How to fix a flickering led Matrix and lcd menu screen I'm making a project where you have a led matrix, LCD and 7 different sensors. Each sensor will display a different message to the matrix and has it's own sub menu on the LCD.
I've created a menu for switching between the sensors. A rotary encoder is used to navigate in the menu. (A pin has an interrupt on change for executing only the void loop when the pin has changed) Also a select button is used to run the program of a menu item.( a sensor program like prg_Pong(), prg_Flame());
I want to display the menu items on the LCD (no I2C). Now my problem is my main menu items are displayed correctly (with no flicker because of the interrupt on the rotary encoder pin)
but when I press the button to run for ex prg_Pong() the lcd prints message running pong but the message is flickering and the message on the led matrix is good (static).
I've found a solution by adding a delay(300); in the loop after drawMenu but when I do that and enter prg_Pong();
the message on the led matrix starts to flicker at the delay time and the menu item "running pong" doesn't flicker anymore.
The functions displayData(),mtx_clear() are used for the led matrix and they are working. Because when I remove the functionality of the LCD the message is displayed correctly.
void loop() {
  drawMenu(RotaryEncoder());
  delay(300);
}

void drawMenu(byte rotaryPosition) {
  stateBtnSelect = digitalRead(BTN_SELECT);
  if (stateBtnSelect == HIGH && previousBtnState == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;
    time = millis();
  }
  previousBtnState = stateBtnSelect;

  //Switch the value of the rotary encoder
  switch (rotaryPosition) {
    case 0:
      displayMenuItem(0);
      if (state == HIGH) {
        prg_Pong();
      }
      break;
    case 1:
      displayMenuItem(1);
      if (state == HIGH) {
        prg_Ascroll();
      }
      break;
    case 2:
      displayMenuItem(2);
      if (state == HIGH) {
        prg_Clock();
      }
      break;
    case 3:
      displayMenuItem(3);
      if (state == HIGH) {
        prg_Flame();
      }
      break;
    case 4:
      displayMenuItem(4);
      if (state == HIGH) {
        prg_Heartbeat();
      }
      break;
    default:
      break;
  }
}

//Display a menu item
void displayMenuItem(byte item)
{
  //menu strings (mai n categories)
    String menuItems[MAX_MENU_ITEMS] = {"Pong game", "A. Scroller", "Clock", "Flame/temp", "Heartbeat"};
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Menu");
    lcd.setCursor(0, 1);
    lcd.write(byte(0));
    lcd.print(menuItems[item]);
}

void prg_Pong()
{
  lcd.clear();
  delay(100);
  lcd.print("run pong");
  mtx_clear();

  //print cirlce once
  MessageEncoder(ReturnLetter(24), BitStream);
  for (int j = 0; j < 8; j++)
  {
    displayData(~BitStream[j] & Kolommen[j]);
  }
}

A: you are clearing the lcd display frequently, so it will look like flickering.
i used a two more variables to find, Is there any need to update the display? change the display contents only if required, I didn't compile code but hope this will  solve your problem, i use similar technique in my projects.
prev_menu=-1;
update_display=true;

void loop() {
  drawMenu(RotaryEncoder());
  delay(300);
}

void drawMenu(byte rotaryPosition) {
  stateBtnSelect = digitalRead(BTN_SELECT);
  if (stateBtnSelect == HIGH && previousBtnState == LOW && millis() - time > debounce) {
    if (state == HIGH)
        state = LOW;
    else
      state = HIGH;
    time = millis();
    update_display=true;
  }
  previousBtnState = stateBtnSelect;

    if(prev_menu != rotaryPosition)
            update_display=true;
    else
        update_display=false;

  //Switch the value of the rotary encoder
  switch (rotaryPosition) {
    case 0:
      displayMenuItem(0);
      if (state == HIGH) {
        prg_Pong();
      }
      break;
    case 1:
      displayMenuItem(1);
      if (state == HIGH) {
        prg_Ascroll();
      }
      break;
    case 2:
      displayMenuItem(2);
      if (state == HIGH) {
        prg_Clock();
      }
      break;
    case 3:
      displayMenuItem(3);
      if (state == HIGH) {
        prg_Flame();
      }
      break;
    case 4:
      displayMenuItem(4);
      if (state == HIGH) {
        prg_Heartbeat();
      }
      break;
    default:
      break;
  }
}

//Display a menu item
void displayMenuItem(byte item)
{
  //menu strings (mai n categories)
    if(  update_display){

    String menuItems[MAX_MENU_ITEMS] = {"Pong game", "A. Scroller", "Clock", "Flame/temp", "Heartbeat"};
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Menu");
    lcd.setCursor(0, 1);
    lcd.write(byte(0));
    lcd.print(menuItems[item]);
    prev_menu=item;

    }
}

void prg_Pong()
{
if(update_display){
  lcd.clear();
  delay(100);
  lcd.print("run pong");
    update_display=false;

  }
  mtx_clear();

  //print cirlce once
  MessageEncoder(ReturnLetter(24), BitStream);
  for (int j = 0; j < 8; j++)
  {
    displayData(~BitStream[j] & Kolommen[j]);
  }
}


text:
Q: How to print unicode characters in the header (YAML) section of a knitr document? This is the YAML header of an RMarkdown IEEE rticle I'm writing in RStudio.
---
title: Analysis of the impact of ...
author:
  - name: First Lást
    affiliation: xx
    department: yy
    location: zz
    email: aa
abstract: |
  This study aims to investigate ...

bibliography: mybibfile.bib
output: rticles::ieee_article
csl: ieee.csl
---

In the author section, the á will not get printed when converted to PDF with knitr
I've tried with different combinations such as  \u{á}, $\á$ and even \u0225 (the unicode for that character) without any luck.
How does one include special characters in that section so they are properly displayed when converted to PDF?

A: I think you nearly had it. Try using the $\'{a}$ LaTeX command. It worked in RStudio for me. You can find some documentation for LaTex special characters here.