text:
Q: Pandas - create new column where rows match I'd like to create a new column in pandas that matches row values  based on the same condition. I'm trying to turn a dependent variable into an independent variable.
In the sample dataframe below (taken from the actual dataset), each row is separated by the value test_name and by time period, 'tp'. I want to create a new column intensity_value, where the values for tp are equal and place the new column where the test_value is 'PANAS'
For instance, in the dataframe, the third row has a 'PANAS' value of 35 and an intensity value of 50 in the 7th row. Both rows have the same id (73) and time period, w3s1. The ideal dataframe would have a new column in the 3rd row, intensity_value of 50.
Code is below to create a dataframe from a dictionary. I haven't been able to find any examples online that create new columns by similar row values.
Thanks  for any help and please let me know if I can make this question easier to answer.
df = {'trial_id': {73: 79, 300: 79, 515: 79, 715: 79, 2541: 79, 2673: 79, 2810: 79, 2960: 79}, 'tp': {73: 'w1s1', 300: 'w2s1', 515: 'w3s1', 715: 'w4s1', 2541: 'w1s1', 2673: 'w2s1', 2810: 'w3s1', 2960: 'w4s1'}, 'test_name': {73: 'PANAS', 300: 'PANAS', 515: 'PANAS', 715: 'PANAS', 2541: 'intensity', 2673: 'intensity', 2810: 'intensity', 2960: 'intensity'}, 'value': {73: 25.0, 300: 30.0, 515: 35.0, 715: 34.0, 2541: 0.0, 2673: 0.0, 2810: 50.0, 2960: 0.0}}

pd.DataFrame.from_dict(df)

A: just join/merge the same df with itself
import pandas as pd
df = {'trial_id': {73: 79, 300: 79, 515: 79, 715: 79, 2541: 79, 2673: 79, 2810: 79, 2960: 79}, 'tp': {73: 'w1s1', 300: 'w2s1', 515: 'w3s1', 715: 'w4s1', 2541: 'w1s1', 2673: 'w2s1', 2810: 'w3s1', 2960: 'w4s1'}, 'test_name': {73: 'PANAS', 300: 'PANAS', 515: 'PANAS', 715: 'PANAS', 2541: 'intensity', 2673: 'intensity', 2810: 'intensity', 2960: 'intensity'}, 'value': {73: 25.0, 300: 30.0, 515: 35.0, 715: 34.0, 2541: 0.0, 2673: 0.0, 2810: 50.0, 2960: 0.0}}

df1 = pd.DataFrame.from_dict(df)
df2 = df1.loc[df1['test_name'] == 'PANAS']
df1 = df1.loc[df1['test_name'] == 'intensity']
df3 = df2.merge(df1, how='inner', left_on='tp', right_on='tp')
df3 = df3[['tp', 'test_name_x', 'value_x', 'test_name_y', 'value_y']]
print(df3)

here is the result:
tp test_name_x  value_x test_name_y  value_y
0  w1s1       PANAS     25.0   intensity      0.0
1  w2s1       PANAS     30.0   intensity      0.0
2  w3s1       PANAS     35.0   intensity     50.0
3  w4s1       PANAS     34.0   intensity      0.0

you can change the column names as you like


text:
Q: Preposition problem of 'on' In one our Indian English literature textbook, one of the objective was given as follows-
Students will use vocabulary to write about a range general vocational subject area.
Is the sentence correct? Shouldn't we use "range on general"?

redpajama_set_name: RedPajamaStackExchange


text:
Q: NI DAQ M series counter with trigger I am using a M series DAQ's two counter channel to generate pulse train to control two step motor, but these two channels are not fully independent, when one channel generate pulse, the other channel with change state too.
  In this link, it mentioned a way to use paule trigger to pause the other channel when one channel generating finite pulse. Link
  I tried to convert it to python code as below:
outputchannel = "Dev1/Ctr0"
gatechannel = "Dev1/Ctr1"
frequency = 1000
samples = 1000

def GenerateFinitePulse(outputchannel, gatechannel, pulsecount, frequency):
    with nidaqmx.Task() as pulse_task:
        pulsechannel = pulse_task.co_channels.add_co_pulse_chan_freq(
            counter=outputchannel,freq=frequency, duty_cycle=0.5)

        pulse_task.timing.cfg_implicit_timing(
            sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS,
            samps_per_chan=1000)

        pulse_task.triggers.pause_trigger.trig_type = nidaqmx.constants.TriggerType.DIGITAL_LEVEL
        pulse_task.triggers.pause_trigger.dig_lvl_src = gatechannel + "InternalOutput"
        pulse_task.triggers.pause_trigger.dig_lvl_when = nidaqmx.constants.Level.LOW

        pulse_task.start()

        with nidaqmx.Task() as gate_task:
            gatechannel = gate_task.co_channels.add_co_pulse_chan_time(
                counter=gatechannel, low_time= 1, high_time= pulsecount/frequency)
            gatechannel.co_pulse_term = " "
            gate_task.start()

        time.sleep(10)

one question is that even set the co_pulse_term = " ", i still can get the pulse output from the channel from a oscilloscope.
and here is an error I got:

nidaqmx.errors.DaqError: Source terminal to be routed could not be found on the device.

Make sure the terminal name is valid for the specified device. Refer
  to Measurement & Automation Explorer for valid terminal names.
  Property: DAQmx_DigLvl_PauseTrig_Src Property:
  DAQmx_DigLvl_PauseTrig_When Source Device: Dev1 Source Terminal:
  Dev1/Ctr1InternalOutput

somehow it can't find the "Internal output".
please help if anyone has experience. Thank you very much!


text:
Q: Same PHP, Same Server, Different Results I have three domains on the same server (CentOS 7.5.1804), all running WordPress 4.9.8, all running the same version of PHP (7.2.10) and using the same php.ini file (literally, not the same php.ini file copied to each directory, the exact same single file).
The problem is that on only one domain, WordPress thinks that I don't have php-mysql installed, yet the other two sites work without issue.
I get the following on the non-working domain:

Your PHP installation appears to be missing the MySQL extension which
  is required by WordPress.

Despite the fact that the same php.ini file is being used, on the non-working site, the phpinfo() report is missing the mysqli section.
Domains are: hummdis.com (non-working), dev.hummdis.com (working),
exoticallyplugged.com (working).
Thoughts??

A: The only explanation I can conceive is that all tests for MySQL fail, and they do so in all your sites.
But on the two working sites, you have a db.php fixup file that makes things right. On the one that doesn't work, the WP_CONTENT_DIR has no fixup.
This is the relevant source section:
if ( ! extension_loaded( 'mysql' ) && ! extension_loaded( 'mysqli' )
    && ! extension_loaded( 'mysqlnd' ) && ! file_exists( WP_CONTENT_DIR . '/db.php' ) ) {
    wp_load_translations_early();
    $protocol = wp_get_server_protocol();
    header( sprintf( '%s 500 Internal Server Error', $protocol ), true, 500 );
    header( 'Content-Type: text/html; charset=utf-8' );
    die( __( 'Your PHP installation appears to be missing the MySQL extension which is required by WordPress.' ) );

As you can see, the error is only generated if all the tests fail, and there is no "db.php" to be found.
You may also want to check whether the .htaccess directives are the same between the sites. I seem to remember that MySQL modules may be loaded dynamically, and if so, it could be that some sites load them, and some don't.

A: So, I've resolved the issue and I'm not 100% sure what fixed it.  However, these are the steps that I took:

*

*yum update

*This resulted in:

Found 3 pre-existing rpmdb problem(s), 'yum check' output follows:

I'm not going to provide the full update, the point is that I couldn't perform a Yum update because of these issues.

*I found this post and followed the steps.

*I then found this post and followed the steps that install yum plugin-priorities.

I then tested the site and it's loading without issue.

A: Maybe missing from $PATH the locations, some info. Go to commnad line of a working domain and issue:  which php-mysql
and issue the same commnad to the one that is not working.
It looks, if you use diffent linux user, in .profile to have problem


text:
Q: Get Publish Response/PubAck latency with paho org.eclipse.paho.client.mqttv3.MqttClient publish I am using paho library Classes for Mqtt Connections org.eclipse.paho.client.mqttv3.MqttClient. (not MqttAsyncClient)
In my case when I publish using

mqttClient.publish(uid + "/p", new MqttMessage(payload.toString().getBytes()));

This method does the task for me but doesn't return anything so I can't check the latency between publish and pubAck.
To get the latency I use the following instead of directly calling publish function of mqttClient.
    public long publish(JsonObject payload , String uid, int qos) {
    try {
        MqttTopic topic = mqttClient.getTopic(uid + "/p");
        MqttMessage message = new MqttMessage(payload.toString().getBytes());
        message.setQos(qos);
        message.setRetained(true);
        long publishTime = System.currentTimeMillis();
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion(10000);
        long pubCompleted = System.currentTimeMillis();
        if (token.getResponse() != null && token.getResponse() instanceof MqttPubAck) {
            return pubCompleted-publishTime;
        }
        return -1;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

This gets the work done, but I am not sure whether this is the right approach or not. Please let me know in case there is some other way to to do this.


text:
Q: Agrupar SQL por campo Tengo los siguientes datos en una tabla, necesito agrupar por "grupos" del campo U_entregas, necesito que agrupe cada que detecte un grupo diferente, es decir, en el siguiente ejemplo muestra los primeros 2 registros en 0, necesito que se agrupen esos 2 y muestre la fecha mas antigua, luego continúe con los números 2 y muestre la fecha mas antigua de esa agrupación, luego agrupe los numero 3 y después agrupe los números 2 de nuevo pero no en la primera agrupación de numero 2 y así sucesivamente.
La tabla es:
UpdateDate/U_Entrega/UpdateTS

2021-08-17/ 0 / 165458

2021-08-17/ 0 / 165534

2021-10-28/ 2 / 121425

2021-10-28/ 2 / 122802

2021-10-28/ 2 / 122825

2021-10-28/ 2 / 122925

2021-10-28/ 3 / 122945

2021-10-28/ 3 / 122959

2021-10-28/ 3 / 134413

2021-11-04/ 3 / 95207

2021-11-04/ 2 / 101059

2022-01-04/ 2 / 175444

2022-01-05/ 2 / 141023

2022-01-05/ 3 / 154301

2022-01-05/ 3 / 154313

2022-01-05/ 3 / 162335

2022-01-05/ 3 / 162829

2022-01-05/ 3 / 163106

2022-01-05/ 3 / 163415

y necesito que el resultado sea :
UpdateDate/U_Entrega/UpdateTS

2021-08-17/ 0 / 165458

2021-10-28/ 2 / 121425

2021-10-28/ 3 / 122945

2021-11-04/ 2 / 101059

2022-01-05/ 3 / 154301

A: Pues esto funciona:
;WITH cte
AS (SELECT
  *,
  ROW_NUMBER() OVER (ORDER BY id ASC) - ROW_NUMBER() OVER (PARTITION BY [U_Entrega] ORDER BY UpdateDate, U_Entrega DESC) rn
FROM datos)

SELECT
  [UpdateDate], [U_Entrega], [UpdateTS]
FROM (SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY [U_Entrega], rn ORDER BY UpdateDate, U_Entrega DESC) rn2
  FROM cte) a
WHERE rn2 = 1
ORDER BY id ASC

El único ajuste que se debe realizar es genera una columna auto incrementable para tener como referencia.
Un ejemplo funcional en este fiddle: http://sqlfiddle.com/#!18/ec9ba/2
A continuacion el resultado que se obtiene:
| UpdateDate | U_Entrega | UpdateTS |
|------------|-----------|----------|
| 2021-08-17 |         0 |   165458 |
| 2021-10-28 |         2 |   121425 |
| 2021-10-28 |         3 |   122945 |
| 2021-11-04 |         2 |   101059 |
| 2022-01-05 |         3 |   154301 |

fuente: https://stackoverflow.com/questions/33375588/row-number-partitioning-according-to-consecutive-rows

A: Si entendí lo que buscas, sería agrupar por UpdateDate y U_Entrega y obtener el valor mínimo de UpdateTS, algo así:
SELECT UpdateDate,
       U_Entrega,
       MIN(UpdateTS) as 'UpdateTS'
       FROM tu_tabla
       GROUP BY UpdateDate,
                U_Entrega


text:
Q: why i am getting force close when i want to exit? is there another code for exit the app?
i dont know why it doesnt working in here it worked for me all the time.
maybe its about my xml file i think its heavy or my code is need to be fixed.
here is my code
package ir.whitegate.guardians;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    addListenerOnButton();
    getActionBar().hide();

}

public void addListenerOnButton() {

    final Context context = this;

    button = (Button) findViewById(R.id.buttonstory);

    button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context, Story.class);
                startActivity(intent);

            }
            public void EXIT(View view)
            {
                finish();
            }
        });

}
}

