text:
Q: java, how to call UDF in spark 1.4.1 In spark 1.4.1, the parameter of callUdf method is
(String udfName, scala.collection.Seq<Column> cols)

There is no method that can act to column directly, like method in 1.5.1
callUDF(String udfName, Column col)

So how to call UDF in 1.4.1? Or how to change column type to
scala.collection.Seq<Column>

For example, these codes work in 1.6.1
sqlContext.udf().register("stringToLong", new UDF1<String, Long>() {

    @Override
    public Long call(String arg0) throws Exception {
        // TODO Auto-generated method stub
        IPTypeConvert itc = new IPTypeConvert();
        return itc.stringtoLong(arg0);
    }
}, DataTypes.LongType);
DataFrame interDF = initInterDF.withColumn("interIPInt", callUDF("stringToLong", initInterDF.col("interIP")));

How should I change the codes so that they can work in spark 1.4.1?

A: You can convert list to Seq[Column]:
import scala.collection.JavaConversions;
import scala.collection.Seq;

import static java.util.Arrays.asList;

DataFrame interDF = initInterDF.withColumn("interIPInt",
    callUDF("stringToLong", JavaConversions.asScalaBuffer(asList(initInterDF.col("interIP")))));

See more in this question


text:
Q: 2nd order differential equation question By finding a suitable particular integral, find the general solution $y$ of the differential equation $\frac{d^2y}{dx^2}+2\frac{dy}{dx}=f(x)$ when
a) $f(x)=3e^{-2x}$
b) $f(x)=1-x^2$
For part a I've done this so far and I'm pretty sure it's wrong…
$$y=De^{-2x}$$
$$\frac{dy}{dx}=-2De^{-2x}$$
$$\frac{d^2y}{dx^2}=4De^{-2x}$$
$$4De^{-2x}-4De^{-2x}=3e^{-2x}$$

A: It can't work because $-2$ is a root of the characteristic equation. Try $Dx^{-2x}$.
Concerning b), as 0 is also a root of the characteristic equation , try a cubic polynomial.
Let me explain the details: a standard form for $f(x)$ is $p(x)\mathrm e^{\,cx}$, where $p(x)$ is a polynomial of degree $d\ge 0$.

*

*If $c$ is not a root of the characteristic equation, a solution is $q(x)\mathrm e^{\,cx}$,  where $q(x)$ is some polynomial of degree $d$.

*If $c$ is a simple root of the characteristic equation, a solution is $xq(x)\mathrm e^{\,cx}$.

*If $c$ is a double root of the characteristic equation, a solution is $x^2 q(x)\mathrm e^{\,cx}$.

Note that the case of $f(x)=p(x)\cos x$ or $f(x)=p(x)\sin x$ is covered by these cases thanks to Euler formulae.

A: $$\frac{d^2y}{dx^2}+2\frac{dy}{dx}=f(x)$$ by solving
  $\frac{d^2y}{dx^2}+2\frac{dy}{dx}=0$, The complimentary solution is obtained to be:
$$y_c=C_1+C_2e^{-2x}$$
a) $f(x)=3e^{-2x}$
solving  $\frac{d^2y}{dx^2}+2\frac{dy}{dx}=3e^{-2x}$ to obtain the particular solution:
$y_p=Axe^{-2x}$ since we have $e^{-2x}$ in the complimentary solution
$\frac{dy_p}{dx}=Ae^{-2x}-2Axe^{-2x}$
$\frac{d^2y_p}{dx^2}=-4Ae^{-2x}+4Axe^{-2x}$
Substituting gives $A=-3/2$
The general solution is then
$$y=C_1+C_2e^{-2x}-3/2e^{-2x}$$
b) for $f(x)=1-x^2$ you use $y_p=Ax+Bx^2+Cx^3$

A: Hint: It should be clear that the solutions to the associated homogeneous equation are generated by $y_1 = c_1$ and $y_2 = c_2e^{-2x}$. Since your functions $f(x)$ are an exponential and a polynomial, you can do it by determining the missing coefficients, that is:

*

*for item a), the first guess would be $Ae^{-2x}$, but since that is spanned by $y_1$ and $y_2$, call the particular solution $y_p = Axe^{-2x}$, force this to be a solution and go for $A$.

*for item b), your $f$ is a second degree polynomial, $A + Bx + Cx^2$. Since one of the terms, $A$, is spanned by $y_1$ and $y_2$, call the particular solution $y_p = Ax+Bx^2+Cx^3$, force this to be a solution, and solve for $A,B$ and $C$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure Batch VNet Integration - Failing to provision nodes I'm trying to provision a Pool of Nodes within Azure Batch and have the nodes join an existing VNet that has other applications sitting inside of it, to no avail...
I have a subnet created and delegated to Azure Batch.
The pool tries to resize and during the first minute or so, it creates the Public IP, Network Security Group and the Load Balancer (all sounds good!). As it reaches the end of the resize timeout duration, those 3 components start to roll-back and get deleted, and the pool never resizes. I'm only trying to provision 1 node in this instance for the purpose of testing.
I'm getting this error in my Resource Group Activity Log each time it tries to provision the nodes, but don't know exactly what it means, nor how to resolve it.
"errorMessage": "The user did not have permissions to GET the AuditIfNotExists policy's target type 'Microsoft.Security/complianceResults'." It seems to get this error when trying to write to Microsoft.Network/publicIPAddresses.
Other info about setup:

*

*Batch Account Pool Type: Batch Service

*Pool Image: Marketplace - ubuntu-server-container 16-04 Customer

*Container configuration - pulling down Container from ACR Node size: Standard A1_V2 (have tried several others also)

*Dedicated nodes: 1

*VNet: Existing VNet with dedicated subnet delegated to Microsoft.Batch/batchAccounts

Any advice welcomed!

A: I ended up filing a support ticket with Microsoft over this.
Turns out the issue was due to subnet I had chosen. I made the unfortunate mistake of delegating it to Batch Account and it should not be. ResourceNotPermittedOnDelegatedSubnet was the exact exception that was firing in the background.
Nowhere on the portal was I able to access the exception that the support guy had access to though. Nor does the documentation state it mustn't be a delegated subnet.


text:
Q: Unable to set background image width and height of component I have a component that i am passing a slot to. I am also setting background image that works fine but when i try to set the size of backgorund image it don't work.  Here is what i have tried
I have a draggable componengt that i am trying to set backgorund image background image get's set but the size don't work.
<VueDragResize
        v-for="(rect, index) in rects"
        :key="index"
        :w="rect.width"
        :h="rect.height"
        :x="rect.left"
        :y="rect.top"
        :parentW="listWidth"
        :parentH="listHeight"
        :axis="rect.axis"
        :isActive="rect.active"
        :minw="rect.minw"
        :minh="rect.minh"
        :isDraggable="rect.draggable"
        :isResizable="rect.resizable"
        :parentLimitation="rect.parentLim"
        :snapToGrid="rect.snapToGrid"
        :aspectRatio="rect.aspectRatio"
        :z="rect.zIndex"
        v-on:activated="activateEv(index)"
        v-on:deactivated="deactivateEv(index)"
        v-on:dragging="changePosition($event, index)"
        v-on:resizing="changeSize($event, index)"
        @click.native="getindex(index)"
      >

{{rect.text}}{{rect.recipientname}}

      </VueDragResize>

A: It should be backgroundSize with capital S

{{rect.text}}{{rect.recipientname}}


text:
Q: Is writing $m=\text{undefined}$ formally correct? I often find some of my students write $m=\text{undefined}$ in their answer sheets. Is it formally correct? Should I suggest them to write $m$ is undefined instead?
For  example the question is

Determine the slope $m$ for a line passing through $(1,2)$ and $(1,1)$. Use the previously explained equation $m=\frac{y_2-y_1}{x_2-x_1}$.

\begin{align}
 m &= \frac{2-1}{1-1}\\
  &= \frac{1}{0}\\
  &= \text{undefined}
\end{align}
Should I suggest them to write as follows?
\begin{align}
 m &= \frac{2-1}{1-1}\\
  &= \frac{1}{0}
\end{align}
$m$ is undefined.

A: I would write in words, something like:

The specified line is vertical, and the usual equation for slope does not apply since it would involve dividing by zero.  So the slope of this line is undefined; it does not have a slope.

I would avoid writing $\frac{1}{0}$ at any time, and would avoid saying that $m$ is equal to anything at all.
Strictly speaking the question is not well posed, because you are asking them to "determine" something which does not exist.  Better wording would be something like

Determine the slope $m$ of the line, if it exists.  If the slope is not defined, explain why not.

A: Actually, the gradient formula applies only when $x_1\neq x_2,$ so, technically, the first equality is incorrect; i.e., $$m\neq\frac{2-1}{1-1}=\frac10.$$ m is (uhm, by definition) undefined.


text:
Q: Yii2 show name instead of id (customer_id) in error message i want to show customer name instead of customer id in error message.
How to achieve this?
Below is the relation in my model,
public function getCustomer() {
    return $this->hasOne(Customer::className(), ["id" => "customer_id"]);
}

Model Validation Rules, here in error message i have to set customer name,
public function rules()
        {
            return [
                ['customer_id','unique','message'=>'Customer **{here i have to set customer name}** already exist in rd pool'],

            ];
        }

A: Use costume validation for this propose
first in rule function of models class declare costume validation function
return [

        ['id', 'validateID', 'when'=> function($model){
                return (!empty($model->id))? true:false;
            },],
        ......
];

Then in the same model create public function called validateId
public function validateId($attribute, $params, $validator)
{
    $id = $this->id;

   { here you can write code to check}
    if(condition check)){
        $this->addError('id', "Coustumer $userName booking start date");
        return false;
    }
}

Then add 'enableAjaxValidation' => True,  In form
 <?php $form = ActiveForm::begin([
    'enableAjaxValidation' => true
    ]); ?>

At last in Controller check validation of model like
if($request->isAjax && $model->load($request->post())){
        yii::$app->response->format = 'json';
        return ActiveForm::validate($model);
    }

If you have some confusion Please refer

http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators


text:
Q: understand JSON parse to NSDictionary
Possible Duplicate:
NSJSONSerialization from NSString

I have this old code, how do I accomplish using NSJSONSerialization?
Below uses SBJSON
+ (NSDictionary *) parseJSONResponse: (NSString *) response {
    NSDictionary *dictionary = [response JSONValue];
    return dictionary;
}

A: You'll need the response NSData to perform the following:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];


text:
Q: Unity parenting and deparenting game objects I'm currently implementing a wall climbing system into my 2D game and I'm stuck on a few of the trickier parts.
My thinking is that I would have my player parent to the wall object when it collides with the 2D collider attached. When the player collides with the wall, the player becomes a child of that wall and is limited to only moving up and down on the wall. When the player jumps, or reaches the top, they are no longer a child of the wall. But the player has the ability to jump on any point onto the wall they land on and stays at that point.
Right now I have the parenting part worked out with the following code (this code is attached to the player):
void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.gameObject.tag == "Wall")
    {
        this.transform.parent = collision.transform;
        Debug.Log("hit a wall");
    }
}

