text:
Q: Write to 2 datasources simultaneously when calling SaveAll in CakePHP I am trying to write values to 2 databases (need not be simultaneously) when the saveAll function is called. This does not apply to all tables but only 4 out of the 10 tables in the 2 databases.
My current logic, in Pseudocode:
    $updateOk = $model->saveAll(...);

    if (!$updateOk)
      return error;

    /* start second source synchronizing */
    $model->changeDataSource('second');
    $updateOk = $model->saveAll(...);

    $model->changeDataSource('default');
    if (!$updateOk)
        return error;

    return;

The issue with this is that sometimes it does not write to the second source, resulting in inconsistencies.
I need some advice on how to best solve this issue. I have 3 possible ideas:

*

*Follow the code above and add checks to make sure things get saved and if it doest, rollback the default to maintain consistency

*Write a server script that does a replication every time a saveAll() is called. (Resource intensive and not really scalable)

*Use a combo of both. Do a check for consistency before saving and do a script replication once a day

Which is the best way or are there better ways of implementing this requirement? Any ways to ensure consistencies?

A: The solution possibly lies in database table replication (set up your second database as a slave, configured to replicate only specific tables).
Also, how will you ever scale this?
This way, you only need to worry about writing to the DB once (your models are going to get very bloated if you need all this extra code to write to two every time), plus you are allowing your app to scale horizontally in the future (think if your app was so big you required 20 x database servers?).
Another solution would be to create a shell task, scheduled on a cron job to move the data, but I would consider replication first.
Good luck!


text:
Q: Translate svg element so data lines up with axes I'm trying to modify an example scatterplot here to include gridlines and also to functionize the plotting like I've seen in tutorial I'm taking. I am able to add the gridlines and create a plot function, but the data points no longer line up with the axes.
Question: How can I make the data and the axes align?

I think the problem is with how the SVG element is translated or something with the "chart" class. I've tried various translations using the height and width vars, but still don't understand how to make my gridlines and data match up without manually translating things until they fit.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Learning D3</title>
    <link rel="stylesheet" href="main.css">
    <script  type="text/javascript" src="d3.min.js"></script>
</head>
<body>
<!--Place all DOM elements here -->
<script>
var w = 800;
var h = 450;
var margin = {
    top: 60,
    bottom: 80,
    left: 100,
    right: 80
};
var width = w - margin.left - margin.right;
var height = h - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var svg = d3.select("body").append("svg")
    .attr("id", "chart")
    .attr("width", w)
    .attr("height", h);

var chart = svg.append("g")
    .classed("display", true)
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var yGridlines = d3.svg.axis()
    .scale(y)
    .tickSize(-width,0,0)
    .tickFormat("")
    .orient("left");

var xGridlines = d3.svg.axis()
    .scale(x)
    //.tickValues(tickValues)
    .tickSize(-height,-height)
    .tickFormat("")
    .orient("bottom");

function drawAxis(params){
    if(params.initialize){
        this.append("g")
            .classed("gridline x", true)
            .attr("transform", "translate(0," + height + ")")
            .call(params.axis.gridlines.x);
        this.append("g")
            .classed("gridline y", true)
            .attr("transform", "translate(0,0)")
            .call(params.axis.gridlines.y);
        this.append("g")
            .classed("axis x", true)
            .attr("transform", "translate(0," + height + ")")
            .call(params.axis.x);
        this.append("g")
            .classed("axis y", true)
            .attr("transform", "translate(0,0)")
            .call(params.axis.y);
        this.select(".y.axis")
            .append("text")
            .classed("y axis-label", true)
            .attr("transform", "translate(" + -56 + "," + height/2 + ") rotate(-90)")
            .text("Sepal Length")
        this.select(".x.axis")
            .append("text")
            .classed("x axis-label", true)
            .attr("transform", "translate(" + width/2 + "," + 48 + ")")
            .text("Sepal Width");
        this.append("g")
            .append("text")
            .classed("chart-header", true)
            .attr("transform", "translate(0,-24)")
            .text("");
    }
}

function plot(params){
  params.data.forEach(function(d) {
    d.sepalLength = +d.sepalLength;
    d.sepalWidth = +d.sepalWidth;
  });

  x.domain(d3.extent(params.data, function(d) { return d.sepalWidth; }))
  y.domain(d3.extent(params.data, function(d) { return d.sepalLength; }))

  drawAxis.call(this, params);

  /*
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
    .append("text")
      .attr("class", "label")
      .attr("x", width)
      .attr("y", -6)
      .style("text-anchor", "end")
      .text("Sepal Width (cm)");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("class", "label")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Sepal Length (cm)")
      */

  svg.selectAll(".dot")
      .data(params.data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 5)
      .attr("cx", function(d) { return x(d.sepalWidth); })
      .attr("cy", function(d) { return y(d.sepalLength); })
      .style("fill", function(d) { return color(d.species); });

  var legend = svg.selectAll(".legend")
      .data(color.domain())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + ((i * 20) + 100) + ")"; });

  legend.append("rect")
      .attr("x", width - 40)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 44)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

};

d3.csv("iris.csv", function(error, parsed_data) {
    plot.call(chart, {
        data: parsed_data,
        axis: {
            x: xAxis,
            y: yAxis,
            gridlines:{
                x: xGridlines,
                y: yGridlines
            }
        },
        initialize: true
    })
});

</script>
</body>
</html>

*Note: the data is on the example I liked to. Here's a sample for reproducibility:
// Data in either csv or tsv depending on preference:
sepalLength sepalWidth  petalLength petalWidth  species
5.1 3.5 1.4 0.2 setosa
4.9 3   1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5   3.6 1.4 0.2 setosa
6.4 3.2 4.5 1.5 versicolor
6.9 3.1 4.9 1.5 versicolor
5.5 2.3 4   1.3 versicolor
6.5 2.8 4.6 1.5 versicolor
6.5 3   5.5 1.8 virginica
7.7 3.8 6.7 2.2 virginica
7.7 2.6 6.9 2.3 virginica
6   2.2 5   1.5 virginica
6.9 3.2 5.7 2.3 virginica

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set label of axis automatically Is there any way to set the labels of a plot's axis automatically according to the name that the variables have in the code.
For example:
import matplotlib.pyplot as plt
import numpy as np
x_variable=np.linspace(1,5)
y_variable=x_variable**2
plt.plot(x_variable,y_variable)
some_function()

is there any way to add some_function() to this code such that the result for this example will be equivalent to:
plt.xlabel('x_variable')
plt.ylabel('y_variable')

A: In your case x_variable and y_variable are numpy arrays as you are using them to plot on matplotlib.
So you can use the following function as you requested to extract the variable name and plot it as a label
import matplotlib.pyplot as plt
import numpy as np

def Return_variable_name_as_string(myVar):
    return [ k for k,v in globals().iteritems() if np.array_equal(v,myVar)][0]

x_variable=np.linspace(1,5)
y_variable=x_variable**2
plt.plot(x_variable,y_variable)
plt.xlabel(Return_variable_name_as_string(x_variable))
plt.ylabel(Return_variable_name_as_string(y_variable))

You may have to change globals with locals, but that will depend on how you use it on your case.

A: Not really.  However, you can use a dictionary to store the values and use the keys as the labels.
import matplotlib.pyplot as plt
import numpy as np
data = {}
x = 'x_variable'
y = 'y_variable'
data[x] = np.linspace(1,5)
data[y] = x_variable**2
plt.plot(data[x], data[y])

plt.xlabel(x)
plt.ylabel(y)


text:
Q: How to use Stetho with okhttp3 for network inspection? I launched the app the Android emulator (Genymotion). Problem is I cannot inspect anything in Chrome Dev Tools (see screenshot below). Any tips ?
Stetho
Google Chrome Dev Tools in (address bar)
This is what I see after entering this URL in Chrome
chrome://inspect/

TrainerWorkoutApplication.java
import android.app.Application;
import android.content.Context;

import com.facebook.stetho.Stetho;

public class TrainerWorkoutApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        Stetho.initialize(Stetho.newInitializerBuilder(this)
        .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
        .build());
    } // onCreate()

} // TrainerWorkoutApplication

LogInActivity.java
package com.trainerworkout.trainerworkout.activity;

//...

/** As a personal trainer I need to log in so that I can have access to the app. */
public class LogInActivity extends AppCompatActivity {
    public static OkHttpClient client;
    private OkHttpClient.Builder builder = new OkHttpClient.Builder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        builder.addInterceptor(new AddCookiesInterceptor(context));
        builder.addInterceptor(new ReceivedCookiesInterceptor(context));

        builder.addNetworkInterceptor(new StethoInterceptor());

        client = builder.build();
    } // onCreate()

    //...

} // LogInActivity

build.gradle (app)
apply plugin: 'com.android.application'

android {
    //...
} // android

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.squareup.okhttp3:okhttp:3.0.1'
    compile 'com.google.code.gson:gson:2.5'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.facebook.stetho:stetho:1.3.1'
    compile 'com.facebook.stetho:stetho-okhttp3:1.3.1'
} // dependencies

A: To fix this, I think the Application class should be in the application package and not in the java package. Also, make sure the application class is declared in the
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.trainerworkout.trainerworkout"
          xmlns:android="http://schemas.android.com/apk/res/android">
    ...
    <application
        ...
        android:name=".TrainerWorkout">
        ...
    </application>
</manifest>

For more info on how to use Stetho I recommend this tutorial.
Debugging Android Apps with Facebook's Stetho