and here is my xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@drawable/mainsithis">

<RelativeLayout
    android:layout_height="82dp"
    android:layout_width="match_parent">

    <HorizontalScrollView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="82dp"
            android:orientation="horizontal">

            <Button
                android:layout_height="82dp"
                android:layout_width="35dp"
                android:background="@drawable/toleft"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/bios"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/howtoread"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/about"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/writer"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/rateit"/>

            <Button
                android:layout_height="match_parent"
                android:layout_width="82dp"
                android:background="@drawable/moreapps"/>

            <Button
                android:layout_height="82dp"
                android:layout_width="35dp"
                android:background="@drawable/toright"/>

        </LinearLayout>

    </HorizontalScrollView>

</RelativeLayout>

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_weight="0.25"
    android:background="@drawable/rainbow"/>

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_weight="0.80">

    <Button
        android:id="@+id/buttonstory"
        android:layout_height="65dp"
        android:layout_width="wrap_content"
        android:background="@drawable/starttoread"
        android:layout_weight="1.0"/>

    <Button
        android:layout_height="65dp"
        android:layout_width="wrap_content"
        android:background="@drawable/exit"
        android:layout_weight="1.0"
        android:onClick="EXIT"/>

</LinearLayout>

A: You should move EXIT method to class from button clicklistener.
Change addListenerOnButton method like below method
public void addListenerOnButton() {

final Context context = this;

button = (Button) findViewById(R.id.buttonstory);

button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, Story.class);
            startActivity(intent);

        }

    });

}

public void EXIT(View view)
        {
            finish();
        }

A: change
Intent intent = new Intent(context, Story.class);

to
Intent intent = new Intent(MainActivity.this, Story.class);
wrong parameter context
Move this to buttonStory
android:onClick="EXIT"
and add the code to MainActivity.
public void EXIT(View view)
        {
            finish();
        }


text:
Q: How to save combobox data into SQL Server 2012 database? I tried this code, and without combobox it's working.
After adding combobox(comboBloodGroup) with 8 selected items and data type selected is nvchar(50), I get an error
How to code to insert combobox data into sql database.
My new code is
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string strConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\MYPC\DOCUMENTS\LOGIN.MDF";
            SqlConnection cn = new SqlConnection(strConnectionString);
            cn.Open();
            int iId = Convert.ToInt32(txtId.Text.Trim());
            string strFName = txtFName.Text.Trim();
            string strLName = txtLName.Text.Trim();
            int iAge = Convert.ToInt32(txtAge.Text.Trim());
            string stremail = txtemail.Text.Trim();
            string strMobile = txtMobile.Text.Trim();
            string strAddress = txtAddress.Text.Trim();
            string strCity = txtCity.Text.Trim();
            int iPinCode = Convert.ToInt32(txtPinCode.Text.Trim());
            string strGender;
            if (rbMale.Checked)
                strGender = "Male";
            else
                strGender = "Female";
            string strBloodGroup = comboBloodGroup.SelectedItem.ToString();
            DateTime dtDOB = dtPickerDOB.Value;
            string query = "INSERT INTO information(Id, FName, LName, Age, email, Mobile, Address, City, PinCode, Gender, BloodGroup, DOB)VALUES(@iId, @strFName, @strLName, @iAge, @stremail,@strMobile, @strAddress, @strCity, @iPinCode, @strGender, @strBloodGrourp, @dtDOB)";
            SqlCommand InsertCommand = new SqlCommand(query, cn);
            InsertCommand.Connection = cn;
            InsertCommand.Parameters.AddWithValue("@iId", iId);
            InsertCommand.Parameters.AddWithValue("@strFName", strFName);
            InsertCommand.Parameters.AddWithValue("@strLName", strLName);
            InsertCommand.Parameters.AddWithValue("@iAge", iAge);
            InsertCommand.Parameters.AddWithValue("@stremail", stremail);
            InsertCommand.Parameters.AddWithValue("@strMobile", strMobile);
            InsertCommand.Parameters.AddWithValue("@strAddress", strAddress);
            InsertCommand.Parameters.AddWithValue("@strCity", strCity);
            InsertCommand.Parameters.AddWithValue("@iPinCode", iPinCode);
            InsertCommand.Parameters.AddWithValue("@strGender", strGender);
            InsertCommand.Parameters.AddWithValue("@strBloodGroup", strBloodGroup);
            InsertCommand.Parameters.AddWithValue("@dtDOB", dtDOB);
            InsertCommand.ExecuteNonQuery();
            MessageBox.Show("New Patient's Data has been added successfully");
            cn.Close();
        }
        catch (Exception ex)
        {
           MessageBox.Show(ex.Message);
        }
    }

A: You mistyped @strBloodGrourp in query. Change to @strBloodGroup.
string query = "INSERT INTO information(Id, FName, LName, Age, email, Mobile, Address, City, PinCode, Gender, BloodGroup, DOB)VALUES(@iId, @strFName, @strLName, @iAge, @stremail,@strMobile, @strAddress, @strCity, @iPinCode, @strGender, **@strBloodGrourp**, @dtDOB)";

And you add parameter @strBloodGroup

A: Your parameter name you defined in your command and your AddWithValue doesn't match. You defined it as strBloodGrourp in your command but you declared it strBloodGroup in your AddWithValue.
Change your parameter name in your command as;
@strGender, @strBloodGroup, @dtDOB

A few things more;

*

*Use using statement to dispose your connection and command automatically instead of calling Close method manually.

*Don't use AddWithValue method. It may generate unexpected and surprising results sometimes. Use Add method overloads to specify your parameter type and it's size.

using(var cn = new SqlConnection(strConnectionString))
using(var InsertCommand = cn.CreateCommand())
{
    // Set your CommandText property with parameter names.
    // Define your parameter names and it's values. Add them to your command.
    // Open your connection.
    // Execute your query.
}

A: You have a typo
string query = "INSERT INTO information(Id, FName, LName, Age, email, Mobile, Address, City, PinCode, Gender, BloodGroup, DOB)VALUES(@iId, @strFName, @strLName, @iAge, @stremail,@strMobile, @strAddress, @strCity, @iPinCode, @strGender, @strBloodGrourp, @dtDOB)";
Should read
string query = "INSERT INTO information(Id, FName, LName, Age, email, Mobile, Address, City, PinCode, Gender, BloodGroup, DOB)VALUES(@iId, @strFName, @strLName, @iAge, @stremail,@strMobile, @strAddress, @strCity, @iPinCode, @strGender, @strBloodGroup, @dtDOB)";
You had an extra R in bloodgroup


text:
Q: Semilogy interpolation; get x from y I have the following data:
x = [0, 2, 4, 8, 30]
y = [1.2e-3, 3.5e-4, 5.1e-5, 1.6e-5, 2e-7]

I'm trying to interpolate to get y from a given x value.
When plotted the data looks like:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.semilogy(x, y, 'o-')
plt.show()

So say I'm interested in finding what value of x is for a y value of 3e-5.
I can get the x value of a given y by:
z = np.linspace(0, 30, 10000)
logy = np.log10(y)
yy = np.power(10.0, np.interp(z, x, logy))
z[np.isclose(3.5e-5, yy, atol=1e-8)]

Out:
array([5.29852985])

But I have to adjust the atol if I change the value to get a single match and also have to create a load more data points to get the resolution.
Is there a simpler way to do this? Thanks.

A: Let's say you want to find the x_f corresponding to y_f. Assuming the entries in your original list y are in strictly decreasing order and the entries in x are increasing, you find the first entry in y that is less than or equal to your y_0. Say it is the one at index i, so the x,y tuples that make up your the relevant linear function from your piecewise partition will be (x[i-1],y[i-1]) and (x[i], y[i]).
Using the formula for the line given two points on the line we can get x_f:
x_f = x[i-1] + (x[i]-x[i-1])/(y[i]-y[i-1])*(y_f-y[i-1])


text:
Q: What does "back east" mean? How do I go back east if I've never been to the east? It does not make sense to return to a place you've never been.

A: In American English, we sometimes say up north, down south, out west, and back east when referring to directions. The words up, down, out, and back do not have any special meaning in this context, but are often used as a matter of convention. Additionally, the Eastern United States is sometimes referred to as back east.
According to this Ngram, it appears that this usage became more common in the latter half of the 19th century, began to decline between 1940 and 1970, and then became more widely used than before:

A: "Back east" is a west coast-ism to refer to the east coast, as a corollary to "out west". See e.g. http://www.wordorigins.org/index.php/forums/viewthread/1898/
The underlying source is the idea everyone is somehow "from" the east, and they (or their ancestors) at one point moved "out west", but if they were to return, it would be to go "back east."

A: Most of the settlement of the United States was done by people moving from east to west.  For example, the original 13 states in the United States were along the Atlantic coast.
Yes, the Spanish also colonized Florida, Texas, New Mexico, and California, and the French colonized Louisiana -- but those are exceptions that prove the rule.  In 1803 (when the U.S. purchased Louisiana), the Louisiana Purchase was of territory adjacent to and west of the United States.  In the 1830s, American settlers moving west from Tennessee greatly outnumbered the Spanish-speaking colonists in Texas.  In 1849, a "Gold Rush" of American "49ers" moving west similarly overwhelmed the Spanish-organized Indians around the California missions.
Most of the people who moved west during the settlement of the United States moved to areas where North literally is upstream from South.  Most of the United States is in a huge basin, bounded by the Appalachian mountains in the east, the Great Lakes in the northeast, (roughly) the Canadian border, the Rocky Mountains in the west, and the Gulf of Mexico in the south.  With a few exceptions, most rivers in this region flow southwest, south, or southeast.  In this basin, "downstream" is toward the Gulf of Mexico (that is, toward the "South").

A: Sometimes "back X" can refer to a cultural or family home, even if one has never been there.

I'd love to go back to Africa

The implication is that one's culture, or "roots" are in Africa.  However, this is still ambiguous as the speaker might quite rightly assume that the speaker had been there before.

A: There has been some similar answers to this one. I'm not an expert, I'm not even american, but if you watch this video historian Colin Calloway gives some insight as of why this might be such a common term.
Link to video: http://www.choices.edu/resources/scholarsonline/calloway/cc6.php

A: I'm from the Enumclaw, WA.  To my cohorts and me, "back east" basically refers to anything north of the Carolinas and east of Indiana or Ohio-ish.  It does not reference people who used to live on the east coast.  It's a loose geographical reference.  East of the midwest and north of the south is the most common usage, but I have heard people refer to places like Chicago as back east. However, in my humble opinion that would be incorrect usage.


text:
Q: Laravel 5: Controller Testing - PHPUnit returns green the following simple controller test makes a 'GET' request to the PostsController@index action:
<?php

class PostsControllerTest extends TestCase {

    public function testIndex()
    {
        $response = $this->action('GET', 'PostsController@index');

    }
}

In my understanding, if the index method does not exist in my controller, I shouldn't get the green light, when calling phpunit in my command line.
Yet my controller looks like this:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    // public function index()
    // {
    //    //
    //    return 'Posts Index';
    //}
}

As you can clearly see the index method is commented out and I still get this:
**OK (1 test, 0 assertions)**

Any suggestions?

A: You aren't making any assertions. Your test isn't checking if $response is "OK".
Change your test to this:
public function testIndex()
{
    $response = $this->action('GET', 'PostsController@index');
    $this->assertEquals(200, $response->status());
}

This test asserts that the page responded with a 200 status code, which means it was successful.
You can read up on Laravel's testing here.


text:
Q: Encoding issues while writing BigQuery results to GCS in CSV format using Apache Beam I have followed this post
Write BigQuery results to GCS in CSV format using Apache Beam
And have created a code to write BigQuery results to GCS in CSV format using Apache Beam.
My code is as below
from __future__ import absolute_import
import apache_beam as beam
import argparse
import pickle
import logging
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.io.gcp.internal.clients import bigquery
from datetime import date
today = date.today()
current_date = today.strftime("%Y%m%d")
def createFile(argv=None):
    parser = argparse.ArgumentParser()
    known_args, pipeline_args = parser.parse_known_args(argv)
    p = beam.Pipeline(options=PipelineOptions(pipeline_args))
    (p | 'ReadTable' >> beam.io.Read(beam.io.BigQuerySource(query="SELECT CUST_ROLE,CUST_ROLE_TXT,CUST_C4C_CUSTID,CUST_FNAME,CUST_LNAME,CUST_EMAIL,CUST_MOBILE,DL_BILL_TO_ADD,DL_SHIP_TO_ADD,CUST_STATE,CUST_GENDER_TXT,CUST_LOCALITY,CUST_GROUP,CUST_GROUP_TXT,CUST_DOB,CUST_SHIP_TO_EMAIL,CUST_CITY,CUST_WEDDING_ANNIVERSARY,CUST_PINCODE,CUST_UUID,CUST_ENTITY_ID,CONSENT_EMAIL,CONSENT_WHATSAPP,CONSENT_MOBILE FROM `whr-asia-datalake-nonprod.WHR_DATALAKE.CONSUMER_EXTRACT`",use_standard_sql=True))
       | 'read values' >> beam.Map(lambda x: x.values())
       | 'CSV format' >> beam.Map(lambda row:'|'.join(['"'+ str(column) +'"' for column in row]))
       | 'Write_to_GCS' >> beam.io.WriteToText('gs://whr-asia-datalake-dev-standard/outbound/Adobe/Customer_Master'+''+ str(current_date),file_name_suffix='.csv',header='CUST_ROLE|CUST_ROLE_TXT|CUST_C4C_CUSTID|CUST_FNAME|CUST_LNAME|CUST_EMAIL|CUST_MOBILE|DL_BILL_TO_ADD|DL_SHIP_TO_ADD|CUST_STATE|CUST_GENDER_TXT|CUST_LOCALITY|CUST_GROUP|CUST_GROUP_TXT|CUST_DOB|CUST_SHIP_TO_EMAIL|CUST_CITY|CUST_WEDDING_ANNIVERSARY|CUST_PINCODE|CUST_UUID|CUST_ENTITY_ID|CONSENT_EMAIL|CONSENT_WHATSAPP|CONSENT_MOBILE'))
    p.run().wait_until_finish()
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.INFO)
    createFile()

My code works fine and creates a csv file when tested for few records. However, when running for huge data , I get below error
/home/radhika_sharma_ibm/Consumer_Extract.py", line 20, in  RuntimeError: UnicodeEncodeError: 'ascii' codec can't encode character u'\xc3' in position 8: ordinal not in range(128) [while running 'CSV format']
Can anyone please tell me how to apply encoding while doing 'read values'.
I have tried adding below and have assigned the class in write but the issue is in CSV FORMAT.
from apache_beam.coders.coders import Coder
class CustomCoder(Coder):
"""A custom coder used for reading and writing strings as UTF-8."""
def encode(self, value):
    return value.encode("utf-8", "replace")

def decode(self, value):
    return value.decode("utf-8", "ignore")

def is_deterministic(self):
    return True

Any suggestions please. I am really struggling with this.
I have also tried using below in read values and csv format, I get a different issue provided below
   | 'read values' >> beam.Map(lambda x: x.values(),encoding='utf-8')
   | 'CSV format' >> beam.Map(lambda row:'|'.join(['"'+ str(column) +'"' for column in row]),encoding='utf-8')