The two areas I'm struggling with are de parenting my player from the wall and having the player still to the position on the wall where they land.
With the first part (de-parenting) I believe I'll need to make use of the following code:
void OnCollisionExit2D(Collision2D collision)
{

    if(collision.gameObject.tag == null)
    {
         this.transform.parent = null;
        Debug.Log("not hitting anythin");
    }
}

However, when I run this, my player doesn't deparent right away. Am I doing it correctly?
I'm also clueless as to how to begin my other problem of having the player stick to the part of the wall they connect with. Can someone please help me with my issues?

A: Ideally you'd use tranform.SetParent for the extra you get over position.
transform.SetParent(parentTransform, true);
transform.SetParent(null, true);

if the latter line is fired it should detach from it's parent to the best of my understanding and the 2nd parameter on SetParent should fix positioning issues.
Though your existing code should at least change the hierarchy, I suspect the issue there is your collision code - if you enter a collision with Tag:Wall then you're going to exit a collision with Tag:Wall not Tag:Null.
However @limoragni is right, editing your hierarchy is going to have no effect on the possible movement of your character unless you've specifically coded that in yourself. You could just as easily set a boolean and use your code with that.
Ref:
http://docs.unity3d.com/ScriptReference/Transform.SetParent.html


text:
Q: split strings from a column in separate columns I am trying to split string values from a column, in as many columns as strings are in each row.
I am creating a new dataframe with three columns and I have the string values in the third column, I want to split in new columns (which already have headers) but the numbers of strings which are separated by semicolon, is different in each row
If I use this code:
df['string']= df['string'].str.split(';', expand=True)

then I will have left only one value in the column while the rest of the string values will not be split but eliminated.
Cal u advice on how this line of code should be modified in order to have the right output?
many thanks in advance

A: Then we do
df['string']= df['string'].str.split(';', expand=True).str[0]

A: Instead of overwriting the original column, you can take the result of split and join with original DataFrame
df = pd.DataFrame({'my_string':['car;war;bus','school;college']})
df = df.join(df['my_string'].str.split(';',expand=True))
print(df)
        my_string       0        1     2
0     car;war;bus     car      war   bus
1  school;college  school  college  None


text:
Q: How to use if statement in mysql to add text to a string value I want to check if schoolid is 1, then add hyphen next year in two digit form to record.year
For example, if record.year = 1997, and schools.schoolid =1, then I would want record.year to return 1997-98.
$sqlquery = 'SELECT
        record.year,
        schools.school,
        schools.schoolid,
        sports.sport,
        conferences.conference,
        record.year
    FROM
        `record`,
        `schools`,
        `conferences`,
        `sports`
    WHERE
        schools.schoolid = record.schoolid
    AND
        sports.sportid = record.sportid
    AND
        record.conferenceid = conferences.conferenceid';

A: Assuming that record.year is of type INT,
SELECT
IF
(
   schools.schoolid = 1,
   CONCAT(record.year,'-',RIGHT(record.year+1,2)),
   record.year
) AS year,
schools.school,
....

if record.year is varchar just cast it to number when adding hyphen:
SELECT
IF
(
   schools.schoolid = 1,
   CONCAT(record.year,'-',RIGHT(CAST(record.year AS SIGNED)+1,2)),
   record.year
) AS year,
schools.school,
....


text:
Q: php :How to generate 2D array from mysql SELECT? I have some questions , please help me.

*

*In PHP/MySQL I have a query that I want to generate 2D array, how can I do it ?

*I hava a php array code, like this:
$menu = Array( // I wanna to get data from a SQL SELECT.
    Array('id'=>1,'title'=>'Menu 1',          'parent_id'=>null),
    Array('id'=>2,'title'=>'Sub 1.1',         'parent_id'=>1),
    Array('id'=>3,'title'=>'Sub 1.2',         'parent_id'=>1),
    Array('id'=>4,'title'=>'Sub 1.3',         'parent_id'=>1),
    Array('id'=>5,'title'=>'Menu 2',          'parent_id'=>null),
    Array('id'=>6,'title'=>'Sub 2.1',         'parent_id'=>5),
    Array('id'=>7,'title'=>'Sub Sub 2.1.1',   'parent_id'=>10),
    Array('id'=>8,'title'=>'Sub 2.2',         'parent_id'=>5),
    Array('id'=>9,'title'=>'Menu 3',          'parent_id'=>null),
    Array('id'=>10,'title'=>'Menu 3',          'parent_id'=>null),
);

How could I to generate this simple array using mysql ?
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
    die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$result = mysql_query("SELECT * FROM mytable");

//this is wrong,but I wanna to reach this effect↓↓↓↓↓↓↓↓
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    echo "Array('id'=>$row["id"],'title'=>'$row["title"]','parent_id'=>$row["parent_id"]),"

}

?>

A: Create an array with one zero indices and append arrays to it.
$rows = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $rows[] = $row;
}

A: $data = array();

for ($i=1; $i<4; $i++) {
    $row = array();
    $row[] = $i;
    $row[] = $i*3;
    $row[] = $i*9;

    $data[] = $row;
}

var_dump($data);

--output:--
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(3)
    [2]=>
    int(9)
  }
  [1]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(6)
    [2]=>
    int(18)
  }
  [2]=>
  array(3) {
    [0]=>
    int(3)
    [1]=>
    int(9)
    [2]=>
    int(27)
  }
}


text:
Q: method with some kind of wait statement I need to have some kind of wait statement in SystemC method.
I know that we can't use wait as method doesn't have there own thread like the thread process.
But here my requirement is i have some set of sensitivity list for method and once any of them get trigger the method will get call. And here i want value to get updated based on some event notification till that time i should wit in that method itself, once that even gets notify i have to update the value and comes out of method.
Could someone please help me with this kind of requirement?
I tried using next_trigger(event_name), but somehow it's not working. Here i thought that my method will wait until the event(event_name) gets triggered after that the value gets updated and control will be passed back from method to systemc kernel. But somehow it's not happening.
My sudo code is as below:
sc_core::sc_event  event_name;
if(1 == test_signal)
    {
      next_trigger(event_name);
      result = value;
    }

Thanks in advance...

A: Now it's working i just modified the code so that dynamic sensitivity will be properly taken care for method.
The modified code is as:
sc_core::sc_event  event_name;
if(1 == test_signal)
    {
      next_trigger(event_name);
      if(reg_event_name)
     {
        result = value;
     }
    }

Please do let me know if anyone need similar help.


text:
Q: Need a php script for applying imark on images
Possible Duplicate:
Add 'Watermark' to images with php

I am working on a website having wallpapers in it. My client wants to add the Imark on each uploaded image. When he will upload an image he will also upload an Imark image. if any one can help me in finding a php script. Thanks in advance...

A: I'm guessing you mean "watermark."
Try this:
Add 'Watermark' to images with php
PHP Watermarking - Zubrag
Dynamic Watermark / On-the-fly Zip Files problem
PHP watermarking
SO php watermark
Google php image watermark


text:
Q: Force recreation of Activity/Fragment on restore I am having a number of issues around saving app state to a Bundle via onSaveInstanceState().
For now, I need to address the issue of my app crashing when it restored after being closed by Android.
When an Activity/Fragment (in background) is being force closed by Android to regain resources, is there a way I can say "don't try and restore state when resume, just create everything anew"?
Thanks

A: In the "onCreate" method f the activity, you can pass a null value to the super call
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    //rest of your code
}

A: I recommend to you save your data in onPause() method. Whe you close app with HOME button onSaveInstanceState never have been called and data will be lost.

is there a way I can say "don't try and restore state when resume, just create everything anew"?

Yes. You can. You can check window state of app and manipulate your logic with boolean flags. Also i will recommend to you slice save\restore data process into 2 separate ways :

*

*Prepare Data to save \ restore

*Save \ Restore

A: For activity if you want to create it from scratch then just override onSaveInstanceState and call super.onSaveinstanceState passing a null al the Bundle.
For Fragment just set setRetainInstanceState to false in onActivityCreated method of the Fragment.


text:
Q: KDE desktop environment alongside GNOME I'm using Ubuntu and I would like to experience KDE desktop environment. I have installed KDE in full mode using apt-get install with no error but no further effects occurred. I don't know how to use my installation, start in KDE mode and switch between unity and KDE.

A: Installing KDE
To install KDE (which it sounds like you may have already done), you install one of the following packages:

*

*kde-plasma-desktop
This will only install a minimal core of KDE apps and utilities.  Good if you want to use KDE but don't need all the applications and utilities that come with it.

*kde-full
This will install a more full range of KDE applications and utilities.
If you have other desktop environments installed this will cause you to double-up on a fair few apps (ie, have both the Gnome and KDE equivalent installed).  This is not necessarily a bad thing as it gives choice and lets you (if you want) use anything a native KDE user would use.

*kubuntu-desktop
This installs the full Kubuntu desktop which includes the full KDE suite, plus all of Ubuntu's "Kubuntu" look and feel, including the splash screens and greeters.  It also installs additional applications that Kubuntu normally installs, like Kontact and Konversation.
This is not usually recommended if you also have other desktop environments installed, because it changes the splash screen and greeter to Kubuntu.
Selecting KDE when logging in

*

*Before you enter your password upon log-in, you need to open up the drop-down that says "Ubuntu" (which will make you use Gnome/Compiz/Unity, Ubuntu's default) and change it to KDE.

A: Hi when you are at the login screen there you can choose wich desktop you want to use like in the screenshot here


text:
Q: How to run npm command inside a class library in c# I am making a class library project , its goal , for the moment , is to run a JavaScript project through an npm command thanks to a c# method call .
The npm command :

npm start

The JavaScript project (made with reactJS ) resides within the class library project .
The Class library ( to call ) :
namespace DoGutenberg
{

  public class Run
{

public void start ()
{

            string strCmdText;
            strCmdText = "/C npm start ";
            System.Diagnostics.Process.Start("CMD.exe", strCmdText);

  }
}
}

The method call from another asp.net project :
using DoGutenberg;

  var a = new DoGutenberg.Run();

            a.start();

The sripts field within package.json inside the JavaScript project  :
 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },

The problem is that when i call start() method from another asp.net project , after importing the class library as a reference for sure , npm errors are generated in npm command window that i couldn't catch since the window is keeping hiding fast .
Any help with that please ? or what can be any other outlet to run this JavaScript project ?

A: By adding a Console.ReadKey() in the dll your CMD window should persist:
public void start()
{
string strCmdText;
strCmdText = "/C npm start ";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
Console.ReadKey();
}


text:
Q: Impact of publishing messages to one Kafka broker with in a cluster I have Kafka cluster with three brokers and zookeeper instances. Kept the replication factor of 2 for each partition.
i want to understand the impact of publishing messages to single node in a cluster by giving one broker address. Will this broker sends message to other brokers if messages fit into partitions hold by other brokers?
can someone explain how internal sync works or else point to resources.

A:
giving one broker address