text:
Q: Bypass Confirm Action Dialog Box I have a simple code where I'm deleting certain users from Distribution Groups. However, whenever it attempts to delete a user, a dialog box appears asking me if I really want to delete the user. It does this for every user I try to delete. Is there a way to make it so that box doesn't appear, and says yes automatically?
Here's my code:
#Accept input parameters
Param(
      [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
      [string] $DistributionGroup
     )

$DL = Get-DistributionGroupMember -Identity $DistributionGroup | select windowsliveid, name | where windowsliveid -like '*c-*'
$DL

$DL | % {
    Remove-DistributionGroupMember -Identity $DistributionGroup -Member $_.name
    }

A: Normally this should work:
Remove-DistributionGroupMember -Identity $DistributionGroup -Member $_.name -Confirm:$False

As indicated here.

A: if you set $confirm to false explicitly, it shouldn't prompt you to confirm.
Remove-DistributionGroupMember -Identity $DistributionGroup -Member $_.name -Confirm:$False

Alternatively, you can try -force parameter as well.
Remove-DistributionGroupMember -Identity $DistributionGroup -Member $_.name -Force

PS: Test above changes before trying out in production environment.
Source: https://social.technet.microsoft.com/Forums/windowsserver/en-US/03afb508-12f2-4173-a94d-273dc7b848b4/how-to-stop-getting-prompted-to-confirm?forum=winserverpowershell


text:
Q: Solr Query not found I have a solr-MSSQL server settng annd I import data from sql data base and all my data is on-uicode. the import is done very well but when searching, it failes to bring the result although when I query . it returns some results. is there any suggestion why it is so?

A: How are you searching the data ? whats the query ? can you post the queries and the configuration ?
To start with : -
q=*:* searches for all content on all the documents, hence you get back the results.
q=something will search for something on the default search field, which is usually text if you have not modified the schema.xml.
<defaultSearchField>text</defaultSearchField>

You can change the default field to be the field you want to search on.
OR use specific field to search on the specific field e.g. title q=some_field:something
If you want to search on multiple field, you can combine the fields into one field by using copyfields or use dismax request handler.


text:
Q: Android Studio: Code is done, but app is crashing everytime I try to run I've made an app that allows user to login but everytime I try to run, my App is crashing constantly.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mertino11.ourapplication">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".FireApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true">
        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    </manifest>

activity_account.xml (XML for user logged in succesfully)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_account"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mertino11.ourapplication.AccountActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Account Page"
        android:ems="10"
        android:id="@+id/editText"
        android:textSize="22sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:textStyle="normal|bold"
        android:textAlignment="center" />
</RelativeLayout>

activity_main.xml (login page)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:baselineAligned="false">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/emailField"
        android:hint="Email"
        android:paddingTop="20dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/passwordField"
        android:hint="Password"
        android:fontFamily="sans-serif"
        android:paddingTop="20dp" />

    <Button
        android:text="Login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/loginBtn"
        android:paddingTop="20dp" />
</LinearLayout>

Java --> Class: AccountActivity (Page when the user logged in successfully)
package com.example.mertino11.ourapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class AccountActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
    }
}

Java --> Class: FireApp (Firebase settings I think)
package com.example.mertino11.ourapplication;

import android.app.Application;

import com.firebase.client.Firebase;

/**
 * Created by Mertino11 on 10-Dec-16.
 */

public class FireApp extends Application {

    @Override
    public void  onCreate() {
        super.onCreate();

        Firebase.setAndroidContext(this);
    }
}