return self.do_fn_invoker.invoke_process(windowed_value)
  File "apache_beam/runners/common.py", line 742, in apache_beam.runners.common.PerWindowInvoker.invoke_process
    self._invoke_process_per_window(
  File "apache_beam/runners/common.py", line 862, in apache_beam.runners.common.PerWindowInvoker._invoke_process_per_window
    self.process_method(*args_for_process, **kwargs_for_process),
TypeError: <lambda>() got an unexpected keyword argument 'encoding' [while running 'read values']


text:
Q: Vue.js ailed to resolve component: b-button I want to make a modal using bootstrap in vue.js.
I got the warning error

'[Vue warn]: Failed to resolve component: b-button' and here is my code

<template>

    Open Modal
    Toggle Modal

Hello From My Modal!

      Close Me
      Toggle Me

</template>

i try to solve my problem by looking for the answer from their website bootstrap-vue.org but still it did not work on my project.


text:
Q: Running a Java Application from the Windows Context Menu I would like to create a Java application that can be opened from the context menu of any given file or directory on the computer. I know how to add my program to the registry so that it appears when right-clicking on a file, but how can I receive the location of the directory/file from which my program was run in order to work with it inside the application?
Is there a way that I can receive it as an argument in the main?

A: First convert your jar to exe file.
then you add to registry and whatever..
if you set whenever you open with right click on file ( you must set the file association, that is your application. Ex: Right click on your targeted file select open with and select your application  ) your application main function receive the path in args[0]. that's all...

A: Add the context menu. Tell it to run CMD. Tell CMD to run the jar (and then close).
HKEY_CLASSES_ROOT\ * \shell\ClickMe\Command
default="cmd \\c java c:\myJar.jar \"%1\""


text:
Q: "DisplayName" subkey value showing up blank I made a console application to retrieve the "DisplayName" values of all the registryKeys (RegistryKey.GetValue("DisplayName") of applications installed on my machine.
I took that method, which was successful, and have implemented it in a program using the Autodesk Revit API. The problem is, the specific application's DisplayName that I am looking for does not show up, or it is a blank string. This did not happen before in my simple console application. I need this because I need to be able to grab the installation path.
Does anyone have an answer as to why the same method does not display the "DisplayName" value consistently in both my console application and in Autodesk Revit? Many DisplayName values do show up, but some apparently do not.


text:
Q: How to convert python socket stream string value to float? I'm starting to use sockets to send a file. I learned I can send in 1024 "chunks" through the socket stream, and piece it back on the server side. I set the server to first get a string containing the size of the file it will receive, and as it reads to compare to see if the read is finished or not.
Client code is:
BUFFER_SIZE = 1024
limit = os.path.getsize("test.db") #4096 bytes
currentamt = BUFFER_SIZE
f = open("test.db", "rb")
l = f.read(BUFFER_SIZE)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(str(limit)) #first, send the limit
while(1):
  s.send(l)
  if currentamt >= limit:
    break
  l = f.read(BUFFER_SIZE)
  currentamt += BUFFER_SIZE
  print "still sending.."

s.close()
print "Done."

Server code is as such:
while True:
  conn, addr = s.accept()
  print "Connection address: ", addr
  f = open('rec.db', 'wb')
  while 1:
    limit = conn.recv(20) #this will get your limit size
    limit = limit.rstrip()
    limit = float(limit) #error in question
    print limit
    l = conn.recv(BUFFER_SIZE) #get byte bufferred back
    while (1):
      if currentamt >= limit:
        f.write(l)
        break
      f.write(l)
      l = conn.recv(BUFFER_SIZE)
      currentamt += BUFFER_SIZE
  f.close() #close your file after you're done
  conn.close()

s.close()

If I change limit in server from 20 to 10, I am able to convert to a float, but then I get an error after the print statement! Also, the print limit does work before the float(limit) statement, which confuses me.

A: TCP/IP guarantees that you get the right bytes in the right order.  It doesn't guarantee anything about the sizes of the chunks you receive.  IOW, if you send 1024 bytes, 1024 bytes, 1024 bytes - then there's nothing to prevent TCP from chopping that into 512 bytes, 512 bytes, 512 bytes, 512 bytes, 512 bytes, 512 bytes - or even stranger things.  It also reserves the right to aggregate chunks, to form 2048 bytes, 1024 bytes.
To get around this, it's important to put a loop around your sends and recvs, or to use something that makes it easier to bufsock or twisted.  Personally, I think twisted makes this easier but a lot of other things harder, but maybe that's just because I wrote bufsock.
Bufsock is at http://stromberg.dnsalias.org/~strombrg/bufsock.html
In your specific case, I see you sending a length in ASCII, but I don't see you sending any sort of termination character or padding to a field width.  That'll reap havoc in the other side of the connection, where it appears to be assuming the length is always 20 characters long.  To deal with this, you might:
s.send(str(limit) + '\n')

...but there's still the problem of missing loops.  Bufsock does the looping for you, you just have to remember to bufsock.flush() frequently (enough).


text:
Q: Is it normal for a MacBook Pro to get so hot that it's uncomfortable to type? I have a 15" unibody MacBook Pro that often gets so hot on the left side that it is uncomfortable to type. I just bought a cooling pad which has helped a lot, but I'm wondering if something is wrong with my computer?
Have we as computer users come to accept this kind of behavior from our portables?

A: Yes, this happened lots with my MacBook; the fans seem to have an unusually high temperature threshold until they kick in. It may be because since the case is solid aluminium, it conducts the heat away from the internal components, so is in itself much hotter than the actual inside components, leading to the fans not kicking in even though the body feels hot.
I downloaded Fan Control which allows you to change the fan speed, and has been working great and keeping it cool, although sometimes it can be a little too sensitive - it depends how you set it up.
Edit: the use of the unibody to transfer heat from the internals to the air outside is certainly true for the bottom of the MacBook, probably the top as well, so this again, is probably why it seems hotter than the actual components are:

The bottom of the MacBook case functions as a cooling surface that transfers heat from inside the computer to the cooler air outside.

A: While I don't have a MacBook Pro but merely a MacBook I got tired of mine being hot as well. One way of doing something about this is undervolting the CPU.
While it may sound like it, undervolting will NOT harm performance - it merely lowers the voltage to the CPU. An electric component needs a certain amount of voltage to function (and also it cannot be too much!) or it won't work properly - however not all CPUs (even within the same make and brand) are made equally and as such the minimum voltage under which they can function differs. Intel (and AMD too) sets a standard "bar" for which all their released CPUs MUST be able to function, however this is usually quite alot above what YOUR specific CPU needs. If you try undervolting too much your system will crash and reset the voltage settings, but no components will be damaged.
A software for the Mac that can be used to undervolt the CPU is Coolbook. Read the instructions carefully and you should be good going - and please notice that the software is not free, however it is dirt cheap. I used it to succesfully undervolt my CPU and it dropped about 10C - another benefit of this is that it actually means your CPU uses less power - ie your battery lasts longer.

A: No, it is NOT normal!
Open the case, and clean the ventilation grids. They get filled with a ton of dirt and prevent efficient cooling. It might even lead to failure of the fan if dirt clogs up too much.
By cleaning I managed to reduce the temperature from 90C to 70C!

A: Mac laptops getting uncomfortably hot is quite a common occurrence, however there are numerous things you can do to prevent it, including using a laptop cooling pad (which you already are doing), downloading a fan control program such as SMC fan control, clearing dust buildup inside your Mac, and avoiding and blocking Flash Content when possible.  Check out this page that is dedicated to just the sort of problems you're experiencing:  http://www.squidoo.com/how-to-prevent-your-mac-from-overheating
Good luck!

A: They have always done this to different degrees all the way back to my PowerBook 5300C.

A: I find it depends on whether something is keeping the CPU active or not.  For just browsing the web and light editing, it doesn't get very hot.  But if I've got a VirtualBox or Parallels session going, the CPU load goes up to a very steady 25%, and then it gets hot.

A: Yes, which is probably part of the reason why Apple has never called them "Laptops." My new unibody MacBook doesn't heat up as much but the Mac Pros would turn my thighs red.

A: Disclaimer: I don't own a MacBook.
This appears to be a known issue due to the laptop's design.

A: This has been a problem for ages when a computer comes with the warning, you can expect it to get hot.
"Do not leave the bottom of your MacBook Pro in contact with your lap or any surface of your body for extended periods. Prolonged contact with your body could cause discomfort and potentially a burn"


text:
Q: Automator Application as 'Login Items' to 'Connect to Servers' - Servers don't display in Finder Side Bar? Have an Automator Application as a 'Login Items' to 'Connect to Servers' (AFP).
On login it runs, connects the servers, but does not add them to the Finder Side Bar under 'Devices'.
Once logged in, I disconnect the servers manually, and then run the Application manually. The servers connect & are added to the Finder side bar! Same, unmodified Application.
Have tried to add a 'Pause' of a few seconds to the Automator Application at the start, but it still won't work.
This exact same Automator Application used to work in Snow Leopard without fail. Stopped working with the upgrade to Mountain Lion. Have opened & re-saved the Application using Automator on Mountain Lion as well.
Any suggestions?
Added (30-SEP-12) ...
Finder directly after login & Automator script has run.

Run Automator script manually.

Finder after running Automator script manually.

Also, just discovered something new. During login, if I quickly open Finder, while the script is starting/running, the mappings are created (!), but if I don't open Finder, let the script run, then the mappings are not created.
Added (01-OCT-12) ...
Workaround ... add a 'Get Specified Finder Items', and then an 'Open Finder Items' to open Finder before attempting to connect to the servers.


text:
Q: What is resources.ap_ and why does it have a penchant for not existing? Every once in a while a borked Eclipse build gets nailed down to the absence of this file, with the simple fix of cleaning the build, or occasionally doing a deeper clean on the project's metadata. I can live with this state of affairs, but the curious side of me has to ask why.
A search for it on developer.android.com turns up nothing :(, and a search on Google turns up various threads by folks wondering why their build is broken.
This guy is the closest thing I've found to an explanation of the thing itself. Hopefully some nice, patient guru can shed some light on the fundamentals here without this noob digging too far into the source :)

A: The resource.ap_ is all the resources for you file zipped up.  Everything from the res, assets folders and the Manifest file.
The apk file added in the class.dex (all your compiled code) and any linked .so (native code).
Both of these files are in .zip format.  They can easily be view by changing the extension to .zip and opening them.

A: The .ap_ file is probably your apk before it is signed with your certificate (by default, a debug certificate generated by ADT in your home directory.)

A: here is a picture which may give you the answer.


text:
Q: How to keep battery charge at 80% to increase its lifespan Lithium-based Batteries are not supposed to constantly sit a maximum charge. This damages them and reduces their lifespan. This is why some people take the battery out when using the laptop plugged in; but I don't want to do this, because then a power outage could cause data loss.
On the Samsung N150 netbook, there is a BIOS SETUP option to set the max battery charge level to 80%. Then you can leave the netbook plugged in, with the battery installed, and still preserve the battery's lifespan.
I want to do it with my HP G42-230BR laptop, which does not have such a BIOS SETUP option.
It should still be possible with software, right?
I have Googled and did not found how to do it:
https://www.google.com/search?q=ubuntu|linux+partial+charge|recharge+battery+life
Do you know how to do it?
Thank you very much for your attention

A: Slightly duplicate of How can I limit battery charging to 80% capacity?, but I won't mind. And for those that say the 80% thing is a myth, that's not what Jorge ask for; he wanted to know how to enable it, whether or not it's a myth...discuss that elsewhere.
If you don't have an option in your BIOS, it's difficult to impossible to override the hardware in your computer without the proprietary company that made your computer (HP) making a special script for you. Look for something like that, otherwise, it won't work.
Maybe look in your BIOS again. Maybe also (if you are daring enough), to update your BIOS. This is tricky, but I will not explain it here. That MIGHT allow you enable this setting. I still think that it would be in your BIOS if anywhere, check over it again. If you do update your BIOS, ensure it's a newer version, AND that it includes the "enable batter saver" option that you want (you may have to read the update notes (bleah!)).
Hope this helps! If it does, +1 me :).
Zzzach...

A: There is 80% charge and there is 80% charge.
Electronic equipment (cell phones, laptops, etc) require a certain minimum voltage to be able to function.  Simpler devices, like flash lights, can function down to near zero charge (albeit whether usable is another question)
When manufacturers state that a battery should not fall below 80%, they talk about the kind of depletion that you get when you use a battery till it is completely flat, eg due to a continuous drain, such as by flash light globe.
A cellphone, or laptop however would cut out long before this... probably even before a battery reaches this 80% limit.  This is due to the internal resistance of the battery going up, which causes a voltage drop under load.  If the battery is near enough to fully charged, e.g above a certain threshold, this voltage drop doesn't show up when using a simple meter to test battery charge, as these meters does not put enough load on the battery to cause the internal resistance to have a real effect.
Cell phones and such have "intelligent" managed batteries to be able to report to you how long you can still use the battery, e.g before it reach the threshold where the internal resistance causes the supplied voltage to go too low to be able to power the device.
So there are two measures of battery charge:

*

*That reported by the battery indicator on the cellphone is "time until battery reaches cut-off threshold"

*The actual amount of charge resident in the battery, regardless of whether it can be used by a specific device.

This complicates the whole situation:  How do you control the device to not use the battery below a certain threshold (Type 2 above), when that threshold is measured on a different scale compared to that reported by the battery level management circuitry (Type 1 above)
I'm quite sure there is no way to do this, but in all likeliness your device will never deplete the battery to below the 80% manufacturer safety margin, so this is not a real issue.


text:
Q: Where to place a central error handler for a Windows Forms project In ASP.NET I can use Application_Error within global.asax in order to handle any errors that have been unhandled.
Is there an equivalent in windows forms?

A: Yes its AppDomain.UnhandledException

using System;
using System.Security.Permissions;

public class Test {

   [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
   public static void Example()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

      try {
         throw new Exception("1");
      } catch (Exception e) {
         Console.WriteLine("Catch clause caught : " + e.Message);
      }

      throw new Exception("2");

      // Output:
      //   Catch clause caught : 1
      //   MyHandler caught : 2
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
   }

   public static void Main() {
      Example();
   }
}

A: [STAThread]
static void Main()
{
  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  Application.Run(new FrmMain());
}

private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
  MessageBox.Show("Unhandled exception: "+e.Exception.ToString());
}

A: It depend on the architecture of your app. For exemple, if you do MVC architecture then it should be in your controler.if you know Chain of responsability pattern[GOF] or if you prefer a big handler of all type of execption. Otherwise, you'll to tell us more about your app.


text:
Q: Generalized definitions of Lagrangian and Hamiltonian functions When we enter into the scope of Analytical mechanics we usually start with these two primary notions: Lagrangian function & Hamiltonian function
And usually textbooks define Lagrangian as $L=T-V$ and Hamiltonian as $H=T+V$ where $T$ is Kinetic energy and $V$ is Potential energy. But as we proceed it turns out Lagrangian and Hamiltonian may not always have these values and this occurs in just some special cases and there is a more general definition.
My question is:

*

*What is the generalized definitions of these two functions?

*Is there a general defining equation where the mentioned values could be extracted as a special case?
EDIT: A third question
Do we know about the notions of "Kinetic energy" and "Potential energy" beforehand or are they defined after the Lagrangian gets its famous form $L=T-V$ and then we assign $T$ and $V$ their respective definitions?
EDIT 2: A fourth question
What if there were non-conservative fields? Then obviously $V$ term couldn't show their effects(since Potentials are always associated with conservative fields). Then how could we bring the effects of non-conservative fields into play?

A: *

*This is a huge topic. How general do you want to be? We will only be schematic here. Perhaps the most general setting is a physical system with a set of equations of motion. (The word equations of motion refer to a coupled set of differential equations that governs time evolution. E.g. in Newtonian mechanics, it's Newton's 2nd law.)

*There are no general algorithms to determine whether a variational formulation exists or not, cf. e.g. this Phys.SE post. In other words, finding a variational formulation is in general an art.

*Generically, there does not exist a variational formulation for dissipative and non-conservative systems. However, see e.g. this and this Phys.SE posts. For a discussion of the non-conservative forces, see also this Phys.SE post.

*The Lagrangian $L$ need not be of the form $T-U$, cf. e.g. this Phys.SE post. Of course, classes of physical systems do obey $L=T-U$, cf. e.g. this Phys.SE post.

*Next assume that a Lagrangian $L$ is given. To find the Hamiltonian $H$, perform a (possibly singular) Legendre transformation between the generalized velocity and momentum variables. (If the Lagrangian depends on higher time derivatives, cf. e.g. this Phys.SE post, see the Ostrogradsky formalism.)

*For the condition when the Hamiltonian $H$ & the total energy $E$ agree, see e.g. this & this Phys.SE posts & links therein.

*For books on Lagrangian & Hamiltonian formulations, see e.g. this & this resource recommendation lists & links therein.

A: In general - No there is not. In the corresponding formalism, the Lagrange or the Hamilton-function will be the starting point to describe the system, and that means that you have to shape the Lagrange function in a suitable way to describe the system. There are no other properties of the system at that point, that have allready been translated into a mathematical object (Like the kinetic Energy, or the Potential energy), you start with the Lagrange function, and in a suitable system you can afterwards identify terms within the Lagrange-function with $V$ or with $T$.
However, choosing a Lagrange-function is not entirely abitrary: Your Lagrange function $L(\vec{x}, \dot{\vec{x}})$ is supposed to describe your system. That means for example, that $L$ has the same symmetries as you observe at your system.
For example, consider the free space: Every region is the same to a flying particle, the laws of physics are the same everywhere. That means your have translational invariance, and hence $L(\vec{x} + \vec{p}, \dot{\vec{x}})=L(\vec{x}, \dot{\vec{x}}) $, for every $\vec{p}$ you can think of. That means $L$ doesn't depend on x. Do the same with Rotational invariance, then you know L can just depend on $|\dot{\vec{x}}|$.
By now L has the form
$$
L= c f(|\dot{\vec{x}}|)
$$
If you demand that every inertial frame of reference will yield the same equations of motion (galileian invariance), then you demand that $$L(\dot{\vec{x}}) = L(\dot{\vec{x}}+\vec{v}) + D(\dot{\vec{x}}) \\
D(\vec{x},\dot{\vec{x}}) = \nabla g(x)\dot{\vec{x}}$$
This is a less rigid condition, the Term $D$ is a gauge-term and doesn't change the equations of motion. One way to satisfy this condition is to choose:
$$
L= c \dot{\vec{x}^2}
$$
Then
$$
L(\dot{\vec{x}}+\vec{v}) = c \dot{\vec{x}^2} + c \vec{v}^2 + 2 c \vec{v} \dot{\vec{x}} = \tilde{L}(\dot{\vec{x}})
$$
$L$ and $\tilde{L}$ will lead to the same equations of motion in two different frames of reference (as you demanded it). L is now shaped in a way that regards homogenity of time, of space, isotropy of space, and free choice of your frame of reference to be symmetries of the system. Now look at the outcome:$$
L= c \dot{\vec{x}^2}
$$
Up to constants (which will come in to play when you define units), you have the kinetic Energy, and you know this function to correctly describe the motion of a free particle. But you did't know in the first place, that there is something like newtons axioms, or something like energy. Everything you knew where the symmetries, and using them, you arrived at this point. In the same way you can demand gauge invariance, then you will arrive at the electromagnetic coupling terms in the Lagrange-function, and so on.


text:
Q: Why are these records written to the database in seemingly random order? I have a method which creates a list of weekdays, based on two form variables, NumOfDays and FirstDay and writes it to the database. If I create periods of 16 or fewer days, the days are all written to the database in perfect order, but if I try to create a period of 17 or more days, the order is seemingly random.
Here is my method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(int NumOfDays, int FirstDay,
    [Bind("BranchId,Title")] SchedulePeriod schedulePeriod)
{
    if (ModelState.IsValid)
    {
        SchedulePeriodViewModel vm = auto.Map<SchedulePeriodViewModel>(schedulePeriod);
        vm.NumOfDays = NumOfDays;
        vm.FirstDay = FirstDay;
        SchedulePeriodValidator validator = new SchedulePeriodValidator();
        ValidationResult result = validator.Validate(vm);
        if (result.IsValid)
        {
            List<ScheduleDay> days = new List<ScheduleDay>();
            string[] dayNames = { "Monday", "Tuesday", "Wednesday",
                "Thursday", "Friday", "Saturday", "Sunday" };
            for (int i = 0; i < vm.NumOfDays; i++)
            {
                days.Add(new ScheduleDay { Title = dayNames[(vm.FirstDay + i) % 7]} );
            }
            schedulePeriod.ScheduleDays = days;
            db.Add(schedulePeriod);
            await db.SaveChangesAsync();
            return RedirectToAction("Details", "SchedulePeriods",
                new { id = schedulePeriod.Id });
        }
        else
        {
            // handle invalid validation result
        }
    }
    return View(auto.Map<SchedulePeriodViewModel>(schedulePeriod));
}

Here are the models for the periods:
public class SchedulePeriod
{
    public int Id { get; set; }
    public int BranchId { get; set; }
    public string Title { get; set; }

    public List<ScheduleDay> ScheduleDays { get; set; }
    public Branch Branch { get; set; }
}

public class ScheduleDay
{
    public int Id { get; set; }
    public int SchedulePeriodId { get; set; }
    public string Title { get; set; }

    public List<ScheduleShift> ScheduleShifts { get; set; }
    public SchedulePeriod SchedulePeriod { get; set; }
}

Why is it working as expected for periods of up to 16 days, but failing consistently at 17 or more?

A: In relational database concept and MS SQL as well there is no ordering of rows/tuples in a table/relation. So you shouldn't rely on it. To achieve an ordering you need to use a field for this and then use it in ORDER BY when querying.
From Wikipedia article for relation:

Under the definition of body, the tuples of a body do not appear in any particular order.


text:
Q: Change the optional arguments in the interval package A half-open interval can be typeset using \interval[open left]{a}{b} from the interval package. But the option open left is very long. Is it possible to use a contraction such as \interval[ol]{a}{b}?

A: Sure!
\documentclass{article}
\usepackage{interval}

\intervalconfig{
  ol/.style={open left},
}

\begin{document}

$\interval[ol]{a}{b}$

$\interval[open left]{a}{b}$

\end{document}

A: Yes, but it is easier not exactly as you are suggesting:
\def\iol{\interval[open left]} with usage \iol{a}{b}.
Certainly, the name you will use should be easy for you, but \iol seems to be the shortest, easy to remeber one.


text:
Q: Using data sent via AJAX in multiple functions on a WP plugin This might be a scope issue but I want to cover all bases. I am successfully sending a value, distance, to an Ajax handler function. Here is the JS:
    $.ajax({
    type: 'POST',
    url: url,
    data: {
        'action':'example_ajax_request',
        'distance' : distance
    },
    success:function(response) {
        // This outputs the result of the ajax request
        console.log(response);
    },
    error: function(errorThrown){
        console.log(errorThrown);
    }
});

I have access to the distance variable in the backend:
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

// Dynamic field population

function example_ajax_request() {

    // The $_REQUEST contains all the data sent via ajax
    if ( isset($_POST) ) {

        $distance = $_POST['distance'];
        // echo $distance;

    }

   die();
}

$distance contains the value and I can echo it successfully. But I need to use this value in another function that hooks into gravity forms. I need to dynamically set a gravity forms value (using their  gform_field_value_$parameter_name hook). Problem is that I cannot figure out a way to access the $_POST['distance'] value outside of the Ajax function and the Gravity Forms hook fires before the $_POST['distance'] is available (my guess).
Is there a way to access the Ajax sent $_POST object outside of the handler function in WP? Am I looking at this all wrong? Any suggestions on how I can use that value to dynamically populate a Gravity Forms field?
Thanks in advance.
UPDATE:
I'm trying to set the GF value in the backend if possible, not using the Ajax response (using jQuery)

A: As I understand your question, you want to Update a GF field with the results ($distance) of an AJAX request.
If that is correct, on a successful AJAX request, you just need to update the value of your GF field.
Assuming your response is the actual value correctly formatted. here's what you need to do.
$.ajax({
  type: 'POST',
  url: url,
  data: {
    'action':'example_ajax_request',
    'distance' : distance
  },
  success:function(response) {
    // This outputs the result of the ajax request
    console.log(response);
    $('#your-GF-ID').val( response ); // This is where you update your GF field
  },
  error: function(errorThrown){
    console.log(errorThrown);
  }
});


text:
Q: Selectively correcting LFs to CRLFs Given:

*

*a large directory tree containing a mixture of:

*

*files with LF line endings

*files with CRLF line endings

*files with a weird mix of both LF and CRLF line endings (due to a bug)

*binary files

*other files that I don't want to touch even if broken

*paths that might contain spaces

My goal was to leave the LF-only and CRLF-only files alone, and convert the hybrid files to CRLF-only files, while leaving the final two groups alone as well.
This incantation works:
find . (some conditions to exclude stuff I don't want to mess with) |
    xargs -d '\n' unix2dos -ic | cut -c 3- |
    xargs -d '\n' dos2unix -ic | cut -c 3- |
    xargs -d '\n' unix2dos

But now I'm curious whether there is a better / more efficient way to do it.  (Using only standard shell tools, not Perl/Python/etc.)
FWIW, the first unix2dos -ic is to filter the initial list to just those files containing CRLF, then dos2unix -ic subfilters to those also containing LF, and the final one actually does the conversion.  The cut calls are to trim off the two leading spaces that confuse xargs, and the -d is to resolve issues with spaces in the filenames, since the output isn't quoted.


text:
Q: Are there irreducible representations of the crystallographic groups This yields the list of the irreducible representations of the point crystallographic group Oh:
FiniteGroupData[{"CrystallographicPointGroup",32}, "RepresentationNames"]

yielding the following:

My question:  is there a way to get these representations as matrices?
Disclaimer: I am aware of this and this answers. In those answers, however, one builds the whole group from scratch, and then only makes the irreducible representations. My point is if there are the corresponding matrices already available?


text:
Q: Jest with special tests run on occasion How do I write Jest tests that only runs when specifically invoked on the command line?
I want to have integration-like tests that interact with online services from Google and Amazon in a React project.

If I create a differently named test file src/google.itest.js:

*

*Good: It is not normally run by jest

*Good: It resides where all other tests are

*Bad: jest cannot be made to run it:

jest --testPathPattern="\.itest"
Jest still does not run the tests, probably because it is blocked by the testMatch configuration option:
testMatch:
**/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x)
How do I write Jest tests that only runs when specifically invoked on the command line?

A: It works with RegExp (presumably those are ECMAScript regexps):
jest --testRegex 'src/.*itest.*'
Note that an equal sign separating the long option and its value is not required


text:
Q: How do I install a Livebox USB printer as network printer? I hope someone has figured this out because I've spent days with google trying to track down the solution.
I got fed up with microsoft Win XP and 7 and decided to try ubuntu 12.04 on a spare laptop (Dell E6400).  Everything was going fine - I got it connected to my Livebox router using wifi, I could see and access the external hard drive connected to the Livebox USB and I could connect a Canon Pixma iP5000 usb printer locally to the computer.
The wheels came off when I tried to connect ubuntu 12.04 LTS computer to the printer (Canon Pixma iP5000) which is now connected to the USB on the Livebox.  I have not had any problems connecting to this networked printer using a Win XP machine over the wifi.
I tried 3 ways to use the add printer over the network using the tool in Ubuntu 12.04 LTS:

*

*Find Network Printer

*

*I searched for the printer (192.168.1.1 - the livebox IP address) and the tool quickly found "My Gateway Printer" which it connected as ipp://192.168.1.1:631/printers/gateway-usb-printer.

*I used the driver finder to install Canon PIXMA iP5000-CUPS+Gutenprint V5.2.8-pre1.  This is the same driver that works when the printer is attached to the computer via USB connection.

*When I tried to print a test page, I get an indication Idle - Printing page 1, 20%
I investigated using CUPS tool in Firefox.  The CUPS 1.5.3 tool shows an error message: aborted unable to add document to print job.

*App Socket/HP Jet Direct

*

*I entered host 192.168.1.1 port 9100.  The tool sets up a connection socket:/192.168.1.1:9100 and uses the same print driver in (1) above.

When I print a test page, I get a message processing - the printer is busy.  Nothing ever happens.

*Windows Printer via SAMBA
The tool creates a connection "smb:///192.168.1.1%3A631" and I again use the same printer driver in (1) above.
When I print a test page, I get a message Processing - unable to connect to CIFS host, will retry in 60 seconds.  The CUPS tool indicates Connection failed: NT_STATUS_BAD_NETWORK_NAME.
Can someone help me figure out what is going wrong here?  I'd love to get this printer working over the network as the the basis of my project is to create ubuntu driven laptop that I can use to print and share files with my other computers over the livebox wifi network.
I'd appreciate specific instructions to get the printer (connected by USB to a Livebox wifi router) to connect over the wifi network to my laptop.
Thanks!


text:
Q: Prevent css and js inheritence in ascx I have an application with only one aspx page (Default.aspx).
This page loads .ascx controls as needed.
All these controls are using the same JS and CSS file.
Now I want to apply Bootstrap on some of them.  But I am scared that bootstrap will break some CSS and JS.
So I am thinking about wrapping each control in an Iframe (because what I know is:
Iframe blocks inheritance of CSS and JS).
Is my solution ok ?
Or Is there a way to know which CSS and JS is needed by each control?
thanks

A: My advice is that even if you're breaking your application markup into controls (ascx files), you should apply a consistent theme and serve just one bundle of CSS and one bundle of JS. This will help performance of your site as well as be easier to maintain.  Also, it'll be easier to keep a consistent look and feel for your users.
So if you're going to use Bootstrap, use it everywhere.  Write your JS functions such that they aren't dependent on a given markup, and so on.


text:
Q: Invalid value for redirectUrl following active-directory-v2-devquickstarts-node-web Using https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-devquickstarts-node-web I get this error:
TypeError: Invalid value for redirectUrl.The URL must be valid and be https://
My config.js contains redirectUrl: 'http://localhost:3000/'
Using https://developer.microsoft.com/en-us/graph/quick-start it works.
Any idea?

A: allowHttpForRedirectUrl: true, // For development only
set this in your config.js file


text:
Q: SQL query - Select with SUM function with limit
I'm trying to make a query to list PTR_NUM who have at total PTNG_PRICE above 7000. I'm trying to do this:
SELECT painter.PTR_FIRSTNAME, painter.PTR_LASTNAME,
SUM(painting.PTNG_PRICE) AS 'TOTAL PAINTING COST'
FROM painter, painting
WHERE painter.PTR_NUM = painting.PTR_NUM
AND SUM(painting.PTNG_PRICE) > 7000
GROUP BY painter.PTR_NUM;

I'm getting a 1111 error.

A: SELECT painter.PTR_FIRSTNAME, painter.PTR_LASTNAME,
SUM(painting.PTNG_PRICE) AS 'TOTAL PAINTING COST'
FROM painter, painting
WHERE painter.PTR_NUM = painting.PTR_NUM
GROUP BY painter.PTR_NUM
HAVING SUM(painting.PTNG_PRICE) > 7000;


text:
Q: css selector for table with scroll I have a table in html page,
it can contain some or many records, I want to apply specific css to the table, only when there is a scroll on the table, when there are some records and there is no scroll I don't want this css definition to affect the table.
How can I do it?
table **here I need the selector** thead {
     width: calc( 100% - .5em )/* scrollbar is average 1em/16px width,
      remove it from thead width */
}

A: use ViewChild ref to the table and check if scroll is visible in ngClass if scroll is exist then the class will be added to the table :
<table #table [ngClass]="{'visibleScroll': table.scrollHeight > table.clientHeight }"></table>

then add your class in css style sheet:
.visibleScroll{
//your style css
}


text:
Q: Spring Security 3 - Add information to (role) voters I am pretty new to Spring security and just going through the reference, doing some examples. One feature that I am strongly missing (and I wonder that hardly anybody else seems to miss it) is to provide custom information to the user why or for what reason access was denied. E.g. I would like to inform the user that he has no access to module A or that he needs to needs to be granted role-access B, etc.
I took at a look at the role interface, but this information seems to get lost:
int vote(Authentication authentication, Object object, List<ConfigAttribute> config);

Spring Security Access Denied logging with missing role
This says, that I have to provide a custom implementation of AccessDecisionManager.
But how could an actual implementation look like which provides specific information if access is denied? And how to hook it into spring security?
For starters simple role-based access would be sufficient. Can anybody provide any examples on this?

A: Have a look at the AffirmativeBased - DecisionManager. You can enhance it an add some additional information to the AccessDeniedException.
But it seams to be not so easy to get the reasons from the Voters why they dendied the access. (I hope you will find some naming pattern, or you have even to extend the voters).
And this is an example how to configure your custom DecisionManager
 <security:http auto-config="true" access-decision-manager-ref="myDecisionManager">

 <bean id="myAccessDecisionManager"
    class="MyAffirmativeBasedDecisionManager">
    <constructor-arg name="decisionVoters">
        <list>
            <ref bean="roleVoter" />
            <ref bean="authenticatedVoter" />
            <ref bean="preAdviceVoter" />
        </list>
    </constructor-arg>
</bean>

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter" />

<bean id="authenticatedVoter"
    class="org.springframework.security.access.vote.AuthenticatedVoter" />

<bean id="preAdviceVoter"
    class="org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter">
    <constructor-arg ref="exprPreInvocationAdvice" />
</bean>

    <bean
    class="org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice"
    id="exprPreInvocationAdvice">
    <property name="expressionHandler" ref="methodExprHandler" />
</bean>

<bean id="methodExprHandler"
    class="org.springframework.security.access.expression.method.ExtensibleMethodSecurityExpressionHandler">
    <property name="methodSecurityExpressionRootFactory">
            <bean
            class="com.queomedia.infrastructure.security.spring.MethodSecurityExpressionRootFactoryImpl" />
    </property>
</bean>


text:
Q: LLVM assertion failure using AliasAnalysis in Module pass I am running into an issue trying to use AliasAnalysis from within a module pass (LLVM 3.4). This seems to be a fairly common issue with two main solutions, but I haven't been able to get it to work.
With the following simple test program:
#include <stdio.h>

static int gX;

void f() {
  gX = 1;
}

int main() {
  printf("Hello.\n");
  return 0;
}

Compiled like this: clang++ -O0 -c -emit-llvm -o test.bc test.cpp
And my simple pass:
class DebugPass : public ModulePass {
public:
  static char ID;
  DebugPass() : ModulePass(ID) {}

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    AU.setPreservesAll();
    AU.addRequired<AliasAnalysis>();
  }

  virtual bool runOnModule(Module &M) {
    for (Module::iterator fit = M.begin(), fite = M.end(); fit != fite; ++fit) {
      Function *F = fit;
      if (F->isDeclaration()) continue;
      errs() << "Getting AA for " << F->getName() << "\n";
      AliasAnalysis &AA = getAnalysis<AliasAnalysis>(*F);
    }
    return false;
  }
}
char DebugPass::ID = 0;
static RegisterPass<DebugPass> X("testdebug", "Debugging pass", false, false);