Even if you give one address, the bootstrap protocol returns all brokers to the client.
The partitioner logic determines which partition in which broker to send the data to - you target partitions, not brokers in the client.


text:
Q: latex escape chars I want to prepare a text for the use in a LaTeX document.
I wrote a SQL Function which does a lot of REPLACE. For example _ -> \_ and so on.
But there are so many special chars and sometimes I get errors. Does anyone know a SQL-function or a Java package for escaping text to LaTeX?

A: There are only 10 special chars: \ { } _ ^ # & $ % ~.

A: Use a verbatim environment or the listings package, then you can enter source code without escaping.


text:
Q: Swagger in Net 4.5.1 existing project I have an existing project that contains a number of APIs. I would like to do a documentation of these APIs. While searching I came across Swagger which seems not bad. So I installed the nugets packages (Swashbuckle.Net45 -Version 5.2.1). I configured SwaggerConfig and started my project. When I go to the URL localhost [port_num] / swagger I have the following error:

"ExceptionMessage":"Not supported by Swagger 2.0: Multiple operations with path 'api/Pdf' and method 'GET'.

I do not really understand what this error is so if someone has already had this and has a solution I am a taker.

A: Swagger has a stricter rule set for the naming / routing of your controller methods.
The error suggests that you have multiple methods on a controller that are mapped via the same Http Method and path.
Check for any methods in your controllers that match api/Path and change one of them.


text:
Q: symbol barcodescanner doesn't like being closed in a scan callback The motorolla symbol barcodescanner works with a delegate event function, if I attempt to disable the scanner within the context of that space I get a null reference exception.
If I simply disbale the scanner but outside that functions execution everything works fine.
Any ideas how to get around this? The scan opens a new form which means the scanner needs to be disabled...

A: You can trigger a timer in the scanner callback function. In the timer tick callback you then disable the device. Just keep in mind that if the scanner callback is hit again before the timer tick you will need to reset the timer. Failure to do so may result in lost data received from the scanner.

A: is the enable of the scanner a property or do you actually need to turn it off?
In a project I did where the scanner I was using was not able to be turned off was to abstract their library with my own, and have an Enabled property on my library. Then inside my class I just kept the instance of the real scanner operational and if my Enabled property was turned off I didn't raise the event to the outside class.
Therefore you might be able to do something similar here.
void ScannerCallback(object sender, EventArgse)
{
    if (Enabled)
    {
      OnBarcodeArrived(this, EventArgs.empty);
    }
}

A: Paul's idea looks interesting.
Another option would be to enable/disable the scanner based on what control is selected using that control's GotFocus and LostFocus events.
One event could wire up all of it.
private void Control_FocusChanged(object sender, EventArgs e) {
  ScannerEnabled = ((Control)sender).Focused;
}

(You have to code that ScannerEnabled variable, though.

A: I strongly suggest that you create your scanner object, or a wrapper around that object, as a singleton in your project.  I've found the Dispose handling of data-collection objects in several vendors to be iffy, and rapid recreation of the objects even more so.  By using a singleton, you avoid the whole issue.  One create at startup, one dispose at program shutdown.


text:
Q: AngularJs selectors? How does AngularJs make its selectors In HTML without the need/using script tag?
I've seen this happening in html via angular allot:
 {{'Something...'}}

How is this possible without the script tag?

A: Think of it as a templating system. Your html is the template, and the controller is the... controller that you defined in your angular js.
The {{something}} things in your html are usually references to properties on the scope of the controller.
$scope.something = "Hello World!";

Angular simply replaces the {{something}} entries in your html with actual content, for example, with theHtml.replace("{{something}}", $scope.something). Angular can also interpret basic javascript within the brackets so you can do things like <p>{{something + ' Today\'s date is: ' + new Date()}}</p> and actually get the result to output on the page instead of the brackets.
This only explains at a very basic level how the content within the brackets gets replaced with actual content, explaining much more such as how data binding is done will become too much for a single answer on SO.

A: After AngularJs is loaded, it will scan your html document. For every directive or angular mark-up it applies an watcher which sends notifications when that value has changed and by receiving this notification, angular knows UI must be updated asap.
So, for Angular, {{}} it's something that will be verified at a certain time. ( like a directive )
You can read more about this  here .


text:
Q: Control ulines for cloze text @Martin Scharrer suggested me the following amazing solution to make cloze texts: https://tex.stackexchange.com/a/16004/4011
\documentclass{article}
\usepackage[normalem]{ulem}

\makeatletter
\def\UL@putbox{\ifx\UL@start\@empty \else % not inner
  \vrule\@width\z@ \LA@penalty\@M
  {\UL@skip\wd\UL@box \UL@leaders \kern-\UL@skip}%
    \phantom{\box\UL@box}%
  \fi}
\makeatother

\begin{document}

Some text \uline{some text to complete some  text to complete
some  text to complete some  text to complete some  text to complete some    text
to complete some  text to complete} some more text.

\end{document}

Now I have some follow up questions about this approach:

*

*How can I adjust this such that I can choose all the "underline styles" offered by the ulem package \dotuline, \dashuline, \uwave and\uuline?

*How can I adjust the vertical space between the phantom text and the underline?

*Is it possible to get a normal working version of \uline at the same time? (Call it for example \Uline, \Uuline etc.).

A: *

*Just use them.

*\setlength{\ULdepth}{...}

*The following example adds the switch \ifulphantom that can be set to enable or disable the phantom version for the macros of package ulem.
Full example:
\documentclass{article}
\usepackage[normalem]{ulem}

\makeatletter
\@ifdefinable\UL@putbox@original{%
  \let\UL@putbox@original\UL@putbox
  \def\UL@putbox@phantom{%
    \ifx\UL@start\@empty
    \else % not inner
      \vrule\@width\z@
      \LA@penalty\@M
      {\UL@skip\wd\UL@box \UL@leaders \kern-\UL@skip}%
      \phantom{\box\UL@box}%
    \fi
  }%
  \newif\ifulphantom
  \renewcommand*{\UL@putbox}{%
    \ifulphantom
      \expandafter\UL@putbox@phantom
    \else
      \expandafter\UL@putbox@original
    \fi
  }%
}
\makeatother

\usepackage{parskip}

\begin{document}

\ulphantomtrue

\begingroup
  \setlength{\ULdepth}{0pt}

  Some text \uline{some text to complete some  text to complete
  some  text to complete some  text to complete some  text to complete some
  text to complete some  text to complete} some more text.

  \setlength{\ULdepth}{1ex}

  Some text \uline{some text to complete some  text to complete
  some  text to complete some  text to complete some  text to complete some
  text to complete some  text to complete} some more text.
\endgroup

Some text \uuline{some text to complete some  text to complete
some  text to complete some  text to complete some  text to complete some
text to complete some  text to complete} some more text.

Some text \uwave{some text to complete some  text to complete
some  text to complete some  text to complete some  text to complete some
text to complete some  text to complete} some more text.

\ulphantomfalse

\begingroup
  \setlength{\ULdepth}{0pt}

  Some text \uline{some text to complete some  text to complete
  some  text to complete some  text to complete some  text to complete some
  text to complete some  text to complete} some more text.

  \setlength{\ULdepth}{1ex}

  Some text \uline{some text to complete some  text to complete
  some  text to complete some  text to complete some  text to complete some
  text to complete some  text to complete} some more text.
\endgroup

Some text \uuline{some text to complete some  text to complete
some  text to complete some  text to complete some  text to complete some
text to complete some  text to complete} some more text.

Some text \uwave{some text to complete some  text to complete
some  text to complete some  text to complete some  text to complete some
text to complete some  text to complete} some more text.

\end{document}

A: I wrote a package named "cloze" that specializes in creating cloze texts. You have to use LuaLaTeX or LuaTeX.
\documentclass{article}
\usepackage[show]{cloze}

\begin{document}
Some text \cloze{some text to complete some text to complete some text
to complete some text to complete some text to complete some text to
complete some  text to complete} some more text.
\end{document}

Change the global options to \usepackage[hide]{cloze} or use \clozehide to hide the cloze text.


text:
Q: Pandas histogram of dates with empty bins My use case is very simliar to this post, but my data is not continuous through each bin. I'm attempting to create multiple figures over the same time span to show activity (or lack thereof) over 18 months. I thought I hit the jackpot with the df.groupby(df.date.month).count() approach, but since my data is irregular I get different bins per dataset.
My question, then, is how would I go about creating some kind of master x-axis with fixed bins (month,year) and plot each dataset against these bins. I think I'm missing some fundamental understanding of either Pandas or MPL, and I apologize for what I'm sure is a silly question. First post, go easy...
Since I can't comment yet, I'll edit here:
I have 18 months generated with pd.period_range. I also have a DataFrame full of observations with timestamps within those months. Some of months have zero observations. How do I effectively count and chart the observations by month?

A: Have you tried the suggestions here?
You can also try this sort of approach to manually define the bin boundaries
bins = [0, 30, 60, 90, 120]
labels = [1, 2, 3, 4]
df['new_bin'] = pd.cut(df['existing_value'], bins=bins, labels=labels)


text:
Q: People Picker not showing user results if we not entered exact We have enabled Claims authentication with LDAP membership role. Its working fine. In people picker if we enter the exact user name then only search results showing Form Auth user. otherwise not showing the users. showing error "No results were found to match your search item. Please enter a new term or less specific term."
Can you please any one help me to resolve this issue.

A: If I understood the question correctly, you will need to modify webconfig section <PeoplePickerWildcards> (to be precisier, configuration/SharePoint/PeoplePickerWildcards) to achieve this, as it described in following MSDN article:

*

*http://msdn.microsoft.com/en-us/library/bb975136.aspx
The sample code:
<PeoplePickerWildcards>
  <clear />
  <add key="AspNetSqlMembershipProvider" value="%" />
  <add key="fbaMembers" value="%" />
</PeoplePickerWildcards>

Also I'd recommend you to read an essential, "must-read" article on configuring People Picker by using stsadm:

*

*http://technet.microsoft.com/en-us/library/gg602075.aspx
, particularly, about the Peoplepicker-searchadcustomquery property.

A: For LDAP membership providers, use
<add key="fbaMembers" value="*" />


text:
Q: Convert coordinate systems using SQLGeometery One of my shape files looks like this:
POLYGON (
  -91.513078999999991 36.970298,
  -87.01993499999999 36.970298,
  -87.01993499999999 42.508337999999995,
  -91.513078999999991 42.508337999999995,
  -91.513078999999991 36.970298)

Another file is using SRID 3857:
POLYGON (
  -10033572.109485552 4727287.954831399,
  -10033571.708142675 4727287.954831399,
  -10033571.708142675 4727288.1439229213,
  -10033572.109485552 4727288.1439229213,
  -10033572.109485552 4727287.954831399)

Assuming I can figure out which coordinate systems are being used, how do I convert from one format to the other?

A: Use the GeometryToGeometry function from Pro Spatial, chapter 8.
Source code and data tables: http://www.apress.com/9781430234913


text:
Q: Could SE profile and hot questions support MathJax for titles and summaries? I guess not, but just in case it's easily fixed: could the hot questions and SE profile support MathJax to render question titles and summaries?
On most SE sites, the SE MultiCollider does not support MathJax, and neither do the global SE profiles:

Of course, the specific site itself supports the very same title just fine:

I know support for this on the regular sites has been declined, "as it is an extremely heavy dependency". But maybe it's still doable just for rendering the titles and summaries? Or maybe only on the global SE profile? (Careers might like this too? Never used that.)

A: If MathJax cannot be enabled on non-MathJax sites, then maybe render a title such as:

Prove that $\displaystyle\lim_{x\rightarrow 1}\frac{x^{1/m}-1}{x^{1/n}-1}=\frac{n}{m}$

...on non-MathJax sites as:
Prove that <img src=...>

...where the image URL is taken from $ [...] $:
https://latex.codecogs.com/png.latex?[...]

Like:

Prove that

(And some CSS to align the image, which might be hard as vertical-align: middle does not quite fix it...)

A: The problem with doing that is that the MathJax dependency is a very heavy one, and with your proposal it'd have to be loaded on all pages of all sites.
What would be ideal is if it there was some sort of approximate LaTeX → Unicode translator in C# to make a display-friendlier representation of equations, bringing
$\displaystyle\lim_{x\rightarrow 1}\frac{x^{1/m}-1}{x^{1/n}-1}=\frac{n}{m}$

to (e.g.)
lim(x→1) (x^(1/m)-1)/(x^(1/n)-1) = n/m


text:
Q: why Unable to upload a picture on firebase storage? There's a mistake in this code:
String download_url=task.getResult.getStorage.getDownloadUrl.toString);