Java --> Class: Main Activity (Back-end logging with account)
package com.example.mertino11.ourapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    private EditText mEmailField;
    private EditText mPasswordField;

    private Button mLoginBtn;

    private FirebaseAuth mAuth;

    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();

        mEmailField = (EditText) findViewById(R.id.emailField);
        mPasswordField = (EditText) findViewById(R.id.passwordField);

        mLoginBtn = (Button) findViewById(R.id.loginBtn);

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if(firebaseAuth.getCurrentUser() != null) {

                    startActivity(new Intent(MainActivity.this, AccountActivity.class));

                }
            }
        };

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startSignIn();

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        mAuth.addAuthStateListener(mAuthListener);
    }

    private void startSignIn() {

        String email = mEmailField.getText().toString();
        String password = mPasswordField.getText().toString();

        if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {

            Toast.makeText(MainActivity.this, "Fields are empty!", Toast.LENGTH_LONG).show();

        } else {
            mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if(!task.isSuccessful()){

                        Toast.makeText(MainActivity.this, "Sign In Problem!", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

    }
}

Error Message at Run:
 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.mertino11.ourapplication, PID: 3060
                  android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?
                      at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                      at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                      at android.app.Activity.startActivityForResult(Activity.java:4224)
                      at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                      at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
                      at android.app.Activity.startActivityForResult(Activity.java:4183)
                      at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
                      at android.app.Activity.startActivity(Activity.java:4507)
                      at android.app.Activity.startActivity(Activity.java:4475)
                      at com.example.mertino11.ourapplication.MainActivity$1.onAuthStateChanged(MainActivity.java:48)
                      at com.google.firebase.auth.FirebaseAuth$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.

Screenshot of the error:
http://i66.tinypic.com/51btrp.png
The scenario of the app:

*

*Create account firebase Google (manually)

*Opens app --> Sees login page

*Logs in with accountdetails of Firebase

*Goes to AccountActivity page

Note: I am a amateur/beginner with AndroidStudio.

A: The error is pretty self-explanatory.
You have missed adding the AccounActivity on your manifest...
<application
    android:name=".FireApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name=".AccountActivity"
        android:theme="@style/AppTheme" />
</application>

A: Add AccountActivity in your AndroidManifest.xml
<activity
        android:name=".AccountActivity">
        <intent-filter>
            ...
        </intent-filter>
</activity>

A: Always carefully read logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.mertino11.ourapplication/com.example.mertino11.ourapplication.AccountActivity}; have you declared this activity in your AndroidManifest.xml?

A: I thank you all for giving me the solution. However (If it is possible) do you guys know why my App is running AccountActivity first instead of my Mainactivity? (it should run the mainactivity first)?

A: add .AccountActivity in manifest file as
 <activity
    android:name=".AccountActivity">

   </activity>


text:
Q: submit function does not trigger onsubmit return function? I think I have a misunderstanding of the onsubmit attribute. I thought that every submission, like a <input type="submit" ...>, <button></button> or any javascript form.submit() trigger the onsubmit="return function();" after the submit. In other words, I will never see the "last triggered" log.
Example:

function triggerFirst() {
  console.log("first triggered");
  myForm.submit();
}

function triggerLast() {
  console.log("last triggered");
  return true;
}
<form id="myForm" onsubmit="return triggerLast();">
  <input type="button" onclick="triggerFirst();" value="trigger">
</form>

This example will never trigger the onsubmit, why? I thought onsubmit means if someone submits? Is that false?

A: It works.
UPDATED:
Place the 2nd function inside first.

function triggerFirst() {
  alert('wow');
triggerLast()
}

function triggerLast() {
alert('wowpsubmit');
  return true;
}
<form id="myForm" onsubmit='return triggerLast();'>
  <input type="button" onclick="triggerFirst();" value="trigger" >
</form>

A: An HTML form does not require javascript to work. Refer the code below:
<form action="action_page.php">
  First name:

  <input type="text" name="firstname" value="Mickey">

  Last name:

  <input type="text" name="lastname" value="Mouse">

  <input type="submit" value="Submit">
</form>

The <form action="action_page.php"> declaration is run once the form is submitted.
The <input type="submit" value="Submit"> is a built in type that triggers the form action to run.
See more here

A: In your triggerFirst function the inner function call to submit does nothing. That submit function is not defined. I think here you want to make the function submit so below I passed a reference to the form into the triggerFirst function. This should clarify things for you. Open the console to view the output.

function triggerFirst(form) {
  console.log('triggerFirst')
  console.log(form);
  form.submit();
}

function triggerLast() {
  console.log('triggerLast')
  return true;
}
<form onsubmit="return triggerLast();">
  <input type="button" onclick="triggerFirst(this.form);" value="trigger">
</form>


text:
Q: Left join two datatables- No SQL and no LINQ I have a dataset in my VB.NET solution. Let's say the dataset has 2 data tables (MyTable1 and MyTable2). Lets assume MyTable1 and MyTable2 are like:
MyTable1:

Order
Account_Number
Account_Name

10000
10000000000001
BlahA

20000
10000000000002
BlahB

30000
10000000000003
BlahC

MyTable2:

Order_Number
Line_Number
Model

10000
00000000034
MD35Z

15000
00000000530
MX25A

25000
00000024535
P231Y

20000
00000027735
A511L

30000
00000000910
M232C

Now I want to left join MyTable2 to MyTable1 and get the following result as my MyTable1:

Order
Account_Number
Account_Name
Line_Number
Model

10000
10000000000001
BlahA
00000000034
MD35Z

20000
10000000000002
BlahB
00000027735
A511L

30000
10000000000003
BlahC
00000000910
M232C

To achieve this, I used LINQ, however, I was wondering if there is any way to use SQL queries when the datatables are not in a SQL database? (There is no db connection).


text:
Q: Not authorized returned to windows Universal app from Azure mobile app I have created an azure mobile app which exposes an api. I have registered the mobile app for Microsoft account authentication. The mobile app is working when I access it from postman or even Microsoft edge after I log into my windows account.
The mobile app is a backend for a universal windows app. I followed the boilerplate Microsoft examples (Add Authentication to UWA).  The code to login to the site works well (It either retrieves my stored credentials or has me log into the Microsoft account server).  The credentials are stored in the CurrentUser of an instance of MobileServiceClient.
This is an example of one of the controllers.
    [MobileAppController]
    [Authorize]
    public class TeamsController : ApiController
    {
    private GameNoteContext db = new GameNoteContext();
    [HttpGet, Route("api/Teams")]
    // GET: api/Teams
    public IQueryable<Team> GetTeams()
    {
                   return db.Teams;
    }

The client calls the api with the following code:
    //myuri is the controller, param is the query strings as a dictionary object
     var response = await client.InvokeApiAsync(myuri, System.Net.Http.HttpMethod.Get, param);
The generated request is correct and appears to have the correct headers.  I can copy them into postman and I get the correct response.  But from my client (run from visual studio) I get unauthorized.  Here is the request body that is sent from the client:
  X-ZUMO-FEATURES: AT,QS
  X-ZUMO-INSTALLATION-ID: theidiscorrect
  X-ZUMO-AUTH: atokenappearshere
  Accept: application/json
  User-Agent: ZUMO/2.1
  User-Agent: (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.1.40707.0)
  X-ZUMO-VERSION: ZUMO/2.1 (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.1.40707.0)
  ZUMO-API-VERSION: 2.0.0
  Accept-Encoding: gzip

I can't figure out what to try next.

A: You will need to turn on Application Logging in the portal and take a look at the server side logs.  Short version is that the token is not being accepted.  This could be because it has expired or because there is a configuration error on the server-side.  However, you won't be able to tell until you take a look at the server side logs.
See Enable diagnostics logging for web apps in Azure App Service.


text:
Q: Set the exception (error handling) to a boolean I'm doing a boolean check and I run into several div/0 errors. So I want the error to be set to False so that my output has either True or False. I tried the code below but Python threw a syntax error. Is there a way to go about this?
    except ZeroDivisionError as False:

A: The code you have is attempting to assign a ZeroDivisionError object to the name False.  There's no good reason to do that, and the language assumes you're making a mistake and won't let you.  (Python 3 does not allow you to assign to False at all).
Instead, you should have a variable with a unique name that you use to store whether ot not the error was raised:
try:
    1/maybe_zero
    var = True
except ZeroDivisionError:
    var = False


text:
Q: Split Field in a Linq Query Below is the content of a field name OULocationPath.  I need to parse out the OU=location but only the "location". Not the "OU=".
CN=my name,OU=department,OU=location,OU=general area,DC=company,DC=org
Below is the query that I use to populate a grid.  I haven't added the field above as of yet.
  Public Function GetLocationList() As List(Of Contact)
    GetLocationList = mContacts.FindAll(Function(x) x.Company.Contains("CompanyName") = True And x.WorkEmail = Nothing And x.WorkPhone <> "")
End Function

Thank you!

A: @Andrew Morton and @NetMage,
I was able to get the parse working using the code below:
 Public Function GetLocationList() As List(Of Contact)
    GetLocationList = Nothing
    Dim Answerset = mContacts.FindAll(Function(x) x.Company.Contains("CompanyName") = True AndAlso x.WorkEmail = Nothing AndAlso x.WorkPhone IsNot Nothing)
    Dim _GridLocations As New List(Of Contact)
    Dim _GridLocation As Contact
    _GridLocations.Clear()

    For Each l In Answerset
        _GridLocation = New Contact
        With _GridLocation
            .FullName = l.FullName
            .WorkPhone = l.WorkPhone
            .Extension = l.Extension

            Dim s As String = l.OULocationPath
            Dim sp As String() = s.Split(New [Char]() {","c, "="c})
            Dim first6 As String() = sp.ToList().GetRange(0, 6).ToArray()
            .OULocationPath= first6(5)
        End With
        _GridLocations.Add(_GridLocation)
    Next
    GetLocationList = _GridLocations
End Function


text:
Q: AWS StepFunctionsLocal StepFunctions test with definition substitutions I have been looking into StepFunctionsLocal (SFL) to test. To get a project bootstrapped, I aws the SAM cli to generate a new project - which comes pre-packed with SFL tests and a make file to run everything.
However, it seems broken out of the box. When running the tests using directions in the README, I get this error:

InvalidDefinition: An error occurred (InvalidDefinition) when calling the CreateStateMachine operation: Invalid State Machine Definition: ''SCHEMA_VALIDATION_FAILED:
Value is not a valid resource ARN at /States/Check Stock Value/Resource','SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at /States/Sell Stock/Resource', 'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at /States/Buy Stock/Resource', 'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at /States/Record Transaction/Resource''

And, indeed, the state machine definition is provided as a file that uses DefinitionSubstitutions:
{
    "Comment": "A state machine that does mock stock trading.",
    "StartAt": "Check Stock Value",
    "States": {
        "Check Stock Value": {
            "Type": "Task",
            "Resource": "${StockCheckerFunctionArn}", <--
            "Retry": [
                {
                    "ErrorEquals": [
                        "States.TaskFailed"
                    ],
                    "IntervalSeconds": 15,
                    "MaxAttempts": 5,
                    "BackoffRate": 1.5
                }
            ],
            "Next": "Buy or Sell?"
        },
...

The CloudFormation template injects those values
StockTradingStateMachine:
    Type: AWS::Serverless::StateMachine # More info about State Machine Resource: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-statemachine.html
    Properties:
      DefinitionUri: statemachine/stock_trader.asl.json
      DefinitionSubstitutions:
        StockCheckerFunctionArn: !GetAtt StockCheckerFunction.Arn <--

the makefile commands to run the test
run:
    docker run -p 8083:8083 -d \
    --mount type=bind,readonly,source=$(ROOT_DIR)/statemachine/test/MockConfigFile.json,destination=/home/StepFunctionsLocal/MockConfigFile.json \
    -e SFN_MOCK_CONFIG="/home/StepFunctionsLocal/MockConfigFile.json" \
    amazon/aws-stepfunctions-local

create:
    aws stepfunctions create-state-machine \
        --endpoint-url http://localhost:8083 \
        --definition file://statemachine/stock_trader.asl.json \
        --name "StockTradingLocalTesting" \
        --role-arn "arn:aws:iam::123456789012:role/DummyRole" \
        --no-cli-pager \
        --debug

happypathsellstocktest:
    aws stepfunctions start-execution \
        --endpoint http://localhost:8083 \
        --name HappyPathSellStockTest \
        --state-machine arn:aws:states:us-east-1:123456789012:stateMachine:StockTradingLocalTesting#HappyPathSellStockTest \
        --no-cli-pager

It appears that nothing provides the definition substitutions. I've come up dry when combing through the AWS docs for how to provide those substitutions through the API, maybe I just don't know what to look for. Any clues?
I did make an issue to fix the template: https://github.com/aws/aws-sam-cli-app-templates/issues/342

A: Unfortunately, DefinitionSubstitutions is a feature of the CloudFormation resource and not supported directly in the Step Functions API. You would need to parse and replace the substitution variables in your own code before you call Create State Machine in your test.


text:
Q: Nested comments with Laravel I'm currently trying to replicate something similar to a forum, but I'm stumped on how I could create nested comments. I understand that for regular replies I could create a replies table and run a loop for each comment that matches the thread id. But I don't know how I would easily do this for nested replies.
Could someone please give me some advice or point me in the right direction? Thanks.
This is the structure for my posts table:
Screenshot of phpMyAdmin http://bitdrops.co/drops/J5v.png

A: You want to look into polymorphic relations to solve this. You want to be able to comment on Posts and Comments.
What I have done is set up a commentable trait and have the models I want to add comments to use it. This way if you ever want to comment on another model, you can just add the trait to that model.
Laracasts is a great resource for laravel and has a good lesson on traits.
There is a bit more to it than this, but hopefully it will get you started.
You set up your database structure like this.
User Table
  `id` int(10),
  `name` varchar(255),
  `username` varchar(255)

Comments table
  `id` int(10),
  `user_id` int(10),
  `body` text,
  `commentable_id` int(10),
  `commentable_type` varchar(255)

Posts Table
  `id` int(10),
  `user_id` int(10),
  `body` text

Your models like this.
Comment Model
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

    use CommentableTrait;

    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Post Model
<?php namespace App;

use CommentableTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    use CommentableTrait;

}

and of course you need the trait.
Trait
<?php namespace App;

use Comment;

trait CommentableTrait {

    /**
     * List of users who have favorited this item
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function comments()
    {
        return $this->morphMany('App\Comments\Comment', 'commentable')->latest();
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addComment($body, $user_id)
    {

        $comment = new Comment();
        $comment->body = $body;
        $comment->user_id = $user_id;

        $this->comments()->save($comment);

        return $comment;
    }

}


text:
Q: MemoryStream and constructing an array of bytes I am using a MemoryStream to construct an array of bytes i need to send to a server.I have thre questions:
1) Is there a better way to construct an array of bytes than this ?
2) Why this pice of code writes bogus in my memory stream ?
var
  serial : word;
  MS : TMemoryStream;
const
  somebytes : array [0..1] of byte = ($72,$72);
...
begin
      MS := TMemoryStream.Create();
      try
      MS.Write(somebytes[0],2);
      serial := $3E6C;
      MS.Write(serial,2);
      finally
      MS.Free;
end;

Using the debugger i see that in the stream is added the value $6F32 instead of $3E6C.
3) If i call
MS.Position := 2;

and then i access PByte(MS.Memory)^ why do i get the first byte in the stream instead of the third?

A:
Is there a better way to construct an array of bytes than this?

That's a perfectly reasonable way to do it, in my view.

I see that in the stream is added the value $6F32 instead of $3E6C.

Check again. The correct values are in fact added. But beware of the traps of little endian data types. The 4 bytes added to your stream, in order, are: $72, $72, $6C, $3E.

Why do I get the first byte in the stream instead of the third?

Because the Memory property always refers to the beginning of the stream. It does not take account of the stream's current position.


text:
Q: determine correct place using homography matrix (AR) I use surf in emgu cv lib to detect and recgnize my object i need to insert 3d model in the place of this object i have the homography matrix what i want to know is how to get modelview matrix of sharpgl from this homography matrix .i want steps that can result me the correct modelview matrix where i can place the 3d object
any answer will help me
thanks in advance

A: Take a look at AForge.net. The author of that library did something very similar using glyphs and then inserting his own 3D model in place of the glyph. The library handles the 3d pose of the glyph and applies those to the 3d model.  The project can be found here
http://www.aforgenet.com/projects/gratf/
I dont know how you would do this same thing with Open CV and Emgu.

A: You should simply calibrate your camera using Zhang's method to get camera matrices and then use H decomposition as described in the link you found.
To sum up:

*

*Perform Classical checkboard corner detection (emgucv code here)

*Increase corner detection accuracy to subpixel level invoking FindCornerSubPix() function

*Finally use CameraCalibration.CalibrateCamera() to calculate the intrinsic camera parameters

Hope this helps


text:
Q: has_many :through and accepts_nested_attributes_for duplicating records This is a rails 3 app and it is confusing me. I have this:
class Coleta < ActiveRecord::Base
  has_many :coletas_produtos
  has_many :produtos, through: :coletas_produtos

  accepts_nested_attributes_for :produtos
end

class Produto < ActiveRecord::Base
  has_many :coletas
  has_many :coletas_produtos, through: :coletas
end

class ColetasProduto < ActiveRecord::Base
  belongs_to :produto
  belongs_to :coleta
end

When I try to save a new Coleta, I do it like this:
def create
  @coleta = Coleta.new(params[:coleta])

  respond_to do |format|
    if @coleta.save
      format.html { redirect_to(coletas_path, :notice => "Coleta cadastrada com sucesso.") }
    else
      format.html { render :action => "new" }
    end
  end
end

And this is my form:
<%= form_for(@coleta) do |f| %>
  <%= f.fields_for :produtos do |p| %>

      <%= p.label :codigo, "Código" %>

      <%= p.text_field :codigo %>

  <% end %>
<% end %>

This is working because it creates the correct records under the coletas_produtos table. My problem is that I want it to save ONLY the many-to-many relation, and not the produtos relation.
It keeps saving the records inside the produtos table along with the records on coletas_produtos. I want to ignore and keep only the latest records.
What is the best (is there a way?) way to do it?

A: Your has_many...through relationship definition needs some adjustment.
# app/models/produto.rb
class Produto < ActiveRecord::Base
  has_many :coletas_produtos
  has_many :coletas, through: :coletas_produtos
end

Please see "has_many :through" relation for proper definition.
Then in your ColetasController#new:
# app/controllers/coletas_controller.rb
def new
  @coleta = Coleta.new
  @coleta.coletas_produtos.build |cp| do
    @produto = cp.build_produto
  end
end

This will instantiate a new instance of Coleta and build all the required relationships i.e. associated coletas_produtos and produto in your new action.


text:
Q: R Count Unique By Group in DPLYR HAVE = data.frame("TRIMESTER" = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,4,4),
                  "STUDENT" = c(1,2,3,3,4,2,5,6,7,1,2,2,2,2,2,1,2,3,4,5))
HAVE$WANT1 = c(4,4,4,4,4,5,5,5,5,5,1,1,1,1,5,5,5,5,5,5)
HAVE$WANT2 = c(0,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1)

I have HAVE and wish to APPEND a column to count the UNIQUE value of STUDENT for every TRIMESTER shown WANT1 and I wish to create WANT2 which is the SUM of times for every TRIMESTER that STUDENT==5 appears so STUDENT==5 appear ZERO times in TRIMESTER == 1, so the value for all TRIMESTER == 1 is ZERO but student 5 appear ONCE in TRIMESTER==4 so the value is 1

A: The code below should produce the desired result.
library(dplyr)

HAVE %>%
  group_by(TRIMESTER) %>%
  mutate(WANT1 = length(unique(STUDENT)),
      WANT2 = as.numeric(any(5 == STUDENT)))

A: After grouping by 'TRIMESTER', get the count of distinct elements of 'STUDENT' with n_distinct and the count of STUDENT 5 with sum on a logical expression
library(dplyr)
HAVE %>%
   group_by(TRIMESTER) %>%
   mutate(WANT1new = n_distinct(STUDENT),
          WANT2NEW = sum(STUDENT == 5)) %>%
   ungroup

-output
# A tibble: 20 × 6
   TRIMESTER STUDENT WANT1 WANT2 WANT1new WANT2NEW
       <dbl>   <dbl> <dbl> <dbl>    <int>    <int>
 1         1       1     4     0        4        0
 2         1       2     4     0        4        0
 3         1       3     4     0        4        0
 4         1       3     4     0        4        0
 5         1       4     4     0        4        0
 6         2       2     5     1        5        1
 7         2       5     5     1        5        1
 8         2       6     5     1        5        1
 9         2       7     5     1        5        1
10         2       1     5     1        5        1
11         3       2     1     0        1        0
12         3       2     1     0        1        0
13         3       2     1     0        1        0
14         3       2     1     0        1        0
15         4       2     5     1        5        1
16         4       1     5     1        5        1
17         4       2     5     1        5        1
18         4       3     5     1        5        1
19         4       4     5     1        5        1
20         4       5     5     1        5        1


text:
Q: Disable swiperefreshlayout and scrollview when interacting with a map fragment I currently have the following layout high level layout
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="81dp">

            ...

            <FrameLayout
                android:id="@+id/location_container"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView3"
                app:layout_constraintVertical_bias="0.0">

                <fragment
                    android:id="@+id/fragment_location"
                    android:name="com.nissanshare.vehicleinfo.VehicleLocationFragment"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="8dp"
                    android:tag="fragment_vehicleInfo"
                    tools:layout="@layout/fragment_vehicle_info_location" />

                <View
                    android:id="@+id/transparent_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@android:color/transparent" />
            </FrameLayout>

            ...

        </android.support.constraint.ConstraintLayout>
    </ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>

And in my code I have the following method
mTouchInterceptor is the transparent_view in the layout
private void setupTouchInterceptor() {
        mTouchInterceptor.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        Log.d(TAG, ".onTouch:DOWN");
                        // Disallow ScrollView to intercept touch events.
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    case MotionEvent.ACTION_UP:
                        Log.d(TAG, ".onTouch:UP");
                        // Allow ScrollView to intercept touch events.

                        mScrollView.requestDisallowInterceptTouchEvent(false);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(false);

                        return true;

                    case MotionEvent.ACTION_MOVE:
                        Log.d(TAG, ".onTouch:MOVE");
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                        mSwipeRefreshLayout.requestDisallowInterceptTouchEvent(true);

                        return false;

                    default:
                        return true;
                }
            }
        });
    }

This is the same code I use when just using scrollview without the SwipeRefreshLayout and it works flawlessly. However when adding the SwipeRefreshLayout, it seems that it doesn't respect the call to requestDisallowInterceptTouchEvent. How do I prevent the SwipeRefreshLayout from refreshing when interacting with the map.

A: Simply had to change ScrollView to android.support.v4.widget.NestedScrollView.


text:
Q: Displaying Salesforce Data in Cloud Pages Error I am trying to fetch salesforce contact details and display it in Cloud Pages. However its throwing an 500 error.
When I try with an Update Salesforce AMPScript, it works fine. What am I doing wrong?
%%[
VAR @SubKey, @result, @rs1 , @FirstName , @LastName , @row
Set @SubKey = [_subscriberKey]
SET @result = UpdateSingleSalesforceObject("Contact",@SubKey,"Membership_Type__c","Gold")

SET @rs1 = RetrieveSalesforceObjects("Contact", " FirstName,LastName","Id" , "=", @SubKey)
If RowCount(@rs1) > 0 Then
  Set @row = ROW(@rs1,1)
  Set @FirstName = FIELD(@row,"FirstName")
  Set @LastName = FIELD(@row,"LastName")

]%%
FirstName
 %%=v(@FirstName)=%%

LastName
 %%=v(@LastName)=%%


text:
Q: How to pass data to Mat-Menu from parent button? I'm building a component that displays menus by the following array
names = [{name:'John'}, {name:'Bill'}, {name:'Dan'}];

So i by iterating the array -  will get 3 menus - like here :

What i need to be able to do is to display for each menu it's "name" , so instead of "My Name" - it should displays each of the names in the array (John, Bill, Dan)....
I know i could be done by using the [matMenuTriggerData] directive - but i can't understand how to implement it....
Example


text:
Q: IEEE754 Numbers In which cases is n + 0 not equal to n where n is a number (in the IEEE754 standard, or more precise a double-precision floating-point number/64 Bit float)?
So where:
function isNotSame(n: number) {
  return n + 0 !== n;
}

Does return true.
For example:

function isNotSame(n) {
  return n + 0 !== n;
}

console.log(isNotSame(Number.NaN));

Returns true;

A: -0 if you use Object.is to compare:
Object.is(-0 + 0, -0)
//=> false

NaN if:
NaN + 0 === NaN
//=> false

But:
Object.is(NaN + 0, NaN)
//=> true


text:
Q: Is it possible to reuse a task in two different spots in a Luigi pipeline? I am developing a Luigi pipeline and am running into a major problem. There doesn't seem to be any way to reuse tasks in the same pipeline.
To illustrate what I am after, consider the following workflow:
Collect_Data → Clean_data → Task_on_data_A → Task_on_data_B
                     ↳ Sample_data → Task_on_data_A → Task_on_data_B

I perform the same operations on Clean_data and Sample_data. I want to do something like this in Luigi while following DRY principles. Right now it seems like I have to literally copy and paste my code for tasks A and B to do this.
Airflow has a way to deal with situations like this. Does Luigi?

A: I think you should draw the arrows as dependency arrows going the other way. It helps to think about it this way since the execution path is determined by the requires methods. In your scenario, it is very simple because you just have a TaskA that has a conditional dependency.
You just need to add one more task at the start that depends on two TaskBs and an indicator of whether the taskb is to be run on the sample
Pseudocode:
ParentTask
  def requires():
     return [TaskB(sample_type=True),
             TaskB(sample_type=False)]

TaskB
  def requires():
    return TaskA(sample_type)

TaskA
  def requires():
    if sample_type:
      return SampleTask()
    else:
      return CleanTask()

SampleTask
  def requires():
    return CleanTask()

CleanTask
  def requires()
    return CollectData()


text:
Q: Django 3.0.4 compatibility with Six package I am using Django 2.2.10 for my app. I am trying to bump it up to Django 3.0.4. But it's throwing me this error:
ImportError: cannot import name 'six' from 'django.utils' (C:\Users\hkhatri\Desktop\capstone\fitgirl-inc\env\lib\site-packages\django\utils__init__.py)
I already have six==1.14.0 installed. Can someone please help on how to upgrade my Django version from 2.2.10 to 3.

A: I haven't seen the rest of your code and not sure how you're using six but this is how I'm using six in Django 3:

*

*You want to install Six with pip

*Add it to your apps in settings

*Then import it in your model import six

*...six.PY3......


text:
Q: Class with dynamic_attr() cannot pass __dict__ to the external scope Reproducible example code
My c++ code is very simple:
struct A
{
    A()
    {
        this->a = 0;
    }
    py::int_ a;
};

struct B
{
    B() {}
    A sa;
};

PYBIND11_MODULE(libdemo_ext, m)
{
    py::class_<A>(m, "A", py::dynamic_attr())
        .def(py::init<>())
        .def_readwrite("a", &A::a);
    py::class_<B>(m, "B", py::dynamic_attr())
        .def(py::init<>())
        .def_readwrite("sa", &B::sa);
}

When I use it in python like this:
def func(b):
    sa = b.sa
    sa.pa = 'hello'

b = B()
func(b)
print(b.sa.pa)

and result is:
Traceback (most recent call last):
  File "demo.py", line 12, in <module>
    print(b.sa.pa)
AttributeError: 'libdemo_ext.A' object has no attribute 'pa'

But if I use it like this:
def func(b):
    sa = b.sa
    sa.pa = 'hello'

b = B()
sa = b.sa
func(b)
print(b.sa.pa)

everythis is ok.
I have A class with dynamic_attr, And B class with dynamic_attr and A object.
But I cannot trans A's dynamic feature by B.

A: pybind11 tracks bound objects and reuses them if the type and C++ address match. That's why the second case works. I do not know the exact use case that you are describing, but if the attribute is always added in a function, then you can make sure the reference stays alive by tying it to the lifetime of the 'b' object. Example:
def func(b):
    b._sa = b.sa
    b.sa.pa = 'hello'

or:
def func(b):
    sa = b.sa
    b.__dict__['sa'] = sa
    sa.pa = 'hello'

If you have many objects of type 'A', the second approach will be more efficient.


text:
Q: TopShelf windows service memory leak while update information from sql I have a windows service with prepared topshelf.This project send request web service and response xml data.After that this xml data serialize list objects and than these objects update information from sql.When Start service about 8 mb after that increase 1.8 gb memory out of range exception.Why ?
 public class HostService
{

    private readonly Timer _updaterThread;
    private readonly object _lockObject;
    private readonly Manager _manager;
    public HostService()
    {
        _manager = new Manager();
        _lockObject = new object();
        var interval = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateInterval"]);
        _updaterThread = new Timer(interval) { AutoReset = true };
        _updaterThread.Elapsed += UpdateInfo;
    }

    public void Start()
    {
        try
        {
            LoadLogger();
            _updaterThread.Start();

        }
        catch (Exception e)
        {
            FXEventLogger.Instance().AddLog(EventLogEntryType.Error, e);
        }
    }

    private void UpdateInfo(object state, EventArgs ev)
    {
        lock (_lockObject)
        {
            _manager.UpdateFmdProductions();
        }
    }

    public void Stop()
    {
        try
        {

            _updaterThread.Stop();
            FXEventLogger.Instance().AddLog(EventLogEntryType.SuccessAudit, "Service stopped");
            FXEventLogger.Finalize();
        }
        catch (Exception e)
        {
            FXEventLogger.Instance().AddLog(EventLogEntryType.Error, e);
        }
    }

A: **UpdateFmdProductions() make two process First **
`public class SmdStatusProvider
    {
    public List<MakerInfo> GetMakersInfo()
    {
        SMDStatusServiceClient requester = null;
        try
        {
            requester = new SMDStatusServiceClient();

            var response = requester.Request("//MachineStatus[@MachineType='MAKER']/ShiftStatus");

            return ParseMakersInfo(response);
        }
        catch (Exception e)
        {
            FXEventLogger.Instance().AddLog(EventLogEntryType.Error, e);

            return null;
        }
        finally
        {
            requester.Close();
            GC.SuppressFinalize(this);
        }
    }

    private List<MakerInfo> ParseMakersInfo(string shiftStatesXml)
    {
        using (var sr = new StringReader(shiftStatesXml))
        {
            var serializer = new XmlSerializer(typeof(List<MakerInfo>), new XmlRootAttribute("result"));

            var _makersInfo = (List<MakerInfo>) serializer.Deserialize(sr);

            sr.Dispose();

            return _makersInfo;
        }
    }
}`

public class FMDRepository : SqlServerClient
    {
    public FMDRepository(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public bool UpdateRealProductions(IEnumerable<MakerInfo> makersInfo)
    {
        if (makersInfo == null) return false;

        OpenConnection();

        foreach (var makerInfo in makersInfo)
        {
            var success = ExecuteNonQuery(
                  String.Format("UPDATE [Shooter] SET [RealProduction]={0}, [LastUpdate]='{1:yyyy-MM-dd HH:mm:ss}' WHERE [Machine]='{2}'",
                      Math.Round(makerInfo.RealProduction, 0), DateTime.Now,
                      makerInfo.Machine));
            if (success == -1)
            {
                CloseConnection();
                return false;
            }
        }
        CloseConnection();
        return true;
    }
}


text:
Q: Advanced Dojo query store = Observable(new Memory({data: data}));

chart.addSeries("Load Cell 0", new StoreSeries(store, { query: { load_cell_id:0 }}, "kn"));

How would I go about doing a more advanced query with the Store Series?
For the above i need all 'load_cell_id = 0' and 'date_time < 12345' or other time stamp.
At the moment i can only get load_cell_id:0 to work.

A: As with dojo/store/Memory you can use a function as a query (source):
store.query(function(product){
    return product.price < 10;
}).forEach(function(shoe){
    // called for each match
});

See my answer to Is it possible to filter data in a dgrid like you can in a datagrid? for more complex example. Alternatively, in the case you need bad ass querying, there is Resource Query Language as I mentioned in the answer to How to query a dgrid on multiple columns (example code here).


text:
Q: Some consequences of the Baire Category Theorem I read there are some consequences of the Baire Category Theorem in "The Integrals of Lebesgue, Denjoy, Perron, and Henstock" by Russel. A. Gordon. The statement is

Corollary 5.3. Let $E$ be a non-empty closed set and let $(E_k)$ be a sequence of sets such that $E=\bigcup_{k\in\mathbb{N}} E_k$.
(a) If each $E_k$ is closed, then there exist a portion o$E\cap I$ of $E$ and a positive integer $p$ such that $E\cap I\subseteq E_p$.
(b) If each $E_k$ is an $F_\sigma$ set, then there exist a portion o$E\cap I$ of $E$ and a positive integer $p$ such that $E\cap I\subseteq E_p$.

Note: A portion of a set $E$ is a nonempty set of the form $E \cap I$ where $I$ is an open
interval.
Statements (a) and (b) are quite similar. The difference is only on "each $E_k$ is closed" and "each $E_k$ is an $F_\sigma$ set".
I have proved statement (a). Then, I found in Wikipedia, it is stated that each closed set is an $F_\sigma$ set.
So, is it enough to prove statement (a) only, because each closed set is an $F_\sigma$ set, so that statements (a) and (b) are the same.
Or I should prove statement (b) by using statement (a)?
Thanks for any advice.


text:
Q: How to publish Unity APK to Play store? Signed in debug mode? I am very new to Android (Im an apple person) and am trying to build my Unity project for Android to be uploaded to google play store. I've followed all the tutorials and directions from Unity AND google but am having trouble. In desperate need of help.
I've built my project both as an APK and then as a Google Android Project which created a folder on my desktop which i've opened in Android Studio. I've registered as a developer and read up on licensing.
When I try to upload my APK to Google play I get the error my project was signed in debug mode and needs to be in release mode; I've looked at other questions but can't understand how to sign it in release mode. How can I do this exactly?
I don't understand what a Keystore is and saw this under Publish Settings in Unity. Is this related to signing? I have my license key from Google play but this does not work when I enter this as my Keystore.
I do not have an Android device.
How can I upload my APK from Unity to the Google play store?

A: The solution to this is pretty simple, open the MonoDevelop IDE and you would see that your IDE is is Debug mode (Refer the screenshot below).
enter image description here
Change it to Release mode. Try building the app again and upload this new apk to the play store, it should upload all fine this time.

A: You can build and sign an APK directly from Unity. This link might help:https://www.youtube.com/watch?v=6xsjB4pbnnA

A: You got to sign the application at android you create something similar to provisioning [profiles by yourself. You need to go Player settings>Publish settings>Create new keystore. Once you have created that you will require a create a key after you did all that make a build now you will be able to upload to google play


text:
Q: How to trace traffic to GCP kubernetes Services How to trace traffic of GCP kubernetes service? I would like to see who access the service and volume of traffic.

A: Make sure your service that is exposing your pods is configured with externalTrafficPolicy: local to ensure that requests that reach you pod maintain their clientIP.
Next, ensure your application logs incoming connections (nginx does this by default).
Ensure that you have logging enabled (either stackdriver or a 3rd party tool like ELK) so that you can export the logs (the k8s cluster won't hold the container logs for very long).
If you are using Stackdriver, you can then create a log-based metric based off of the logs you collected. As long as you collect the logs by container, the metric should aggregate logs from each of your pods. You can then use Stackdriver Monitoring to watch the network load the pods receive and Stackdriver Logging to review the source IPs of the requests.
If you can't get your application to log connections, an alternative would be to create a DaemonSet that runs a TCPdump to stream connections to your service (how you configure this sepcifically will depend on which service you are using).


text:
Q: MERGE Constraint Error on self referenced table MERGE is raising an Error
ORA-02291: integrity constraint violated-parent key not found

on inserting into a self referenced table.
If I change query a little bit with no matter, it will work.
Am I do something wrong.
Execution order:

*

*Preparement stuff

*First MERGE query (will not work)

*Second MERGE query (will work)

The order of the columns in the MERGE query does not matter. You also can run the second MERGE before first.
If you would like to restart your test, start at DROP TABLE TGR.
First some preparement:
DROP TABLE SRC;
CREATE TABLE SRC (
  ID VARCHAR(20) PRIMARY KEY,
  PARENT VARCHAR(20)
);

INSERT INTO SRC SELECT '1', null FROM DUAL;
INSERT INTO SRC SELECT '2', '1' FROM DUAL;

DROP TABLE TRG;
CREATE TABLE TRG (
  ID VARCHAR(20) PRIMARY KEY,
  PARENT VARCHAR(20),
  CONSTRAINT FK2 FOREIGN KEY(PARENT) REFERENCES TRG(ID)
);

This will not work:
MERGE INTO TRG t USING(
  SELECT PARENT, ID FROM SRC
) s ON (t.ID=s.ID)
WHEN NOT MATCHED THEN INSERT(ID,PARENT) VALUES (s.ID,s.PARENT);

But this will work.
MERGE INTO TRG t USING(
  SELECT ID, PARENT FROM SRC
) s ON (t.ID=s.ID)
WHEN NOT MATCHED THEN INSERT(ID,PARENT) VALUES (s.ID,s.PARENT);

If you change the datatype of these columns to NUMBER, it will work.
DROP TABLE SRC;
CREATE TABLE SRC (
  ID NUMBER PRIMARY KEY,
  PARENT NUMBER
);

INSERT INTO SRC SELECT 1, null FROM DUAL;
INSERT INTO SRC SELECT 2, 1 FROM DUAL;

DROP TABLE TRG;
CREATE TABLE TRG (
  ID NUMBER PRIMARY KEY,
  PARENT NUMBER,
  CONSTRAINT FK2 FOREIGN KEY(PARENT) REFERENCES TRG(ID)
);

MERGE INTO TRG t USING(
  SELECT PARENT, ID FROM SRC
) s ON (t.ID=s.ID)
WHEN NOT MATCHED THEN INSERT(ID,PARENT) VALUES (s.ID,s.PARENT);

Edit:
Forgot to tell: I am using 12c


text:
Q: Get the attachment file size in SharePoint list items - PnP Powershell I need to get the file size of each of the attachments in a SharePoint List using PnP Powershell scripting. I am able to get the attachments' file names, but not the file size.

A: For file class in CSOM, you can use the length Property to estimate the file size.
PnP seems not to have property on file size.
An example here for your reference:https://www.sharepointdiary.com/2019/05/sharepoint-online-get-attachments-from-list-using-powershell.html


text:
Q: Change propagation among connections If I update a table using one connection and issue a query in another connection immediately after that, is there a chance that I can't see the changes even if it's extremely unlikely?

A: If the first transaction has committed and the second transaction started after the first one committed (more accurately, it obtained its snapshot after the first one committed), then everything that the first transaction wrote will be visible to the second one.


text:
Q: Resource is not supported in this region cloudformation EFSFileSystem I've encountered following error message in AWS CloudFormation about EFSFileSystem.
  EFSMountTargetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref 'VPC'
      GroupDescription: Security group for mount target
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '2049'
        ToPort: '2049'
        CidrIp: 0.0.0.0/0
  EFSFileSystem:
    Type: AWS::EFS::FileSystem
    Properties:
      PerformanceMode: generalPurpose
  EFSMountTargetA:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataA'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']
  EFSMountTargetB:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataB'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']

Please let me know how to use EFSFileSystem or replace in that region?

A: AWS Elastic File System is not currently available in Mumbai, Hong Kong, Beijing, Ningxia, Osaka, Paris or Stockholm.  I can't tell from your CloudFormation snippet if you're trying to deploy in one of those regions.
References
AWS Regional Product Services


text:
Q: How can I remove AutoNumeric formatting before submitting form? I'm using the jQuery plugin AutoNumeric but when I submit a form, I can't remove the formatting on the fields before POST.
I tried to use $('input').autonumeric('destroy') (and other methods) but it leaves the formatting on the text fields.
How can I POST the unformatted data to the server? How can I remove the formatting? Is there an attribute for it in the initial config, or somewhere else?
I don't want to send the serialized form data to the server (with AJAX). I want to submit the form with the unformatted data like a normal HTML action.

A: Inside data callback you must call getString method like below:
        $("#form").autosave({
        callbacks: {
            data: function (options, $inputs, formData) {

                return $("#form").autoNumeric("getString");
            },
            trigger: {
                method: "interval",
                options: {
                    interval: 300000
                }
            },
            save: {
                method: "ajax",
                options: {
                    type: "POST",
                    url: '/Action',
                    success: function (data) {

                    }
                }
            }
        }
    });

A: I wrote a better, somewhat more general hack for this in jQuery
$('form').submit(function(){
    var form = $(this);
    $('input').each(function(i){
        var self = $(this);
        try{
            var v = self.autoNumeric('get');
            self.autoNumeric('destroy');
            self.val(v);
        }catch(err){
            console.log("Not an autonumeric field: " + self.attr("name"));
        }
    });
    return true;
});

This code cleans form w/ error handling on not autoNumeric values.

A: With newer versions you can use the option:
unformatOnSubmit: true

A: Use the get method.

'get' | returns un-formatted object via ".val()" or
  ".text()" | $(selector).autoNumeric('get');

<script type="text/javascript">
    function clean(form) {
        form["my_field"].value = "15";
    }
</script>

<form method="post" action="submit.php" onsubmit="clean(this)">
    <input type="text" name="my_field">
</form>

This will always submit "15". Now get creative :)

Mirrored raw value:
<form method="post" action="submit.php">
    <input type="text" name="my_field_formatted" id="my_field_formatted">
    <input type="hidden" name="my_field" id="my_field_raw">
</form>

<script type="text/javascript">
    $("#my_field_formatted").change(function () {
        $("#my_field").val($("#my_field_formatted").autoNumeric("get"));
    });
</script>

The in submit.php ignore the value for my_field_formatted and use my_field instead.

A: You can always use php str_replace function
str_repalce(',','',$stringYouWantToFix);

it will remove all commas. you can cast the value to integer if necessary.

A: $("input.classname").autoNumeric('init',{your_options});
$('form').submit(function(){
   var form=$(this);
   $('form').find('input.classname').each(function(){
       var self=$(this);
       var v = self.autoNumeric('get');
       // self.autoNumeric('destroy');
       self.val(v);
   });
});

classname is your input class that will init as autoNumeric
Sorry for bad English ^_^

A: There is another solution for integration which doesn't interfere with your client-side validation nor causes the flash of unformatted text before submission:
var input = $(selector);
var proxy = document.createElement('input');
proxy.type = 'text';
input.parent().prepend(proxy);
proxy = $(proxy);
proxy.autoNumeric('init', options);
proxy.autoNumeric('set', input.val())''
proxy.change(function () {
    input.val(proxy.autoNumeric('get'));
});

A: You could use the getArray method (http://www.decorplanit.com/plugin/#getArrayAnchor).
$.post("myScript.php", $('#mainFormData').autoNumeric('getArray'));

A: I came up with this, seems like the cleanest way.
I know it's a pretty old thread but it's the first Google match, so i'll leave it here for future
$('form').on('submit', function(){
    $('.curr').each(function(){
        $(this).autoNumeric('update', {aSign: '', aDec: '.', aSep: ''});;
    });
});

A: Solution for AJAX Use Case

I believe this is better answer among all of those mentioned above, as the person who wrote the question is doing AJAX. So
kindly upvote it, so that people find it easily. For non-ajax form submission, answer given by @jpaoletti is the right one.

// Get a reference to any one of the AutoNumeric element on the form to be submitted
var element = AutoNumeric.getAutoNumericElement('#modifyQuantity');

// Unformat ALL elements belonging to the form that includes above element
// Note: Do not perform following in AJAX beforeSend event, it will not work
element.formUnformat();

$.ajax({
    url: "<url>",
    data : {
        ids : ids,
        orderType : $('#modifyOrderType').val(),

        // Directly use val() for all AutoNumeric fields (they will be unformatted now)
        quantity : $('#modifyQuantity').val(),
        price : $('#modifyPrice').val(),
        triggerPrice : $('#modifyTriggerPrice').val()
    }
})
.always(function(  ) {
    // When AJAX is finished, re-apply formatting
    element.formReformat();
});

A: autoNumeric("getArray") no longer works.
unformatOnSubmit: true does not seem to work when form is submitted with Ajax using serializeArray().
Instead use formArrayFormatted to get the equivalent serialised data of form.serializeArray()
Just get any AutoNumeric initialised element from the form and call the method. It will serialise the entire form including non-autonumeric inputs.
$.ajax({
    type: "POST",
    url: url,
    data: AutoNumeric.getAutoNumericElement("#anyElement").formArrayFormatted(),
)};


text:
Q: Installing boost on 12.04- have ran "sudo apt-get install libboost-all-dev"- now what? I want to install the boost libraries on Ubuntu 12.04 so I ran:
sudo apt-get install libboost-all-dev

but now searching for a folder named "boost" I cannot seem to find where the files have been installed? Do I have to run some sort of bjam command now or something? I am expecting to see some sort of boost folder hierarchy and then all the header and source files for the boost libraries?

A: Boost header files are in /usr/include/boost.
When you install libboost-all-dev, a number of other specific packages are installed as dependencies.
These packages' also provide libraries and headers through an indirect mechanism. They declare packages with version numbers in their names as dependencies, and those packages are the ones that actually contain the library binaries and header files.
For example, libboost-dev is one of the packages installed as a dependency of libboost-all-dev.
libboost-dev declares just one package as a dependency. In 12.04, this package is libboost1.46-dev
libboost1.46-dev has dependencies too but its main purpose is to provide files directly. You can see these in its file list.
Boost header files have a .hpp extension. (Note that just .h is common for most other C++ libraries.) Many .hpp files are listed in libboost1.46 -dev's file list:
/usr/include/boost/accumulators/accumulators.hpp
/usr/include/boost/accumulators/accumulators_fwd.hpp
/usr/include/boost/accumulators/framework/accumulator_base.hpp
/usr/include/boost/accumulators/framework/accumulator_concept.hpp
  ....
/usr/include/boost/algorithm/minmax.hpp
/usr/include/boost/algorithm/minmax_element.hpp
/usr/include/boost/algorithm/string.hpp
/usr/include/boost/algorithm/string/case_conv.hpp
  ....
/usr/include/boost/aligned_storage.hpp
/usr/include/boost/any.hpp
/usr/include/boost/archive/add_facet.hpp
/usr/include/boost/archive/archive_exception.hpp
/usr/include/boost/archive/basic_archive.hpp
  ....

...and so forth.
You'll notice all those files are inside /usr/include/boost.

To find this information, I used packages.ubuntu.com, the online Ubuntu packages database.
People interested in finding specific information about what files are provided by Boost packages in their Ubuntu release, what packages provide them, and where they will be located on disk once installed can find that there.
Or, to get you started, here's a query that shows the libboost-all-dev package entries for all currently supported Ubuntu releases (and several others).
I got that by searching under Search package directories, changing Distribution to "any," and using libboost-all-dev as the search keyword.


text:
Q: Reaching the spesific string Is there any method that I can reach a specific token in a string? In my code, I used strtok() for the parsing the string token by token but I need to reach the first token, second token, third token etc... to matching each token in a variable (for example, if the first token variable is A then it should be equal to y, if the second token variable is z then it should be equal to w)
Here is my code. There will be some mistakes in my code, sorry for that:

    char parsetokens(){
    char string[]="A B(10) < z3";
    char specialchar[] = ":,=+-*/><[]() ";
    char *token = strtok(string,specialchar);

    while (token!=NULL)
    {
        printf ("%s\n", token);
        token = strtok (NULL, specialchar);
    }
for(token=string[0];*token!=0;token++){
    if (token==y)
    {
         var.op=5; //I want to match the first token's variable which is A to the y
    }
    printf ("%s\n",var.op);
}
}  ```

A: This could be a starting point :
int main() {
    char * token = ":,=+-*/><[]()";
    char * string = "A : B : C + D - E << (F)";
    int index;
    int len = strlen(string);
    int tokenCount = strlen(token);
    char tk[2] = {0};
    for (char i=0; i<tokenCount; i++) {
        index = 0;
        tk[0] = token[i];
        char *sub = NULL;
        while (index < len && (sub = strstr(string + index, tk))) {
            index = (sub - string);
            printf("%s at index : %d\n", tk, index);
            index++;
        }
    }
    return 0;
}

Output :
: at index : 2
: at index : 6
+ at index : 10
- at index : 14
< at index : 18
< at index : 19
( at index : 21
) at index : 23

A: strspn and strcspn can be used to iterate through a string and identify tokens delimited by a set of characters.
#include <stdio.h>
#include <string.h>

int main ( void) {
    char string[]="[A B[x:y] > Z] ";
    char specialchar[] = ":,=+-*/><[]() ";
    char *token = string;
    size_t index = 0;

    while ( *token) {
        token += strspn ( token, specialchar);//count matching characters
        index = strcspn ( token, specialchar);//count non-matching characters
        if ( index) {
            printf ("%.*s at index %d\n"
            , (int)index, token, (int)(token - string));
        }
        token += index;
    }
}

EDIT:
#include <stdio.h>
#include <string.h>

int main ( void) {
    char string[]="[A B[x:y] > Z] ";
    char item[sizeof string] = "";
    char specialchar[] = ":,=+-/*><[]() ";
    char *token = string;
    size_t index = 0;

    while ( *token) {
        token += strspn ( token, specialchar);//count matching characters
        index = strcspn ( token, specialchar);//count non-matching characters
        if ( index) {
            memmove ( item, token, index);
            item[index] = 0;
            printf ("item: %s\n", item);
            printf ("%.*s at index %d\n"
            , (int)index, token, (int)(token - string));
        }
        token += index;
    }
}


text:
Q: Not quite understanding parts of Pigeon Hole Principle Generalization Q
Suppose that I place n items into k boxes. What is the largest number m such that I can be guaranteed that one of the boxes contains at least m items?
First off, I'm not completely understanding the question. "The largest number m such that I can be guaranteed that one of the boxes contains at least m items?" The largest number m? Why the largest? If you have at least m items, how can it be the largest?
A
Bogus solution: we can put $\frac{n - 1}{k}$ balls into each of the k boxes. This accounts for $k (\frac{n - 1}{k}) = n - 1$ of the balls. There is 1 ball left over, which must go in some box, and thus some box must contain at least $\frac{n - 1}{k} + 1$ balls. Seems reasonable, and works with n = 25 and k = 6. So why is this not quite correct?
The problem is that $\frac{n - 1}{k}$ might not be an integer. The best we can do in out initial step is to put $\lfloor{\frac{n - 1}{k}}\rfloor$ balls in each box. Then our leftover ball(s) ensure that at least on box will have $\lfloor{\frac{n - 1}{k}}\rfloor + 1$ balls.
What I'm not understanding here, is why $n - 1$ is used in $\lfloor{\frac{n - 1}{k}}\rfloor$. I can see that it doesn't always work with n or $n - 2$, but what is it about $n - 1$ that makes it work? Is it so that you can say that at least one box has at least m balls?
Also, let's say that I have 7 balls and 5 boxes. The pigeonhole principle works when you put each ball in a box, not when you put all balls in one box (or am I wrong?) My question is, after 5 balls have been put into 5 boxes, and we have two balls left, do the two leftover balls also still need to be distributed, or can I put the two balls into one box?
Because the generalized Pigeonhole Prinicple states that: if we place n balls into k boxes, then at least one box must contain at least $\lfloor \frac{n - 1}{k} \rfloor + 1$ balls.
In the case of 7 balls and 5 boxes, this seems to imply to me that the two leftover balls can be deposited in one box. If we place 7 balls into 5 boxes, then at least one box must contain at least $\lfloor \frac{7 - 1}{5} \rfloor + 1 = 2$ balls. This statement would therefore also be true if one box contains 3 balls.

A: The (strong) pigeonhole principle says that, whatever way I choose to distribute $n$ items into $k$ boxes, at least one box will have at least $\lceil \frac{n}{k} \rceil$ items. (note that $\lceil \frac{n}{k} \rceil = \lfloor \frac{n-1}{k} \rfloor +1$)
First of all, in general, you can put the items into the boxes any way you like. For example, if you put all of the items into one box, then you will have one box with $n$ items. This agrees with what is predicted by the pigeonhole principle, which gives the more modest bound of at least one box with at least $\lceil \frac{n}{k} \rceil$ items.
However, the way to "test" the principle, i.e. to have a placement of items in which the box with the most items contains as few items as possible, is to distribute the items as evenly as possible into the boxes.
Second, I don't see the point of this convoluted "bogus solution" that you present. The way I like to think about it is the following: Suppose that I distribute all $n$ items into the $k$ boxes in an arbitrary manner. If, in the end, every box contains strictly less than $\lceil \frac{n}{k} \rceil$ items (therefore, at most $\lceil \frac{n}{k} \rceil -1$ items), then the total number of items would be at most $k\cdot(\lceil\frac{n}{k}\rceil-1)$, which is, as can be easily verified, strictly smaller than $n$. This is a contradiction because I assumed that I distributed all items. Therefore, for every placement, there is at least one box with at least $\lceil \frac{n}{k} \rceil$ items.
Finally, the question, as stated, does make sense once you're used to seeing questions phrased like this. An alternative way to phrase it would be: For every placement $P$, let $\mathrm{fullest}(P)$ be the number of items in the fullest box. What is the largest $m$ such that
$$\min_P \mathrm{fullest}(P) \geq m \enspace,$$ where $P$ ranges over all possible placements of $n$ items into $k$ boxes?

Example: Let us represent placements as lists of numbers, indicating how many items are in each box. If $n=7$ items and $k=5$ boxes, then a possible placement is $P_1=(7,0,0,0,0)$, another possible placement is $P_2=(1,0,4,1,0)$, and yet another possible placement is $P_3=(2,1,2,1,1)$. Now, using the notation above, $\mathrm{fullest}(P_1)=7$, $\mathrm{fullest}(P_2)=4$, and $\mathrm{fullest}(P_3)=2$.
There are many other possible placements, but the pigeonhole principle says that however long you try, you will never find a placement whose "fullest" value is strictly less than $2=\lceil\frac{7}{5}\rceil$. In other words, if $P$ is any placement of $7$ items into $5$ boxes, then the pigeonhole principle guarantees that $\mathrm{fullest}(P) \geq 2 = \lceil\frac{7}{5}\rceil$.

A: To be honest I find that the presented solution to problem doesn't really make a lot of sense;
Hopefully this proof sounds more reasonable to you:
Let's suppose $n\ge 1$. You want to put these $n$ balls into $k$ holes. The problem is asking the biggest number of balls that at least one hole contains no matter which way you choose to distribute the balls.

Lemma: Now, suppose that there is an integer $s\ge 0$ such that $n\ge sk+1$ (we know at least one such $s$ exists, namely $0$). We claim that, no matter the way you distribute the balls, at least one hole must contain more than $s$ balls.

Proof: Suppose we could distribute the balls so that every hole contains at most $s$ balls. Then this would mean $n\le sk$ since each hole contain at most $s$ balls and there are $k$ holes, contradicting $n\ge sk+1$.
Note that this proof is essentially a rather formalised version of intuitive proof; if you have $n\ge sk+1$ and try to put at most $s$ balls into each hole, in the end you will have $k$ holes filled with $s$ balls in each of them but you will still have some more balls to put into them, so at least one of the holes contain more than $s$ balls.

Now observe that, since $n$ is fixed natural number, then the set $S=\{s\ge 0:n\ge sk+1\}$ is non empty ($0\in S$) and bounded above. Since $S$ is finite, then $m=\max_{s\in S} s$ exists, and is a maximum integer such that $$n\ge mk+1\implies \frac{n-1}{k}\ge m$$
That is, $m=\left\lfloor\frac{n-1}{k}\right\rfloor$.
But from our earlier lemma, $m$ is the maximal number such that no matter how we distribute balls, at least one hole contains more than $m$ balls. That is, $m$ is maximal number of balls such that one of the holes contain at least $m+1$ balls.
So answer to original question is $$m+1=\left\lfloor\frac{n-1}{k}\right\rfloor+1$$


text:
Q: How to prove that the following sum converge Assume $a_n $ is a sequence such that $a_n >0 $ for all $n\in\mathbb{N} $, Such that $ \sum_{n=1}^{\infty}a_{n} $ diverge.
How can I prove that $$ \sum_{n=1}^{\infty}\frac{a_{n}}{S_{n}^{2}} $$
converge, where $ S_{n}=\sum_{k=1}^{n}a_{k} $  The partial sum sequence.
I tried to use cauchy criteria, i.e, given $\varepsilon >0$, I want to prove that there exists $N $ such that for any $n_1 , n_2 $, we have $ \sum_{n=n_{1}}^{n_{2}}\frac{a_{n}}{S_{n}^{2}} < \varepsilon $.
So
$$ \sum_{n=n_{1}}^{n_{2}}\frac{a_{n}}{S_{n}^{2}}\leq\frac{1}{S_{n_{1}}}\sum_{n=n_{1}}^{n_{2}}\frac{a_{n}}{S_{n}}\le\frac{1}{S_{n_{1}}}\left(\frac{a_{n_{1}}}{a_{1}+...+a_{n_{1}}}+\frac{a_{n_{1}+1}}{a_{1}+...+a_{n_{1}+1}}+...+\frac{a_{n_{2}}}{a_{1}+...+a_{n_{2}}}\right)\leq\frac{1}{S_{n_{1}}}\left(\frac{a_{n_{1}}+...+a_{n_{2}}}{a_{1}+...+a_{n_{1}}}\right) $$
$$ =\frac{1}{S_{n_{1}}}\left(1+\frac{a_{n_{1}}+...+a_{n_{2}}}{a_{1}+...+a_{n_{1}}}\right) $$
But I'm not sure how to continue.

A: Hint :
$$\frac{a_n}{S_n^2} \leq \frac{S_n-S_{n-1}}{S_n S_{n-1}} = \frac{1}{S_{n-1}} - \frac{1}{S_n}$$

A: The convergence follows from
$$\sum_{n = 2}^m\frac{a_n}{S_n^2} \leq \sum_{n = 2}^m \frac{a_n}{S_n S_{n - 1}} = \sum_{n = 2}^m \left(\frac 1{S_{n - 1}} - \frac 1{S_n}\right) < \frac 1{S_1}.$$
Thus the infinite sum $\sum_{n = 1}^\infty \frac{a_n}{S_n^2}$ is bounded from above. Since all summands are positive, the series converges.
Note that it doesn't matter whether $\sum_{n = 1}^\infty a_n$ diverges or not.


text:
Q: How does the rsync -u option help syncing two folders? I want folder source and folder destination to be synced, in which all changes in source are to be reflected to destination.
In this case, I would be using the rsync command like so:
rsync -av --progress --delete "/source/" "/destination"

With a / for source to specify its contents and without / for destination.
Now, do I have to use the -u option in order to the destination to update if source has a newer modified time? Or is -av already enough?
And would I need the -i option at all? Thank you!

-u, --update
This forces rsync to skip any files which exist on the destination and have a modified  time  that
is  newer than the source file.  (If an existing destination file has a modification time equal to
the source file's, it will be updated if the sizes are different.)
Note that this does not affect the copying of symlinks or other special files.  Also, a difference
of  file format between the sender and receiver is always considered to be important enough for an
update, no matter what date is on the objects.  In other words, if  the  source  has  a  directory
where the destination has a file, the transfer would occur regardless of the timestamps.
This  option  is a transfer rule, not an exclude, so it doesn't affect the data that goes into the
file-lists, and thus it doesn't affect deletions.  It just limits  the  files  that  the  receiver
requests to be transferred.

--delete
This tells rsync to delete extraneous files from the receiving  side  (ones  that  aren't  on  the
sending  side),  but  only  for  the directories that are being synchronized.  You must have asked
rsync to send the whole directory (e.g.  "dir"  or  "dir/")  without  using  a  wildcard  for  the
directory's  contents  (e.g.  "dir/*")  since the wildcard is expanded by the shell and rsync thus
gets a request to transfer individual files, not the files'  parent  directory.   Files  that  are
excluded   from   the   transfer  are  also  excluded  from  being  deleted  unless  you  use  the
--delete-excluded option or mark the  rules  as  only  matching  on  the  sending  side  (see  the
include/exclude modifiers in the FILTER RULES section).
Prior  to rsync 2.6.7, this option would have no effect unless --recursive was enabled.  Beginning
with 2.6.7, deletions will also occur when --dirs (-d) is enabled, but only for directories  whose
contents are being copied.
This option can be dangerous if used incorrectly!  It is a very good idea to first try a run using
the --dry-run option (-n) to see what files are going to be deleted.
If the sending side detects any I/O errors, then the deletion of any files at the destination will
be  automatically  disabled. This is to prevent temporary filesystem failures (such as NFS errors)
on the sending side from causing a massive deletion of files on the destination.  You can override
this with the --ignore-errors option.
The  --delete  option  may  be combined with one of the --delete-WHEN options without conflict, as
well as --delete-excluded.  However, if none of the --delete-WHEN  options  are  specified,  rsync
will  choose  the  --delete-during  algorithm  when  talking  to  rsync  3.0.0  or  newer, and the
--delete-before  algorithm  when  talking  to  an  older  rsync.   See  also  --delete-delay   and
--delete-after.

A:
Now, do I have to use the -u option in order to the destination to update if source has a newer modified time?

No, that's already the case.  What -u does is to prevent changes happening if the destination is newer.  Without -u, such files will be updated to the version on the source (which could be older).

And would I need the -i option at all?

-i (like --progress) doesn't affect the sync behavior, just the output that is displayed.  It just shows additional information about each file selected.


text:
Q: paintComponent method is not displaying anything on the panel I have been trying to debug this for hours. The program is supposed to be a grapher that graphs coordinates, but i cannot get anything to display not even a random line, but if i put a  print statement there it works. It is a problem with the paintComponent Method. When I out print statement before g.drawLine then it prints, but it doesn't draw any lines even if i put a random line with coordinates (1,3), (2,4).
import java.awt.*;
import java.util.*;
import javax.swing.*;
public abstract class XYGrapher
{
    abstract public Coordinate xyStart();
    abstract public double xRange();
    abstract public double yRange();
    abstract public Coordinate getPoint(int pointNum);
    public class Paint extends JPanel
    {
        public void paintGraph(Graphics g, int xPixel1, int yPixel1, int xPixel2, int yPixel2)
        {
            super.paintComponent(g);
            g.setColor(Color.black);
            g.drawLine(xPixel1, yPixel1, xPixel2, yPixel2);
        }
        public void paintXAxis(Graphics g, int xPixel, int pixelsWide, int pixelsHigh)
        {
            super.paintComponent(g);
            g.setColor(Color.green);
            g.drawLine(xPixel, 0, xPixel, pixelsHigh);
        }
        public void paintYAxis(Graphics g, int yPixel, int pixelsWide, int pixelsHigh)
        {
            super.paintComponent(g);
            g.setColor(Color.green);
            g.drawLine(0, yPixel, pixelsWide, yPixel);
        }
    }
    public void drawGraph(int xPixelStart, int yPixelStart, int pixelsWide, int pixelsHigh)
    {
        JFrame frame = new JFrame();
        Paint panel = new Paint();
        panel.setPreferredSize(new Dimension(pixelsWide, pixelsHigh));
        panel.setMinimumSize(new Dimension(pixelsWide, pixelsHigh));
        panel.setMaximumSize(new Dimension(pixelsWide, pixelsHigh));
        frame.setLocation(frame.getToolkit().getScreenSize().width / 2 - pixelsWide / 2, frame.getToolkit().getScreenSize().height / 2 - pixelsHigh / 2);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

        double xRange = xRange();
        double yRange = yRange();
        Coordinate xyStart = xyStart();

        int xPixel = xPixelStart - (int) (xyStart.getX() * (pixelsWide / xRange));
        int yPixel = yPixelStart + (int) ((xyStart.getY() + yRange) * (pixelsHigh / yRange));

        System.out.println(xPixel + " " + yPixel);

        if(yPixel > 0 && (yPixel < pixelsHigh))
        {
            System.out.println("y");
            panel.paintYAxis(panel.getGraphics(), yPixel, pixelsWide, pixelsHigh);
        }
        if(xPixel > 0 && (xPixel < pixelsHigh))
        {
            System.out.println("x");
            panel.paintXAxis(panel.getGraphics(), xPixel, pixelsWide, pixelsHigh);
        }

        for(int i = 0; i>=0; i++)
        {
            Coordinate point1 = getPoint(i);
            Coordinate point2 = getPoint(i+1);
            if(point2 == null)
            {
                break;
            }
            else
            {
                if(point1.drawFrom() && point2.drawTo())
                {
                    int xPixel1 = (int) (xPixelStart + (point1.getX() - xyStart.getX()) * (pixelsWide / xRange));
                    int yPixel1 = (int) (yPixelStart + (xyStart.getY() + yRange-point1.getY()) * (pixelsHigh / yRange));
                    int xPixel2 = (int) (xPixelStart + (point2.getX() - xyStart.getX()) * (pixelsWide / xRange));
                    int yPixel2 = (int) (yPixelStart + (xyStart.getY() + yRange - point2.getY()) * (pixelsHigh / yRange));

                    panel.paintGraph(panel.getGraphics(), xPixel1, yPixel1, xPixel2, yPixel2);
                }
            }
        }
        frame.pack();
    }
}

This is how i am testing it is supposed to be a square, but nothing shows up.
public class GrapherTester extends XYGrapher
{
    public Coordinate xyStart()
    {
        return new Coordinate(-2,2);
    }
    public double xRange()
    {
        return 4;
    }
    public double yRange()
    {
        return 4;
    }
    public Coordinate getPoint(int pointNum)
    {
        switch(pointNum)
        {
            case 0: return new Coordinate(-1,-1);
            case 1: return new Coordinate(1,-1);
            case 2: return new Coordinate(1,1);
            case 3: return new Coordinate(-1,1);
            case 4: return new Coordinate(-1,-1);
        }
        return null;
    }
    public static void main(String[] args)
    {
        new GrapherTester().drawGraph(100, 100, 500, 500);
    }
}

Coordinate class so if any of you want to run and try it out. That is all you would need.
public class Coordinate
{
    float x;
    float y;
    boolean drawTo;
    boolean drawFrom;
    Coordinate(double x, double y)
    {
        this.x = (float) x;
        this.y = (float) y;
        drawFrom = true;
        drawTo = true;
    }
    Coordinate(double x, double y, boolean drawFrom, boolean drawTo)
    {
        this.x = (float) x;
        this.y = (float) y;
        this.drawFrom = drawFrom;
        this.drawTo = drawTo;
    }
    public double getX()
    {
        return x;
    }
    public double getY()
    {
        return y;
    }
    public boolean drawTo()
    {
        return drawTo;
    }
    public boolean drawFrom()
    {
        return drawFrom;
    }
}

A: The methods paintGraph(...), paintXAxis(...) and paintYAxis(...) should not invoke paintComponent().
Instead the code should be the other way around. That is you should override the paintComponent() method which in turn will invoke those 3 methods. Also the parameters you pass to each of the methods should be properties of the Paint class. So you may also need to add some setter method to assign values to all the properties.
Also, don't forget to override the getPreferredSize() method of the Paint class so the component can be layed out properly by layout managers.
I suggest you start by reading the section from the Swing tutorial on Custom Painting for a more detailed explanation and working examples.

A: The class does not override paintComponent(Graphics).

There are some other odd aspects to the code shown, starting with..
frame.setLocation(frame.getToolkit().getScreenSize().width / 2 - pixelsWide / 2, frame.getToolkit().getScreenSize().height / 2 - pixelsHigh / 2);

What does that translate to in any human language, the 'center of the screen'?  If so, that can be accomplished simpler using:
frame.setLocationRelativeTo(null);

But better still, we now have..
frame.setLocationByPlatform(true);

See here for a quick example.