And by invoking my pass like this: opt -load ../Debug+Asserts/lib/TestLib.dylib -basicaa -testdebug < test.bc > /dev/null
I am seeing the following assertion failure:
Getting AA for _Z1fv
Assertion failed: (FPP && "Unable to find on the fly pass"), function getOnTheFlyPass, file LegacyPassManager.cpp, line 1682.
...
6  opt                      0x0000000102e5ba62 abort + 18
7  opt                      0x0000000102e5ba41 __assert_rtn + 129
8  opt                      0x0000000102d94820 (anonymous namespace)::MPPassManager::getOnTheFlyPass(llvm::Pass*, void const*, llvm::Function&) + 144
9  opt                      0x0000000102d949cf non-virtual thunk to (anonymous namespace)::MPPassManager::getOnTheFlyPass(llvm::Pass*, void const*, llvm::Function&) + 63
10 opt                      0x0000000102d8ed4e llvm::AnalysisResolver::findImplPass(llvm::Pass*, void const*, llvm::Function&) + 78
11 TestLib.dylib           0x0000000104ba9bac llvm::AliasAnalysis& llvm::Pass::getAnalysisID<llvm::AliasAnalysis>(void const*, llvm::Function&) + 236
12 TestLib.dylib           0x0000000104b9eef6 llvm::AliasAnalysis& llvm::Pass::getAnalysis<llvm::AliasAnalysis>(llvm::Function&) + 134
13 TestLib.dylib           0x0000000104bdc287 DebugPass::runOnModule(llvm::Module&) + 215