When I run the program, I choose a picture from the gallery and I post it, and I get a message:

User is not authenticated, please authenticate using Firebase Authentication and try again

final StorageReference newPhoto=mPhotosStrorage.child(imageUri.getLastPathSegment());
newPhoto.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

        if (task.isSuccessful())
        {
            final String myKey=mPhotosDatabase.push().getKey();

 //this error       String download_url=task.getResult().getDownloadUrl().toString();

            String datem=getDateTime();

            DatabaseReference newDatabase=mPhotosDatabase.child(myKey);

            newDatabase.child("postid").setValue(myKey);
            newDatabase.child("postedby").setValue(userId);
            newDatabase.child("postedon").setValue(datem);
            newDatabase.child("postdetails").setValue(post);
            newDatabase.child("postlikes");
            newDatabase.child("postviews");
            newDatabase.child("postcomments");

            newDatabase.child("postimage").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful())
                    {
                        pb.setVisibility(View.GONE);
                        Pair[] pairs=new Pair[1];
                        pairs[0]=new Pair<View,String>(homeLayout,"etTransition");

                        ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(PostActivity.this,pairs);

                        startActivity(new Intent(PostActivity.this,HomeActivity.class),options.toBundle());

                    }
                }
            });
        }else {
            Toast.makeText(PostActivity.this, "Error:"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

Please help solve it and rewrite the code for me.

A: According to your last comment, the problem is at the following line of code:
String download_url=task.getResult().getDownloadUrl().toString();

Please note that this is not how you get the download URL nowadays. Converting that Task object to String isn't helpful at all. To solve this, please use the following lines of code:
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        String url = uri.toString();
        //Do what you need to do with the URL
    }
});

Besides that, always make sure to have the user authenticated, as that error occurs only when the user is not authenticated and the rules are set to reject the operations.


text:
Q: Windows 10 Docker error during docker run I am trying to run docker container on windows 10
When I run "docker run -it nanoserver cmd" using elevated Windows CMD shell
I am getting the following error

docker: Error response from daemon: container
ea592a56c97f4f2e80ab76e5b7615b4caa5d8a64bc3c704092d243d9b444487a
encountered an error during Start failed in Win32: winapi error # 3489661596 (0xd000029c).


text:
Q: Calculated breaching time excluding weekend, holidays and non working hours I`m trying to calculate the date ( with hours minutes and seconds) when a ticket will breach the 9 business hours mark.
I have the following: work start hour is 8AM, work end hour is 5PM. Week is Monday to Friday. I also have a list of holidays based country. I can have start date in weekends, holidays, before start time and also after start.
I`m using this formula
=WORKDAY(A1,1+INT((9-(17-MOD(A1,1)*24))/8),INDIRECT(CONCATENATE("'Validation'!j",MATCH(B1,Validation!I:I,0),":j",MATCH(B1,Validation!I:I,0))))+TIME(8,0,0)+MOD((9-(17-MOD(A1,1)*24)),8)/24