Can anyone offer some insight into what is going wrong?
Edit: Here is the pass structure via -debug-pass=Structure:
Pass Arguments:  -targetlibinfo -datalayout -notti -basictti -x86tti -no-aa -basicaa -testdebug -preverify -domtree -verify
Target Library Information
Data Layout
No target information
Target independent code generator's TTI
X86 Target Transform Info
No Alias Analysis (always returns 'may' alias)
Basic Alias Analysis (stateless AA impl)
  ModulePass Manager
    Debugging pass
    FunctionPass Manager
      Preliminary module verification
      Dominator Tree Construction
      Module Verifier
    Bitcode Writer

Is it significant that my debugging pass occurs before the FunctionPass manager? I am not practiced in interpreting the pass structure output.


text:
Q: jQuery get the document width and height excluding horizontal/vertical scrollbars I have a piece of jQuery on my site that displays an overlay the full width and height of the window. I have an issue in that if the overlay is closed (as there is an option to close it) I lose the vertical scroll bar from my window. Is there a way to specify the width and height excluding any horizontal or vertical scrollbars?
This is my code below, the jQuery will run as soon as the page loads.

        $('#screen').css({ "display": "block",
                            opacity  : 0.7,
                            "width"  : $(document).width(),
                            "height" : $(document).height()
                            });
        $('body').css({ "overflow" : "hidden" });

A: This works:
$('#screen').css({ "display": "block",
                    opacity  : 0.7,
                    "width"  : $(document).width(),
                    "height" : $(document).height()
                    });
$('body').css({ "overflow" : "auto" });


text:
Q: Loop coordinates into string repeated len(x) times I have a DataFrame filled with lat and lng coordinates like so:
     lat        lng
0   -33.859485  151.208584
1   -33.868370  151.207141
2   -33.861735  151.210873

Googlemaps uses the following string to place markers on a map, which I will call new_marker:
new_marker = '&markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C'+str(lat)+'+'+str(lng)

How could I create a loop which creates a string where new_marker is repeated x times (x in this case being the number of coordinates in the dataframe), with each repeat having the respective lat and lng inputted from the dataframe?
In effect, I'd like to be able to generate something like this:
'&markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C+lat0+lng0&markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C+lat1_lng1&markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C+lat2+lng2'
My experience with for and def is very limited.

A: The string corresponding to each lat and lng can be easily created with pandas apply method combined with string formatting.
The first step is to define the function that given a row, generates the desired string:
def coord_formatter(row):
    return '&markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C{:.6f}+{:.6f}'.format(row['lat'],row['lng'])

This basically substitutes row['lat'] to the position in the string where there is the {:.6f}, formatted as a 6 decimal position float, and the lng to the second.
Then, the new column can be created:
df['string'] = df.apply(coord_formatter,axis=1)
# Output df
#          lat         lng                                             string
# 0 -33.859485  151.208584  &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7...
# 1 -33.868370  151.207141  &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7...
# 2 -33.861735  151.210873  &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7...

Or, to create a single string:
output = '\n'.join(df.apply(coord_formatter,axis=1))
# print(output) produces
# &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C-33.859485+151.208584
# &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C-33.868370+151.207141
# &markers=size:mid%7Ccolor:0x0000b3%7Clabel:G%7C-33.861735+151.210873