A1 = Start time
9 = Number of hours to add
B1 = Country name
In another tab I have the list of countries and holidays, indirect/concatenate/match formula is helping me identify the start row and ending row of the holidays per the respective country.
It works fine for start times between 8am and 5pm
I think time (8,0,0) is the start time but I`m not sure what " 8" after mod formula does.
Got this formulas from here http://answers.microsoft.com/en-us/office/forum/officeversion_other-excel/add-work-hours-to-a-date-and-time/c41cf049-3797-48a3-8156-438401c6137c?page=2
This formula doesnt take into account start time outside business hours.
If I receive a ticket on 24th march at 8pm and 25&28 are holidays, I would expect that by adding 9 business hours i get 29 march 5PM.
if I receive a ticket on 25th at 5AM, I would expect to same result if I added 9 business hours.
Thanks,
sorin

A: I came up with a work around to the hours outside the working time -
=IF(MOD(A1,1)<0.333333,INT(A1)+TIME(8,0,0),IF(MOD(A1,1)>0.708333,INT(A1+1)+TIME(8,0,0),A1)). i moved the hours to the start of the program.


text:
Q: C# equivalent of the VB.Net select case true I'm trying to find a C# equivalent of the VB.Net Select Case True, which I found very useful in the past. In VB.Net, I could write (an arbitrary example where a property is of type object and either passed a Boolean value, or an instance of class Expression):
Select Case True
    Case value Is Nothing:
        Throw New Exception("Invalid value.")

    Case value.ToString() == "True":
        moValue = value

    Case value.ToString() == "False":
        moValue = value

    Case value.GetType().Name = "Expression":
        moValue.DataTypeCode = "BOOLEAN"
        moValue = value

    Case Else:
        Throw New Exception("Invalid value.")
End Select

I'm aware of the switch statement, obviously, but the case values cannot be expressions, as far as I can tell. Although C# practitioners may balk at the above, I found it very useful, because it lays out my test cases in a list with the precedence of order of analysis.
Is there a C# construct where I can have a bunch of test cases in a list like this and process the first one that evaluates to true, without having to nest a bunch of if...else's?

A: In C#, you'd write this is an if/else if/else statement:
if (value == null)
{
    throw new Exception("Invalid value");
}
else if (value.ToString() == "True" || value.ToString() == "False")
{
    moValue = value;
}
else if (value.GetType().Name == "Expression")
{
    moValue.DataTypeCode = "BOOLEAN";
    moValue = value;
}
else
{
    throw new Exception("Invalid value");
}

You can do this with a switch statement with when clauses, but please don't.

As an aside, that slightly verbose case:
else if (value.ToString() == "True" || value.ToString() == "False")

can also be written as the more concise pattern:
else if (value.ToString() is "True" or "False")


text:
Q: Connecting IntelliJ to weblogic server I have a server that it has weblogic on its own. I develop my program with intelliJ. Can I connect intelliJ to the weblogic server and just run and deploy the project from intelliJ (just like when we use Tomcat application server on our local and start/stop that with intelliJ)?

A: You indeed can. You can create a Run/Debug configuration for WebLogic same way as for Tomcat, but you might see it as an option only after you click N items more (irrelevant), which is at the very bottom of the list.
Also, this is supported only in Ultimate edition. If you're using community edition, you can't do that from the IDE.
The process of configuration is also described in Intellij IDEA's guides


text:
Q: Not getting output, no errors found ( c language) C code for calculating simple interest
#include <stdio.h>
int main()
{
    float principle, rate, years;
    float simpleInterest = (principle * rate * years)/100;
    printf("Enter the principle");
    scanf("%f", &principle);
    printf("Enter the rate");
    scanf("%f", &rate);
    printf("Enter the years");
    scanf("%f", &years);
    printf("The simple interest is %f", simpleInterest);
}

A: C variables are not mathematical variables: they do not express a relationship:
int y = x + 1; // this does NOT mean that `y` is always equal to `x + 1`

Instead, statements are executed from top to down, and when a variable name comes up in the code, the C language will read its contents[1]. Therefore:
int x = 5;
// now x == 5
int y = x + 1;
// now x == 5 and y == 6
x = 8;
// now x == 8 and y == 6

That means that your code should be:
#include <stdio.h>

int main(void) // NOTE: use `int main(void)` instead of `int main()`
{
    float principle, rate, years;

    printf("Enter the principle");
    scanf("%f", &principle);

    printf("Enter the rate");
    scanf("%f", &rate);

    printf("Enter the years");
    scanf("%f", &years);

    float simpleInterest = (principle * rate * years) / 100.0f;

    printf("The simple interest is %f\n", simpleInterest);

    return 0;
}

NOTES:
[1] = not always true, because of short circuiting when using operators like && and ||, and because operators like sizeof do not evaluate the expressions. But this is beyond the scope of my answer.


text:
Q: proxy_pass from wildcard subdomain via NGINX I'm trying to show users visiting a wildcard subdomain a subfolder:
abc.example.com -> example.com/xyz
This NGINX server block code is working:
server {
   # server name with regexp
   server_name ~^(?<sub>[^.]+)\.example\.com$;
   # this server catches all requests to xxxx.example.com
   # and put "xxxx" to $sub variable
   location / {
        # finally we want to request different URI from remote server
        proxy_pass http://localhost:8000;
        # proxy_redirect will rewrite Location: header from backend
        # or you can leave proxy_redirect off;
        proxy_redirect http://localhost:8000 http://$sub.localhost:8000;
   }
[certbot code]
}

(found in question 5249883).
But when replacing proxy_pass value "https://localhost:8000" with "https:localhost:8000/xyz", I get these errors and a blank page:
Uncaught SyntaxError: Unexpected token '<'

in both socket.io.js and commons.js.
The app I'm running on example.com is built with React/Gatsby. example.com/demo is working.
EDIT: I put the wrong error messages, those errors appeared when I tried something different.

A: The problem was (as I understand it now), that Gatsby hosts scripts at example.com/[script-address] and using NGINX proxy_pass, the script address is also changed to example.com/[subfolder]/[script-address].
The solution to this is to set the "path-prefix" value in gatsby.config as explained here: Gatsby documentation.
With doing that, I set a prefix for my complete application, which is not really what I want to do, as the main application is still hosted on example.com, I only want the subdomains to get passed to some subpages. (The subdomains are user created and served dynamically by the main application).
Surprisingly, both (main application and subdomains) work after changing the path prefix.
This seems only to work for the production build (you have to pass a flag when building), so I'm currently still not sure what to do while developing.
If you have an idea how I could solve that better, please message me :)
Thanks to Ivan and Richard for putting me on the right track!
EDIT: Asset prefixed would be the better way: https://www.gatsbyjs.org/docs/asset-prefix/
It's still ugly and I think there's a way to solve this via NGINX.
I still can't use the development build this way.
EDIT 2:
After I've been messing with this for 3 days now, I've again tried to find a similar question & got lucky: https://serverfault.com/questions/840654/nginx-map-subdomain-to-a-subdirectory-on-proxied-server
I've changed my code to:
    location    / {
    proxy_pass http://localhost:8000/xyz$uri/;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;

   }

and it finally works :)


text:
Q: SSIS OLEDB Destination Not Using Fast Load and Deadlocking I do not typically ask questions on here unless I am truly stuck and cannot find an answer anywhere else. My question should be rather simple and apologies if it is answered somewhere else already but I was unable to find a straight ahead answer.
I am using SSIS to insert data into a table via an OLEDB Destination component. I am simply using the Data Access Mode of "Table or view" and NOT using the "fast load" data access mode. I am having problems with deadlocks as there are 4 SSIS packages that process 1 record to insert into the same destination table. It has to be setup to have different SSIS packages and to process 1 record at a time because each is an individual transaction in the source system. I have read that if using the "fast load" data access mode that there is an option for a table lock or not. If I am NOT using the fast load option does this automatically lock the table or is there no table lock when NOT using the fast load? I am trying to get to the source of a deadlock issue when two of these SSIS packages run at the same time and did not know if having the OLEDB Destinations setup to NOT use the fast load option could be a cause of the deadlock. The reason I am not using the fast load data access mode is because this SSIS packages runs for 1 record at a time and I was having problems with triggers firing when using fast load (I know about the "FIRE_TRIGGERS" option when using fast load).
A simple answer to my question is all I am looking for but any additional help is appreciated.

A: Table or view mode does not use the Tablock hint.  You can view the locking that is going on during that execution of your package by looking at the dmv sys.dm_tran_locks
An insert operation is going to take some level of locking on the table - IX on the page and X on the key, perhaps.
The insert operations, themselves, are not going to cause a deadlock, each insert will just wait for each other until they all complete.  The triggers, on the other hand, could cause deadlocks if they are taking additional locks on the same table, but are waiting for another insert to complete.  i.e.

*

*Insert 1 starts

*Insert 2 starts

*Trigger fires from Insert 1 and is waiting on Insert 2

*Trigger fires from Insert 2 and is waiting on Insert 1

So look at what the triggers are doing.  Do they have a good index to perform their operation or are they doing scans and escalating the locks?
You might consider disabling the triggers, performing the inserts and then doing the trigger operation as a post step.
In any case, to test this theory, disable the triggers and see if you get deadlocks.  Then look at the execution plans to see if they can be improved with a better index.


text:
Q: How to import class from npm package I created a npm package, the package just export a simple class, and I want to create an instance of that class in my code. but I want to be able access the class directly:
The package:
export class SomeClass{
  ///
}

My code now:
var SomeClass = require('some-class').SomeClass
var obj = new SomeClass()

How I want it to be:
var SomeClass = require('some-class')
var obj = new SomeClass()

Is it possible to export it in a way that will make it work?


text:
Q: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' I am beginner in Laravel 7, I am using two tables 'empmast' and 'empatten'. I displayed the values of empmast (empid, empname) and joined two fields (empstatus, doa) with same. Then I tried to push these values to 'empatten' table. The thing is these values are trying to save in the empmast instaed empatten table. Kindly assist.
Complete Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'empstatus' in 'field list'
(SQL: insert into `empmast` (`empid`, `empname`, `empstatus`, `doa`, `updated_at`, `created_at`) values (2, Kirupa Shankar, Present, 17-05-2020, 2020-05-17 06:34:26, 2020-05-17 06:34:26))

EmpAttenController:
use App\Empatten;
use App\Empmast;
use Illuminate\Http\Request;

class EmpAttenController extends Controller
{
    public function store(Request $request, Empatten $empatten)
    {
        $member1 = $request->input('empid');
        $member2 = $request->input('empname');
        $member3 = $request->input('empstatus');
        $member4 = $request->input('doa');

        for ($i = 0; $i < count($member1); $i++) {

            $empatten->empid = $member1[$i];
            $empatten->empname = $member2[$i];
            $empatten->empstatus = $member3[$i];
            $empatten->doa = $member4;
            $empatten->save();
        }
    }
}

Empatten(Model):
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Empatten extends Model
{
    protected $fillable = [
        'empid'     => 'array',
        'empname'   => 'array',
        'empstatus' => 'array',
        'doa'
    ];
}

A: Create new instance of your model before you try to save
    use App\Empatten;
    use App\Empmast;
    use Illuminate\Http\Request;

    class EmpAttenController extends Controller
    {
        public function store(Request $request)
        {
            $member1 = $request->input('empid');
            $member2 = $request->input('empname');
            $member3 = $request->input('empstatus');
            $member4 = $request->input('doa');

            for ($i = 0; $i < count($member1); $i++) {
                $empatten = new Empatten(); // initiate your model class
                $empatten->empid = $member1[$i];
                $empatten->empname = $member2[$i];
                $empatten->empstatus = $member3[$i];
                $empatten->doa = $member4;
                $empatten->save();
            }
        }
    }


text:
Q: Can I use the default UIBarButton icons provided by Apple in other assets of my app? Like in UIButton  or a UIImageView etc..
If so how do I do that using the StoryBoard or in a Xib
I am able to use the default icons inside UIBarButton items but cannot look them up in normal buttons . A solution using Storyboard would be really nice

A: In order to use them you need to extract them using a handy little app called (fittingly enough) iOS Artwork Extractor.  I use it all the time when I want to mimic iOS system behaviours.
Download the Xcode project at:
https://github.com/0xced/iOS-Artwork-Extractor
Or another way:
The Other.artwork file is in /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/Frameworks/UIKit.framework/ (you need the SDK).
Use the "iPhoneShop-1.3.jar" program -- available currently here to extract all of the images into a directory.
java -jar iPhoneShop-1.3.jar ARTWORK Other.artwork EXPORT Other

A: No you cannot use UIBarButtonItem on other as subview like UIButton. UIBarButtonItem can only over UINavigationBar.


text:
Q: Directory invisible until I cd into it I have a mysterious directory that doesn't list until I cd into it. Then it does just fine. Then it vanishes again periodically.
bash-3.00$ pwd
/sde
bash-3.00$ ls -la
total 16
drwxr-xr-x   4 root root    0 May 18 16:46 .
drwxr-xr-x  29 root root 4096 Mar 23 13:16 ..
drwxrwxrwx  11 root root 4096 Dec  8 16:36 src_rep
drwxr-xrwx   7 root root 4096 Dec  3 11:06 taaats_6
bash-3.00$ cd s_int_r
bash-3.00$ pwd
/sde/s_int_r
bash-3.00$ ls ..
s_int_r  src_rep  taaats_6
bash-3.00$ cd ..
bash-3.00$ ls
s_int_r  src_rep  taaats_6

Some time passes, with no commands entered...
bash-3.00$ pwd
/sde
bash-3.00$ ls
src_rep  taaats_6
bash-3.00$ ls ./s_int_r/..
s_int_r  src_rep  taaats_6

I am SSH'd into this machine with putty. If I open up another connection to the machine, the second connection seems to always be the same as the first. Ie- It initially doesn't show on either, but if I cd into it on one connection, it will then show on the second.
What is going on?

A: You're seeing an automounter in operation. Automounter implementations vary, but the basic principle is to mount a directory only when it's accessed. This one is mounting s_int_r on demand when you change into it; other automounters might always list it in the directory entry for /sde but only actually mount it when you try to access a file in it.
cd /sde/s_int_r && df . will tell you where it's mounted from. grep /sde /proc/mounts will tell you what automounter is going on, and from that information you may be able to find out how it's configured.


text:
Q: How to find quality parameter in compressjs dynamically My file size is 500kb (It will come dynamically anysize). And my target is 150kb.
For some reasons i can choose only quality
new Compressor(selectedFile1, {
            quality: targetRatio,

i.e., If i pass targetRatio to 0.7, it will reduce image to 159kb~
To find the targetRatio dynamically what i did is
var targetRatio = fileSize / 150;

But, I cannot figure out how to do find the targetRatio to get exact value i.e., to reduce into 150kb
Here's the place to test

A: Reaching 150kb modifying the quality, won't work for every image.

The amount of JPEG compression is typically measured as a percentage of the quality level. An image at 100% quality has (almost) no loss, and 1% quality is a very low quality image. In general, quality levels of 90% or higher are considered "high quality", 80%-90% is "medium quality", and 70%-80% is low quality.

If you would use a 15.594 x 3.936 jpg (example) which may be at ~2.5mb depending on the information stored, you wouldn't be able to reach 150kb in jpg format.
So targeting 150kb would be 150.000 / 2.500.000 = 0.06.

As you can see from the result size of the screenshot, this is not possible, you have to do multiple converts and test if the result size is exactly or below 150kb by reducing width & height. But compressing the original image from my example using the quality of 0.06 will result in an image around 800KB.

fetch('https://i.imgur.com/mw7BsYS.jpg')
  .then(response => response.blob())
  .then(async blob => {
    let {
      size
    } = blob;

    console.log("Startingsize", size, 'B');
    let img = document.createElement("img");
    img.src = URL.createObjectURL(blob);

    await new Promise((r) => img.onload = r);
    let {
      naturalWidth,
      naturalHeight
    } = img;

    console.log(naturalWidth, naturalHeight, size);
    const targetByte = 150 * 1024;
    // in case first picture is smaller than 150kb
    let compressed = { result: blob };
    // speeds up large pictures
    if (targetByte / size < 0.15) {
      naturalWidth *= 0.15;
      naturalHeight *= 0.15;
    } else if (targetByte / size < 0.25) {
      naturalWidth *= 0.25;
      naturalHeight *= 0.25;
    } else if (targetByte / size < 0.5) {
      naturalWidth *= 0.5;
      naturalHeight *= 0.5;
    } else if (targetByte / size < 0.75) {
      naturalWidth *= 0.75;
      naturalHeight *= 0.75;
    }

    // generate thumbnails
    while (size > targetByte) {
      if (blob.size > targetByte) {
        // the bigger the steps, the faster it will be.
        naturalWidth *= 0.99;
        naturalHeight *= 0.99;
      }
      let res = await new Promise((resolve, reject) => {
        const res = new Compressor(blob, {
          maxWidth: naturalWidth,
          maxHeight: naturalHeight,
          success(blob) {
            size = blob.size;
            console.log(naturalWidth, naturalHeight, size);
            compressed = res;
            resolve();
          },
          error: reject
        })
      });
    }

    // replace the compressed with the original image from above
    const original = img.src;
    img.onclick = () => { if (confirm("sure?")) img.src = original; };

    // compressed.result contains the final blob now
    img.src = URL.createObjectURL(compressed.result);

    await new Promise((r) => img.onload = r);
    console.log(compressed.result, img.naturalWidth, img.naturalHeight)

    document.body.append(img);
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.1.1/compressor.js"></script>

A: To get this exactly to one size is almost impossible. There are too many factors.  You can roughly determine it by a rule of three or take the information from Christoph. I would reduce the image size in advance and you should always consider the quality.  You could otherwise use .gif, but this supports only 256 colors, but would be smaller.


text:
Q: Standard Library Source File I am using GCC on cygwin, but I want to browse for source file of string.cpp from the standard library . I just want to read the source file for knowledge of the function I am using, but the problem is I can't find it anywhere. I only find the header files but not the source files. I assume it is store somewhere else, or maybe in another form? lib? dll? If so, then how can I extract that out..
Thx

A: std::string is actually a template specialization of std::basic_string for the normal char type. Template C++ tends to end up solely in header files.
I haven't used the gcc library implementation, but there may well be no cpp files (or only files for implementing heavy lifting).

A: On my installation, it's located in the vicinity of:
/usr/lib/gcc/i686-pc-cygwin/4.3.4/include/c++/string
/usr/lib/gcc/i686-pc-cygwin/4.3.4/include/c++/bits/basic_string.h

to find this sort of stuff:
cd /usr
find . | grep string


text:
Q: Comparar Duas datas e hora Bom dia galera, estou tentando comparar duas datas mas não estou obtendo sucesso. Eu tenho 2 datas: dataAtual e dataPedido. O que eu quero fazer é que se a dataAtual for igual a dataPedido e se a hora atual for maior que 11:00 AM aparece uma mensagem. Tentei fazer isso mas nao deu certo:
public void getDateTime(Date dataPedido, Date dataSistema) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("HH:mm");
            Date horaAtual = new Date();
            String horaMaxima = "11:00";
            dateFormat.format(horaAtual);

            Date horaMax = null;
            horaMax = dateFormat.parse(horaMaxima);

            if (horaAtual.getTime() > horaMax.getTime() && dataPedido.compareTo(dataSistema) == 0) {
                System.err.println("HORA ATUAL MAIOR, nao pode fazer");
                horarioComparacao = false;

            } else {
                System.err.println("HORA ATUAL Menor, pode fazer");
                horarioComparacao = true;

            }
            System.err.println("HORA MAXIMA: " + horaMax);

        } catch (ParseException ex) {
            Logger.getLogger(frmPedidos.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

A: Se você usar a classe Calendar tudo fica mais simples.
Escreva um método para converter um objecto Date em Calendar com a opção de "zerar" a parte do Time.
public static Calendar DateToCalendar(Date date, boolean setTimeToZero){
    Calendar calendario = Calendar.getInstance();
    calendario.setTime(date);
    if(setTimeToZero){
        calendario.set(Calendar.HOUR_OF_DAY, 0);
        calendario.set(Calendar.MINUTE, 0);
        calenario.set(Calendar.SECOND, 0);
        calendario.set(Calendar.MILLISECOND, 0);
    }
    return calendario;
}

Suponho que quando diz "se a dataAtual for igual a dataPedido..." está a considerar que elas são iguais independente da hora.
Escreva um método para testar as condições:
public boolean possoProcessarPedido(Date dataPedido) {

    Calendar dataAtualTimeZero = DateToCalendar(new Date(), true);
    Calendar dataPedidoTimeZero = DateToCalendar(dataPedido, true);

    if(dataAtualTimeZero.compareTo(dataPedidoTimeZero) != 0){
        // A data do pedido e a data atual são diferentes: pode processar
        return true;
    }

    Calendar dataAtual = DateToCalendar(new Date(), false);
    Calendar dataAtualAs11Horas  = DateToCalendar(new Date(), true);
    dataAtualAs11Horas.set(Calendar.HOUR_OF_DAY, 11);

    if(dataAtual.after(dataAtualAs11Horas){
        //As datas são iguias mas já passa das 11 horas: não pode processar
        return false;
    }
    // As datas são iguais e é antes das 11 horas: pode processar
    return true;
}

Use o método da seguinte forma:
if(possoProcessarPedido(dataPedido){
    // código para processar pedido
}

A: Apenas para complementar as respostas anteriores, a partir do Java 8 você pode usar a API java.time.
Há alguns detalhes a se considerar ao trabalhar com a API antiga (java.util.Date) e a nova simultaneamente, pois alguns conceitos são diferentes. Segue então uma breve explicação sobre Date, para que possamos entender a conversão desta para as classes do java.time.
Sobre java.util.Date
java.util.Date, apesar do nome, não é exatamente uma data propriamente dita, pois ela não representa um único valor de dia, mês e ano. Ela representa na verdade um timestamp: um número gigante (do tipo long) contendo a quantidade de milissegundos desde o Unix Epoch (1970-01-01T00:00Z, ou "1 de janeiro de 1970, à meia noite, em UTC").
O timestamp é um valor, digamos, "universal". Neste exato momento, em qualquer lugar do mundo, o timestamp é o mesmo. Em Java, basta chamar System.currentTimeMillis() e você terá o timestamp correspondente ao instante atual. Eu rodei agora e o valor retornado foi 1534249967760. E este valor é o mesmo no mundo todo: qualquer computador, em qualquer fuso horário do mundo, obteria este mesmo número se chamasse System.currentTimeMillis() no mesmo instante que eu.
Só que este valor (1534249967760) pode representar uma data/hora diferente em cada fuso horário. Em São Paulo, este timestamp equivale a 14 de agosto de 2018, às 09:32:47.760 da manhã. Em Londres, equivale ao mesmo dia (14 de agosto), mas neste mesmo instante o horário lá é 13:32 (1 da tarde). E em Samoa já são 01:32 (1 da manhã) do dia 15.
Podemos ver melhor isso imprimindo o Date (com System.out.println ou com qualquer API de log). Ao imprimí-lo, este é convertido para o timezone default da JVM, por isso o resultado contém uma data e hora específicas. Mas o valor do Date não muda. No código abaixo eu uso a classe java.util.TimeZone para mudar o timezone default:
// código rodado quando o timestamp atual é 1534249967760
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Apia"));
System.out.println(date.getTime() + "=" + date);

Eu mudei o timezone default 3 vezes, para São Paulo, Londres e Apia (que é o timezone de Samoa) e imprimi o Date e o valor de getTime() (que retorna o valor do timestamp). O resultado é:
1534249967760=Tue Aug 14 09:32:47 BRT 2018
1534249967760=Tue Aug 14 13:32:47 BST 2018
1534249967760=Wed Aug 15 01:32:47 WSST 2018

Repare que o timestamp não muda, mas a data e hora sim. Isso acontece porque ao imprimir o Date, ele converte o timestamp para o timezone default, resultando em uma data e hora diferentes em cada caso. Mas estes valores de data e hora não fazem parte do Date, somente o timestamp.
Por isso, para converter um Date para uma data (um dia, mês e ano específicos), você deve escolher um fuso horário (que a API chama de timezone). O que acontece com Calendar é que internamente ele usa o timezone default da JVM e já calcula os valores para o dia, mês, ano, horas, minutos, segundos etc.
Mas no java.time isso não acontece automaticamente e você deve especificar qual timezone deve ser usado.
Com isso, podemos prosseguir para a conversão de Date para as classes do java.time.
Converter Date para uma data e hora específicas
Primeiro convertemos o Date para java.time.Instant, que é a classe que representa um timestamp. Para isso foi adicionado o método toInstant() (disponível a partir do Java 8):
Date data = new Date();
// criar Instant (com o mesmo valor do timestamp de Date)
Instant instant = data.toInstant();

A partir do Instant, podemos convertê-lo para um timezone qualquer, usando a classe java.time.ZoneId (que representa um timezone). O resultado será um java.time.ZonedDateTime (uma classe que representa uma data e hora em um timezone específico). Exemplo:
Date data = new Date();
ZonedDateTime zdt = data.toInstant()
    // converter o Instant para um timezone
    .atZone(ZoneId.of("America/Sao_Paulo"));

O nome do timezone (America/Sao_Paulo) segue a nomenclatura da IANA, que é a base de dados usada pela JVM para obter informações do timezone (como início e fim do horário de verão, por exemplo, assim ela consegue saber exatamente a data e hora correspondente ao timestamp).
Se você quiser usar o timezone default da JVM (e assim simular o que Calendar faz), pode usar ZoneId.systemDefault(). Fica a seu critério.
Para obter a data atual, basta usar o método now():
ZonedDateTime agora = ZonedDateTime.now();

Isso cria um ZonedDateTime contendo a data e hora atual, no timezone default da JVM. Se quiser usar um timezone específico, basta passar o ZoneId:
ZonedDateTime agora = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo"));

Com isso você obtém os valores corretos para a data e hora no timezone que quiser, sem depender da configuração da JVM (que pode mudar sem você saber, pois qualquer parte do código pode chamar TimeZone.setDefault, afetando todas as aplicações que rodam na mesma JVM).
Para fazer as comparações necessárias, basta usar o método equals (para verificar igualdade) e isAfter (para saber se um determinado instante ocorre depois de outro).
A primeira comparação leva em conta apenas a data (ignorando a hora), então você deve usar o método toLocalDate(), que retorna um java.time.LocalDate (uma classe que só possui dia, mês e ano), assim a comparação é feita ignorando o horário.
Depois, para a segunda comparação, basta usar o método toLocalTime(), que retorna um java.time.LocalTime (uma classe que só possui hora, minuto, segundo e frações de segundo). Em seguida comparamos com outro java.time.Localtime cujo valor é 11:00.
Aliás, esta é outra característica do java.time: várias classes especializadas para cada situação (uma que só representa data, outra só para as horas, outra para data e hora com timezone, etc).
Enfim, o código ficaria assim (assumindo que você quer usar o timezone default da JVM):
public boolean possoProcessarPedido(Date dataPedido) {
    ZonedDateTime pedido = dataPedido.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime dataAtual = ZonedDateTime.now();

    // comparar somente a data (ignora o horário)
    if (! dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(LocalTime.of(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

Se ao invés do timezone default, você quiser usar um timezone específico, basta usar o ZoneId correspondente, conforme já explicado anteriormente.
Java 6 e 7
Para Java 6 e 7, você pode usar o ThreeTen Backport, um backport do java.time. Basicamente, possui as mesmas classes (Instant, LocalDate, ZoneId, etc) e métodos do Java 8, com uma diferença: no Java 8 as classes estão no pacote java.time, e no backport elas ficam em org.threeten.bp.
Outra diferença é que no Java 6 e 7 a classe Date não possui o método toInstant() e a conversão deve ser feita pela classe org.threeten.bp.DateTimeUtils:
Date date = new Date();
Instant instant = DateTimeUtils.toInstant(date);

O restante do código ficaria igual.
Java <= 5
Para Java <= 5, é possível usar o Joda-Time. Esta API é o "predecessor" do java.time, e muitos conceitos são parecidos (até alguns nomes de classes são os mesmos), embora ela não seja 100% igual.
O código fica bem parecido: ao invés de ZonedDateTime, usamos a classe org.joda.time.DateTime - aliás, todas as classes abaixo (LocalDate, Localtime, etc), embora tenham os mesmos nomes do java.time, estão no pacote org.joda.time:
public boolean possoProcessarPedido(Date dataPedido) {
    DateTime pedido = new DateTime(dataPedido);
    DateTime dataAtual = new DateTime();

    // comparar somente a data
    if (!dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(new LocalTime(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

Este código usa o timezone default da JVM para converter o Date para DateTime. Se quiser usar um timezone específico, use a classe org.joda.time.DateTimeZone:
DateTimeZone timezone = DateTimeZone.forID("America/Sao_Paulo");
DateTime pedido = new DateTime(dataPedido, timezone);
DateTime dataAtual = new DateTime(timezone);

O método forID recebe o nome do timezone, também seguindo a nomenclatura da IANA.

A: Acho melhor vc usar a classe calendar
Calendar dataAtual = new GregorianCalendar();
    Calendar dataMAxima = new GregorianCalendar();
    dataAtual.setTime(new Date());
    dataMAxima.set(Calendar.HOUR_OF_DAY, 11);
    dataMAxima.set(Calendar.MINUTE, 0);
    dataMAxima.set(Calendar.SECOND, 0);

nela vc tem metodos de comparação, acima eu explico com passar uma data e como setar uma data importante é setar hora, minuto e segundo


text:
Q: How to set the property as lazyloading in fluent-hibernate with auto-mapping? I am using auto-mapping with flent-hibernate for mapping. I would like if there is a way to set the reference property to be as 'lazy-loading' using IConvention or similar, rather than using separate mapping class?

A: firstly, i believe that lazy is the default behaviour.
you can test it quite easily-
[TestMethod]
        public void TestLazyLoading()
        {
            Airport firstObject = null;
            using (ISession session = this.SessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    ObjectDAO dao = new ObjectDAO(session, CurrentUser);
                    firstObject = dao.GetObject();
                    transaction.Commit();
                }
            }
            Assert.IsFalse(NHibernateUtil.IsInitialized(firstObject.Children));

        }

if you want to specify explicitly lazy / eager, use the following inside your MappingOverride class:
mapping.HasMany(x => x.Employees)
                //.Not
                .LazyLoad()
                ;

A: To adjust automappings you can use IAutoMappingOverride<SomeEntity>. You can change there exact property that you need


text:
Q: What happens when a pure virtual function is called on an instance of the parent class in which it is declared? I am new to C++ and have run into an interesting problem in some code with which I have been working lately. Suppose we have the following classes: Parent, Child_A, Child_B, and Child_C:
class Parent {
    ...
    virtual int Foo() = 0;
    ...
}

class Child_A : Parent {
    ...
    int Foo() { return 1; }
    ...
}

class Child_B : Parent {
    ...
    int Foo() { return 2; }
    ...
}

class Child_C : Parent {
    ...
    int Foo() { return 3; }
    ...
}

Now I know what happens if I do this:
std::unique_ptr<Child_A> a = std::make_unique<Child_A>();
Parent *p = &a;
p->Foo();

That will return 1. But my question is, what happens if I do this:
std::unique_ptr<Parent> p = std::make_unique<Parent>();
p->Foo();

Thanks to anyone who can help!
Edit: Turns out that my question does not make any sense, regardless of how many times I try to fix my syntax. A pure virtual function can't be called on the parent like that. I found out later that the code I was looking for did set the parent equal to a member of one of its child classes (with the virtual function defined) before it called that function...I had just missed it before.

A: You have a little misunderstood about C++ syntax, despite the fact your classes don't inherit from parent class.
When you declare a member function like this void foo() = 0, you are saying that your function isn't implemented and you're making your class abstract, and you cannot instantiate an abstract class. A pure virtual function doesn't mean "return 0".

A: If you wanted to be able to instantiate a parent, you could make the function virtual (not pure virtual) and then have the children override that function.


text:
Q: no logro regresar la diferencia, si alguien sabe hacerlo con filter quedo agradecido Compara dos arreglos y devuelve un nuevo arreglo con los elementos que sólo se encuentran en uno de los dos arreglos dados, pero no en ambos. En otras palabras, devuelve la diferencia simétrica de los dos arreglos.
Nota: Puedes devolver el arreglo con sus elementos en cualquier orden.
Hint 1
["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] debe devolver ["diorite", "pink wool"].
Hint 2
["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] debe devolver [].
Hint 3
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) debe devolver [4]

let diferencia = [];

function diffArray(arr1, arr2) {

   for (let i = 0; i < arr1; i++) {
       let diferencia =[];
       for (let j = 0; j < arr2; j++) {
           if (arr2[j] !== arr1[i]){
               diferencia.push(arr2[j])
           }

           if (arr1[i] !== arr2[j]){
               diferencia.push(arr2[j])
           }

       }
   }

return diferencia

}

A: Comparto el código que implementé, para los resultados que requieres.

function diffArray(arr1 = [], arr2 = []) {

  /**
   * Verificamos que no se proporcionen valores nulos,
   * si es nulo alguno de los parametros, se inicializa como un arreglo vacio
   **/
  arr1 = arr1 !== null ? arr1 : [];
  arr2 = arr2 !== null ? arr2 : [];

  // Unimos los 2 arreglos
  const fullArray = arr1.concat(arr2);

  // Ordenamos los items del arreglo nuevo
  fullArray.sort();

  // retornamos un arreglo nuevo con los items que no se repiten
  return fullArray.filter((item, i) => item !== fullArray[i + 1] && item !== fullArray[i - 1]);
}

let array1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub"];
let array2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"];
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = ["andesite", "grass", "dirt", "dead shrub"];
array2 = ["andesite", "grass", "dirt", "dead shrub"];
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = [1, 2, 3, 5];
array2 = [1, 2, 3, 4, 5];
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = undefined;
array2 = undefined;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = null;
array2 = null;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = undefined;
array2 = null;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = null;
array2 = undefined;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = ["andesite", "grass", "dirt", "pink wool", "dead shrub"];
array2 = undefined;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = undefined;
array2 = [1, 2, 3, 4, 5];
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = [1, 2, 3, 4, 5];
array2 = null;
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

array1 = null;
array2 = ["andesite", "grass", "dirt", "dead shrub"];
console.log('array1: ' + array1 + ' array2: ' + array2 + ' resultado: ', diffArray(array1, array2));

Espero te sirva, Saludos.

A: Mira esta forma es de sintaxis más básica, la función devolverArray recibe 2 arreglos de parametros, dentro de ella se genera un arreglo vacio llamado nuevoArreglo.
La función tiene 2 for, el primero recorre el arreglo 1 y en el if pregunta si dentro del arreglo 2 incluye el elemento del primer arreglo si lo incluye lo imprime en la consola , si no lo agrega a nuevoArreglo, el otro for hace lo mismo pero ve los elemento del arreglo 2 si estan en el arreglo 1.
Espero te ayude la clave es usar la función arreglo.include)
arreglo1 =["andesite", "grass", "dirt", "pink wool", "dead shrub"];
arreglo2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"] ;
n1 = [1,2,3,5]
n2= [1,2,3,4,5]

function devolverArray(arr1,arr2){
  let nuevoArreglo = [];
  for(i of arr1){
    if(arr2.includes(i)){
      console.log(i);
    }else{
      nuevoArreglo.push(i)
    }
  }
  for(i of arr2){
    if(arr1.includes(i)){
      console.log(i);
    }else{
      nuevoArreglo.push(i)
    }
  }
  return nuevoArreglo;

}

console.log(devolverArray(n1,n2)) //Devuelve: [4]
console.log(devolverArray(arreglo1,arreglo2)) //Devuelve : ['pink wool', 'diorite']

A: Este ejercicio yo le e visto en una plataforma y lo realize de la siguiente manera:
elabore una funcion que toma como parametro dos arreglos,
utilize programacion funcional, los metodos, concat para concatenar los arreglos y el metodo filter para filtrar elementos.
 function diffArray(arr1, arr2) {
      return arr1
        .concat(arr2)
        .filter(item => !arr1.includes(item) || !arr2.includes(item));
    }

Despues adentro de filtrar lo que se encargara de hacer el codigo es verificar si cada elemento de item (que es el conjunto de elementos de arr1 + arr2) no esta incluido en arreglo1 o arreglo2, si se cumple esto entonces solo tomara los que no se repiten, como resultado se obtendra 4 en el ejemplo.
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);


text:
Q: Output a specific result from array of objects aggregation - MongoDB I have a data looking like this:
{
  "_id": ObjectId("620ca4e292a990273446cf7b"),
  "data": [
    {
      "flagging": "BUSINESS",
      "information": [
        {
          "room": 1,
          "status": "AVAILABLE"
        },
        {
          "room": 2,
          "status": "BUSY"
        }
      ]
    },
    {
      "flagging": "PRIVATE",
      "information": [
        {
          "room": 1,
          "status": "AVAILABLE"
        },
        {
          "room": 2,
          "status": "CLEANING"
        }
      ]
    },
    {
      "flagging": "PUBLIC",
      "information": [
        {
          "room": 1,
          "status": "SERVICE"
        },
        {
          "room": 2,
          "status": "AVAILABLE"
        }
      ]
    }
  ],
  "createdAt": "2022-02-16T07:16:50.674Z"
}

I'm trying to make a service whether user can input a certain flagging, and the data with the corresponding flagging will show as a result. I tried using this code below but what I get are all the datas, not the filtered ones.
db.coll.aggregate([
    {
        $match: { _id: ObjectId("620ca4e292a990273446cf7b") },
    },
    {
        $project: { _id: 0, "data": 1 }
    }
])

What should I change in the code so I can get the following result (if the requested flagging are BUSINESS and PUBLIC)?
{
  "data": [
    {
      "flagging": "BUSINESS",
      "information": [
        {
          "room": 1,
          "status": "AVAILABLE"
        },
        {
          "room": 2,
          "status": "BUSY"
        }
      ]
    },
    {
      "flagging": "PUBLIC",
      "information": [
        {
          "room": 1,
          "status": "SERVICE"
        },
        {
          "room": 2,
          "status": "AVAILABLE"
        }
      ]
    }
  ]
}

Thanks for the help

A: You need  $filter in the $project stage  to filter the nested document(s) in data array with flagging is within ["BUSINESS", "PUBLIC"].
{
  $project: {
    _id: 0,
    data: {
      "$filter": {
        "input": "$data",
        "cond": {
          $in: [
            "$$this.flagging",
            [
              "BUSINESS",
              "PUBLIC"
            ]
          ]
        }
      }
    }
  }
}

Sample Mongo Playground


text:
Q: What's wrong on my conditions ? Using the np.where statement to flag my pandas dataframes The function i am using is keep giving the red filter condition where not applied.
Here the function i am using:
tolerance = 5
def rag(data):

    red_filter   =  ((data.SHIPMENT_MOT_x == 'VESSEL') & \
                     ((data.latedeliverydate + pd.to_timedelta(tolerance,unit='D')) < data.m6p)) | \
                     ((data.SHIPMENT_MOT_x == 'AIR') & (data.latedeliverydate < data.m6p))

    green_filter =  (data.SHIPMENT_MOT_x == 'VESSEL') & \
                    (data.M6_proposed == data.m6p) & \
                    ((data.latedeliverydate + pd.to_timedelta(tolerance,unit='D')) >= data.m6p) | \
                     ((data.SHIPMENT_MOT_x == 'AIR') & (data.latedeliverydate >= data.m6p))

    amber_filter =  (data.SHIPMENT_MOT_x == 'VESSEL') & \
                    (data.M6_proposed != data.m6p) & \
                    ((data.latedeliverydate + pd.to_timedelta(tolerance,unit='D')) >= data.m6p) | \
                    ((data.SHIPMENT_MOT_x == 'AIR') & (data.latedeliverydate >= data.m6p))

data['RAG'] = np.where(green_filter, 'G', np.where(amber_filter, 'A', np.where(red_filter, 'R', '')))

A: Here is the solution if you guys are interested.
np.where is useful but would not recommend when there are multiple conditions
def pmm_rag(data):

    if  ((data.MOT== 'VESSEL') & ((data.m0p + pd.to_timedelta(tolerance,unit='D')) < data.m6p)) | ((data.SHIPMENT_MOT_x == 'AIR') & (data.m0p < data.m6p)):
        return 'R'
    elif (data.MOT== 'VESSEL') & (data.M6_proposed == data.m6p) & ((data.m0p + pd.to_timedelta(tolerance,unit='D')) >= data.m6p) | ((data.MOT== 'AIR') & (data.m0p >= data.m6p)):
        return 'G'
    elif (data.MOT== 'VESSEL') & (data.M6_proposed != data.m6p) & ((data.m0p + pd.to_timedelta(tolerance,unit='D')) >= data.m6p) | ((data.MOT== 'AIR') & (data.m0p >= data.m6p)):
        return 'A'
    else:
        return ''


text:
Q: Unable to resolving the promise inside of a function Here is a piece of my original code, Why I can't resolve the instruct function this way?
Actually I used to resolve the promises like this and the same codes for other functions worked before.
I'm not able to find the reason and the solution without a hand.

var instructResolve;
async function instruct(location, category){

    switch(location) {

          case 'User_Was_Silent':
          console.log('Start!')
          await audioPlay();
          console.log('After audioPlay await is done, then resolve instruct!')
          instructResolve();

          break;
    }

    return new Promise((resolve) => {
    instructResolve = resolve;
    });

};

function audioPlay(source){

  console.log('await audioPlay..')

 return new Promise((resolve) => {
  setTimeout(function(){
     console.log('audioPlay resolved..')
     resolve();
  }, 5000)

  });
}

recognize();
async function recognize(){

await instruct('User_Was_Silent');
//After resolving instruct do stuff like logging some success message on the console
console.log('Final log success!')

}

At the recognize function I'm waiting for the instruct function to resolve and then we do stuff like logging some success message on the console, but since recognize  for some reason doesn't resolve we can not see the console.log('Final log success!')
UPDATE:
I have a similar code that works just fine without any issues, I have implemented the promises and resolves just like the code above but it works!

var updateGuiderResolve;
function updateGuider(state, guide, lower){
console.log('updateGuider...')
    switch(state) {

          case 'default':
          stateReveal("default");
          break;

    }

          return new Promise((resolve) => {
          updateGuiderResolve = resolve;
          });

}

function stateReveal(state){
   console.log('stateReveal...')
   setTimeout(function(){
   speak();
   }, 5000);

}

function speak(){
console.log('speak...')
setTimeout(function(){
console.log('updateGuiderResolve...')
   updateGuiderResolve()
   }, 5000);

}

async function tutor(){
await updateGuider('default');
console.log('final...')

}
tutor()

A: I can see 2 problems in the code base.
One is
instructResolve(); // It's not function, I think as it's only declared at first.

Second one is
await instruct('User_Was_Silent'); // This does not need to add await as it's already async function. Simply call instruct('User_Was_Silent'); and missing second param in this function.

    var instructResolve;
    async function instruct(location, category=null){

        switch(location) {

              case 'User_Was_Silent':
              console.log('Start!')
              await audioPlay();
              console.log('After audioPlay await is done, then resolve instruct!')

              break;
        }
    };

    function audioPlay(source){
     console.log('await audioPlay..')

     return new Promise((resolve) => {
      setTimeout(function(){
         console.log('audioPlay resolved..')
         resolve();
      }, 5000)

      });
    }

async function recognize(){

   await instruct('User_Was_Silent');
   //After resolving instruct do stuff like logging some success message on the console
   console.log('Final log success!')

}
recognize();

A: Try calling instructResolve inside Promise like that:
var instructResolve;
async function instruct(location, category){
 switch(location) {
   case 'User_Was_Silent':
   console.log('Start!')
   await audioPlay();
   console.log('After audioPlay await is done, then resolve instruct!')
   break;
 }

 return new Promise((resolve) => {
    instructResolve = resolve;
    instructResolve();
 });
}

A: There is a solution like this one but I want to know why the question's code doesn't work?

var instructResolve;
async function instruct(location, category){
    return new Promise(async (resolve) => {
    switch(location) {

          case 'User_Was_Silent':
          console.log('Start!')
          await audioPlay();
          console.log('After audioPlay await is done, then resolve instruct!')
          resolve();

          break;
    }

    });

};

function audioPlay(source){

  console.log('await audioPlay..')

 return new Promise((resolve) => {
  setTimeout(function(){
     console.log('audioPlay resolved..')
     resolve();
  }, 5000)

  });
}

async function recognize(){

await instruct('User_Was_Silent');
//After resolving instruct do stuff like logging some success message on the console
console.log('Final log success!')

}

recognize();


text:
Q: Force system to use NTP time Usually ntpd will refuse to change (or slew) system time if difference is too large.
Is there some way (possibly via ntpq) to tell ntpd: "jump to whatever time you think is right"?
Specifically it should be a "jump if synchronized" action.
I would like to avoid, if possible killall -HUP ntpd && ntpd -g or equivalent commands

A: Consider using sntp:
sudo sntp -s time.nist.gov

For a full list of the NIST time-server IP addresses, see https://tf.nist.gov/tf-cgi/servers.cgi.

A: You can use the -g flag on startup of the daemon.
From the man page for ntpd,

-g Normally, ntpd exits if the offset exceeds the sanity limit, which is 1000s by default. [...] This option overrides the limit and allows the time to be set to any value without restriction; however, this can happen only once. After that, ntpd will exit if the limit is exceeded.


text:
Q: Same Value in the Dynamic jQuery Form Hello to all users of the site, my intent was to create a dynamic form for a multiple association of multiple products to the same customer, and I had the idea to implement it with the help of jquery being able to create a dynamic form, so looking on the internet I came across an example on jsFiddle, which works perfectly. The only thing that I need would be not to have an empty input where you can write but an input that has a fixed value. For example, the word "TEST", and every time a new input is generated, the input generated always has the value = "TEST".
How can I do it?
Code (you can copy and paste in your test.html it works!):

<form role="form" action="/wohoo" method="POST">
    impianti

                <input type="text" name="impianti[]">
                <input type="text" name="impianti[]">
                <button type="button" class="RIMUOVI_INPUT">Remove</button>

        <button type="button" class="add-field">Add field</button>

</form>

How to put into.val() <?php echo $row['impianto_id'] ;?>
I have this:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM impianti";
$impianti = mysqli_query($connessione, $query_string);
?>

IMPIANTO ID CAMPAGNA

<select name="impianto_id_campagna">
    <?php
    while ($row = mysqli_fetch_assoc($impianti)) { ?>
        <option value="<?php echo $row['impianto_id']; ?>">
            <?php echo $row['concessionaria']; ?>
        </option>
    <?php } ?>
</select>

I want to echo this in .val()
But it does not work...

<form role="form" action="/wohoo" method="POST">
    impianti

                <input type="text" name="impianti[]">
                <input type="text" name="impianti[]">
                <button type="button" class="RIMUOVI_INPUT">Remove</button>

        <button type="button" class="add-field">Add field</button>

</form>

A:

$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function() {

var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);

$(".add-field", $(this)).click(function(e) {

$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('TEST').focus();});// here the test

$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function() {

if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)

$(this).parent('.CLASSE_DA_SPECIFICARE').remove();

});
});

<form role="form" action="/wohoo" method="POST">

impianti

<input type="text" name="impianti[]">

<input type="text" name="impianti[]">

<button type="button" class="RIMUOVI_INPUT">Remove</button>

<button type="button" class="add-field">Add field</button>

</form>

All you had to do is just add 'test' into the .val() of the input that you created.


text:
Q: база английских слов мне нужна база английских слов и желательно с переводом на русский , где такую можно взять ?
после многочисленных проб парсинга слов с сайтов я набрал около 50к слов , но в них так много ошибок в переводе , что я решил сделать другую
Для моих нужд нужно около 300-400к слов с переводом . я видел много баз , но они меня не устраивали лишними словами "ZZZ" , "ABC" и так далее .
так же повторюсь , желателен ПРАВИЛЬНЫЙ перевод , а не то , что я увидел в одной из баз Sport - скорость
формать записи , наверно , важен
Мне нужен список слов в столбик )
например :
1) Eng word
  на другой строчке translate
2) Eng word - translate
3) eng words /transcription/ - translate


text:
Q: Unresponsive Scene During Scene Change I am working on a game with SpriteKit. I have finished my game, but wanted to add a main menu scene. I made two new files, "HomeScene.swift" and "HomeScene.sks". I was able to get the HomeScene to appear before the GameScene when I ran in the simulator, but it was not responsive to any touches, did not transition to the GameScene, or was affected by any code in my "HomeScene.swift" file.
Do I need to link the scene to the swift file somehow? Do I need to initialize the scene somehow?


text:
Q: How to read a div property in js?
Possible Duplicate:
How to get the attributes of a HTML element using JQuery?

I have a piece of JS and I need to read property 'value' from a div.
I do this:
$('#calendar_event_path')

I get this as and answer:
[

]

How can I get "company_events_index" value from the div?

A: use data-value attribute in your html

the in jQuery fetch its value using data()
var sumthng = $('#calendar_event_path').data("value");


text:
Q: Advanced CSS animations I have been looking over this example and wanting to take it up a notch, I am trying for the number "1" card to start off like this

(-webkit-transform: rotateZ( 160deg );) and rotateZ towards 0 WHILE flipping, I've been playing around with the matrix and skewing and cannot seem to get that effect.

A: You can give the same transform property multiple (space separated) transform-functions at the same time, something like this in your case;
#card .front {
    transition: all 1s;
    transform: rotateY(0deg) rotateZ(200deg);
}
#card.flipped .front {
    transform: rotateY(180deg) rotateZ(0deg);
}

(The same applies to the backface)
Chrome-only demo: http://jsfiddle.net/4Z4sF/