Now each coordinate string is separated with a breakline between them, to have a single string where all of them are simply concatenated, ''.join(... can be used instead.


text:
Q: How to storage link in host? I upload my project in the host. I uploaded an image, and the image save in database. And the image did not show well, but it show in my localhost as well.
web.php
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Auth::routes();

Route::get('/link', function(){
    return Artisan::call('storage:link');
});

Controller
public function update(Request $request)
{
    $user = auth()->user();
    $path = $user->image ?? null;
    if ($request->hasFile('image'))
    {
        $file = $request->file('image');
        $nane = time();
        $extension = $file->getClientOriginalExtension();
        $fileName = $nane . '.' . $extension;
        $path = $file->storeAs('images/users', $fileName, 'public');
    }
    $user->image = $path;
}

The image save in database.
The image uploaded in storage/app/public/images/users folder.
The image did not uploaded public/images/users.

A: Do you have an access to server with ssh? If not you can write like this in your route :
Route::get('/foo', function () {
    Artisan::call('storage:link');
});

It will generate the symlink to your public_html, sorry for my bad english


text:
Q: Bootstrap popover with dynamic content breaks custom checkbox CSS functionality Please take a look at my sample code.
I have custom checkboxes which use Font Awesome's icons. It all works fine until I use custom popover content, which I load on document.ready.
When the content is loaded this way (instead of specifying content directly in the anchor element), the checkboxes stop working (cannot check them).
Any ideas why?
Here's a working example, where the content is set directly.
FYI, the relevant CSS code that lets the Font Awesome checkbox look like it's been checked is:
input[type=checkbox]:checked + label:before { content: "\f046"; }

A: Apply This CSS.
input[type="checkbox"] {
display: block;
height: 21px;
opacity: 0;
position: absolute;
width: 20px;
left:0;
top:0;
z-index: 999;}
.test{position:relative}

also HTML

<input id="box1" type="checkbox" />
Checkbox 1

    <input id="box1" type="checkbox" />
    Checkbox 2

    <input id="box1" type="checkbox" />
    Checkbox 3


text:
Q: Is there a way to get response in json format for Azure Storage Account Queue when Querying from Postman I created an Azure Storage Account and then a Queue Resource as follows.

And I have some messages inside of it as follows.

Now I am able to query with Postman as follows.

As you can see, the response is in xml. Is there a way I can get that in json format?
Changing that xml in the drop down to json is not helping me.

A: Unfortunately it is not possible to get the response in JSON format. Azure Storage Queue REST API only returns data in XML format at least as of version number 2020-10-02 (latest version at the time of providing this answer).


text:
Q: Laravel 8 Queue worker on Heroku On Heroku, I'm running Laravel 8. For background activities, I'm utilizing the Laravel Queue. Everything worked OK before, but now I'm getting an error:
The [database] queue connection is not configured

My queue configurations
return [

'default' => env('QUEUE_DRIVER', 'database'),

'connections' => [

    'sync' => [
        'driver' => 'sync',
    ],
    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'retry_after' => 700,
        'after_commit' => false,
        'timeout' => 180,
    ],

I have run composer dump and I have cleared all application cache but it's not working, how can I fix this?


text:
Q: Travelling salesman - Linear Programming So I just asked this question and accepted an answer, but I realized that I still don't understand this, and I can't access my previous question. We have the travelling salesman problem

Label the cities with the numbers $0, ...,n$ and define:
$x_{ij} = \begin{cases} 1 & \text{the path goes from city } i \text{ to city } j \\ 0 & \text{otherwise} \end{cases} $
For $i = 0, ...,n$, let $u_i$ be an artificial variable, and finally take $c_{ij}$ to be the distance from city $i$ to city $j$. Then TSP can be written as the following integer linear programming problem:
$\begin{align}
\min &\sum_{i=0}^n \sum_{j\ne i,j=0}^nc_{ij}x_{ij} &&  \\
     & 0 \le x_{ij} \le 1  && i,j=0, \cdots, n  \\
     & u_{i} \in \mathbf{Z} && i=0, \cdots, n \\
     & \sum_{i=0,i\ne j}^n x_{ij} = 1 && j=0, \cdots, n \\
     & \sum_{j=0,j\ne i}^n x_{ij} = 1 && i=0, \cdots, n \\
&u_i-u_j +nx_{ij} \le n-1 && 1 \le i \ne j \le n
\end{align}$

The last constraint, $u_i-u_j +nx_{ij} \le n-1$ makes sure that there are no subtours. However, I don't see what this is. Wikipedia says the following:

To prove that every feasible solution contains only one closed sequence of cities, it suffices to show that every subtour in a feasible solution passes through city 0 (noting that the equalities ensure there can only be one such tour). For if we sum all the inequalities corresponding to $x_{ij}=1$ for any subtour of $k$ steps not passing through city 0, we obtain:
  $nk \leq (n-1)k$.

I don't understand this at all. How is the $nk \leq (n-1)k$ obtained? And how does this prevent there being any subtours at all? I have no clue.
As for the dummy variables, what purpose do they serve? Wikipedia says:

It now must be shown that for every single tour covering all cities, there are values for the dummy variables $u_i$ that satisfy the constraints.

But it doesn't at all explain why these dummy variables are necessary and what they add to the inequality. I'm stumped.
This question has been asked before here (but the answer doesn't help me at all) and here (by me, I thought it helped but it didn't), but none of the answers help and my question is slightly different, mostly focusing on how they obtained the expression  $nk \leq (n-1)k$ and why this prevents subtours from forming

A: For your first question: suppose you have a solution to the linear program that has subtour $1 \to 2 \to 3 \to 1$. By assumption, the last set of inequalities holds, so if you add up the following,
\begin{align}
u_1-u_2 + n x_{12} &\le n-1\\
u_2-u_3 + n x_{23} &\le n-1\\
u_3-u_1 + n x_{31} &\le n-1,
\end{align}
you get $$3n \le 3(n-1).$$
This is a contradiction, so this subtour $1 \to 2 \to 3 \to 1$ does not exist.
In general for any subtour of length $k$ not including $0$, the same argument applies: adding up the inequalities corresponding to each edge of the subtour will give $kn \le k(n-1)$ because the $u_i$ terms will cancel.


text:
Q: Report array of values from first tick NetLogo I'm writing some code to vaccinate individuals in a population where flu is circulating. The code has two kinds of vaccines named HOV and HEV. HOV gives an identical vaccine strain to the proportion of the population I want to target. HEV gives different vaccine strains (determined randomly) to this proportion.
I wanted a line of code that reports each turtle's immune status in the first tick of each simulation. Immune status is represented by an integer in this model, so different turtles will have different immune labels depending on whether or not they were vaccinated. I'm hoping to end up with a column containing the array of immune labels of all turtles in the first tick for each run in the final BehaviourSpace .csv output.
My code is below:
extensions [csv]
globals [strain_list_list epidemic-threshold cumulative-infections proportion-of-infection currently-infected peak-prevalence vax-strain]
turtles-own [infection-period infection-number tflu-strain immune-label ant-distance cross-immunity]
patches-own [fomite-age pflu-strain]

to setup
  clear-all
  setup-turtles
  reset-ticks
end

to setup-turtles
  create-turtles 100
  ask turtles [setxy random-xcor random-ycor]
  ask turtles [set color white set infection-number 0 set immune-label -999999999999 set tflu-strain -999999999999]
  ask one-of turtles [set color red set infection-period 0 set infection-number 1 set immune-label 0 set tflu-strain 0]
  if vaccine = "HOV" [
    ifelse (one-of [1 2] = 1) [
      set vax-strain (random ((2 * drift-size) + 1))]
    [set vax-strain (-1 * random ((2 * drift-size) + 1))]
  ask n-of prop-vax turtles with [color = white] [set color blue set immune-label vax-strain]
  ]
  if vaccine = "HEV" [
    let vax-turtles (list turtles with [color = blue])
    ask n-of prop-vax turtles with [color = white] [set color blue]
    foreach [vax-turtles] [
      ifelse (one-of [1 2] = 1) [
      set vax-strain (random ((2 * drift-size) + 1))]
    [set vax-strain (-1 * random ((2 * drift-size) + 1))]
      ]
    ]
  set epidemic-threshold "no"
  set cumulative-infections 0
  set peak-prevalence 0
end

to go
  if ticks = flu-season-length [stop]
  move-infecteds
  move-uninfecteds
  transmit
  mutate
  update-immunity
  track-infecteds
  set cumulative-infections (count turtles with [infection-period = 1] + cumulative-infections)
  set proportion-of-infection (100 - (count turtles with [immune-label = -999999999999]))
  set currently-infected (count turtles with [infection-period = 1])
  tick
end

to move-infecteds ;; infected turtles move slower than uninfected ones and always transmit infection to patches before they leave them
  ask turtles with [color = red] [
  if pcolor = black [
      set pcolor red
    set fomite-age 0
    set pflu-strain tflu-strain]
  right random 360
  forward 3
]
end

to transmit ;; uninfected turtles are infected by fomites (red patches) with some probability. immune-labelling currently first infection
  ask turtles with [color = white or color = blue and pcolor = red] [
    if immune-label != pflu-strain [
      set ant-distance (abs (immune-label - pflu-strain))
      set cross-immunity (natural-immunity * (1 - (ant-distance / antigenic-distance-limit)))
    if cross-immunity < 0 [set cross-immunity 0]
    if random 100 < (((100 - cross-immunity) / 100) * probability-of-infection)
      [set color red set infection-period 0 set infection-number infection-number + 1 set tflu-strain pflu-strain]
        ]
  if immune-label = pflu-strain [
    if random 100 < (((100 - natural-immunity) / 100) * probability-of-infection)
      [set color red set infection-period 0 set infection-number infection-number + 1 set tflu-strain pflu-strain]
    ]
]
end

to mutate ;; some probability of mutation (change in strain label) when an individual receives infection from a patch
  ifelse in-host [
    ask turtles with [color = red] [
     if random 100 < probability-of-mutation [
      ifelse (one-of [1 2] = 1) [
      set tflu-strain (tflu-strain + (random (drift-size + 1)))]
      [set tflu-strain (tflu-strain - (random (drift-size + 1)))]
     ]
    ]
   ]
  [ask turtles with [color = red and infection-period = 0] [
     if random 100 < probability-of-mutation [
      ifelse (one-of [1 2] = 1) [
      set tflu-strain (tflu-strain + (random (drift-size + 1)))]
      [set tflu-strain (tflu-strain - (random (drift-size + 1)))]
      ]
     ]
    ]
end

to update-immunity
  ask turtles with [color = red and infection-period = 0] [
    ifelse immune-labelling = "first-infection" [
  if immune-label = -999999999999 [
        set immune-label tflu-strain]]
  [set immune-label tflu-strain]
]
end

 to track-infecteds ;; turtles with given infection period should become uninfected
  ask turtles with [color = red] [
    set infection-period infection-period + 1
  if infection-period = age-infection-max [
    set color white set infection-period 0 set tflu-strain -999999999999
    ]
  ]
  ask patches with [pcolor = red] [
  set fomite-age fomite-age + 1
  if fomite-age > max-fomite-persistence [
  set pcolor black
    ]
  ]
end

Any advice would be greatly appreciated! Thanks!

A: On second thought – I think I found an answer! I basically created a list of lists that stores the immune labels once the setup command is complete. My updated code is below:
extensions [csv]
globals [initial-immunity-array epidemic-threshold cumulative-infections proportion-of-infection currently-infected peak-prevalence vax-strain]
turtles-own [infection-period infection-number tflu-strain immune-label ant-distance cross-immunity]
patches-own [fomite-age pflu-strain]

to setup
  clear-all
  setup-turtles
  set initial-immunity-array (list t-sorted-immunity-list)
  print initial-immunity-array
  reset-ticks
end

to setup-turtles
  create-turtles 100
  ask turtles [setxy random-xcor random-ycor]
  ask turtles [set color white set infection-number 0 set immune-label -999999999999 set tflu-strain -999999999999 set vax-strain -999999999999]
  ask one-of turtles [set color red set infection-period 0 set infection-number 1 set immune-label 0 set tflu-strain 0]
  if vaccine = "HEV" [
    ask n-of prop-vax turtles with [color = white] [set color blue]
    ask turtles with [color = blue] [
    ifelse (one-of [1 2] = 1) [
      set vax-strain (random ((2 * drift-size) + 1))]
    [set vax-strain (-1 * random ((2 * drift-size) + 1))]
   set immune-label vax-strain
    ]
  ]
  if vaccine = "HOV" [
    ask n-of prop-vax turtles with [color = white] [set color blue]
    ifelse (one-of [1 2] = 1) [
      set vax-strain (random ((2 * drift-size) + 1))]
    [set vax-strain (-1 * random ((2 * drift-size) + 1))]
    ask turtles with [color = blue] [set immune-label vax-strain
    ]
  ]
  set epidemic-threshold "no"
  set cumulative-infections 0
  set peak-prevalence 0
end

to-report t-sorted-immunity-list
  report map [i -> [immune-label] of i] sort turtles
end

to go
  if ticks = flu-season-length [stop]
  move-infecteds
  move-uninfecteds
  transmit
  mutate
  update-immunity
  track-infecteds
  show-strains
  track-epidemic
  set cumulative-infections (count turtles with [infection-period = 1] + cumulative-infections)
  set proportion-of-infection (100 - (count turtles with [immune-label = -999999999999]))
  set currently-infected (count turtles with [infection-period = 1])
end


text:
Q: Compare elements of multiple vectors efficiently EDIT: After some experimenting I think it might be this line:
outcomes.push_back(thesePathGatherers[j].GetResultsSoFar()[0][i]);

Causing issue. The implementation of those class functions are. Could getting these values back from the vector of vectors like this be slow (and slower for larger vectors)?. TheDumpOneResult function is called in "OneStepMonteCarloValuation" prior which fills the ResultList vector
StatisticAllPaths::StatisticAllPaths(const unsigned long minimumNumberOfPaths) : PathsDone(0)
{
    ResultList.reserve(minimumNumberOfPaths);
}

void StatisticAllPaths::DumpOneResult(double result)
{
    ResultList.push_back(result);
    PathsDone++;
}

std::vector<std::vector<double>> StatisticAllPaths::GetResultsSoFar() const
{
    vector<double> innerVector(ResultList);
    vector<vector<double> > Results(1, innerVector);
    Results[0] = ResultList;
    return Results;
}

I have a piece of code that looks like this:
void MonteCarloRainbowOptionFunction::ValueInstrument()
{
    std::vector<MJArray> correlatedNormVariates = GetArraysOfCorrelatedGauassiansByBoxMuller(numberOfPaths, covMatrix);
    std::vector<StatisticAllPaths> thesePathGatherers;
    for (unsigned long i = 0; i < S_vect.size(); i++)
    {
        StandardExcerciseOption thisOption(ThePayOffVect[i], TTM);
        StatisticAllPaths onePathGatherer;
        thesePathGatherers.push_back(onePathGatherer);
        OneStepMonteCarloValuation(thisOption, S_vect[i], impvol_vect[i], r, d_vect[i], numberOfPaths, correlatedNormVariates[i], thesePathGatherers[i]);
    }
    f = 0;
    std::cout << "Time check" << "\n";
    for (unsigned long i = 0; i < numberOfPaths; i++)
    {
        std::vector<double> outcomes;
        for (unsigned long j = 0; j < S_vect.size(); j++)
        {
            outcomes.push_back(thesePathGatherers[j].GetResultsSoFar()[0][i]);
        }
        switch (optionType)
        {
        case RainbowOptionType::best_of:
            f += *max_element(outcomes.begin(), outcomes.end());
            break;
        case RainbowOptionType::worst_of:
            f += *min_element(outcomes.begin(), outcomes.end());
            break;
        default:
            throw std::runtime_error("Unsupported or unknown option type found in " + GetuniqueIdentifier()[0]);
            break;
        }
    }
    std::cout << "Time check" << "\n";
    f *= ((double)nominal/numberOfPaths);
    return;
}

In the first part (before the first "Time Check") I simulate a large amount of values which gets saved in the vectors (really in the first vector of a vector of vectors) thesePathGatherers through the function OneStepMonteCarloValuation. In the second part I go through all the vectors and save the i element in the temp "output" vector, compare the values in output and save the result and then do the same. Looping through all the values in the thesePathGatherers. The first part runs fast but the second one takes much longer and even fails to complete all together for high enough numberOfPaths. How can I optimize this code?
Note that numberOfPaths will be very large
Let me know if there is more I need to share.