text:
Q: How to access ng-model name dynamically? How do I access ng-model name assigned to each div dynamically in for loop in function which I'm calling on ng-click?
I've four divs in my page and at a time i want to display only one and hide others.
I'm trying to do this using ng-show.

content0 details here...

content1 details here...

content2 details here...

content3 details here...

A: try:

content0 details here...

content1 details here...

content2 details here...

content3 details here...

and in ng-click set $scope.current to the one you want to show.

A: Off of the model you would have a Boolean property to say if it was hidden or not.  You would modify this in your loop when calling ngClick.
Example: http://jsfiddle.net/roadprophet/ffKTy/

{{thing.id}}

        <button ng-click="flipMode()">FLIP!</button>

angular.module('app', []).
controller('MainController', ['$scope', function ($scope) {
    $scope.things = [{
        id: 1,
        shown: true
    }, {
        id: 2,
        shown: false
    }, {
        id: 3,
        shown: true
    }, {
        id: 4,
        shown: false
    }, {
        id: 5,
        shown: true
    }, ];
    $scope.flipMode = function () {
        $scope.things.forEach(function (thing) {
            thing.shown = !thing.shown
        })
    };
}]);


text:
Q: Setup validation messages I'm using config file for the validation rules. The problem is that I can't figure out how to set a custom message for each field in the config file. Here is my config
$config = array(
   'user/signup' => array(
                      array(
                              'field' => 'email',
                              'label' => 'Email',
                              'rules' => 'required|valid_email'
                           ),
                      array(
                              'field' => 'password',
                              'label' => 'Password',
                              'rules' => 'required|matches[confirm_password]|min_length[5]|max_length[12]'
                           ),
....

A: All of the native error messages are located in the following language file: language/english/form_validation_lang.php
To set your own custom message you can either edit that file, or use the following function:
$this->form_validation->set_message('rule', 'Error Message');

A: I am not sure if this can be done.
How about extending the form validation library and including the error messages in the set_rules function?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change the input font size in AngularJS Material where when you click in the textarea the text animates and floats above the textarea Looking to find out how to change the input font size in AngularJS Material where when you click in the textarea the text animates and floats above the textarea.  I want the font to be bigger above the textarea, it's very small currently.
Additionally once it's no longer focused I would like to darken the color to black, right now it's a darkish grey.
'''
  <md-input-container class="md-input-has-placeholder"  style="width: 100%">

   <label>Additional Information: </label>
    <textarea aria-label="Additional Information" md-maxlength="6000" rows="6" id="urineDrugScreenText" name="urineDrugScreenText" class="textarea" style=" width: 100%; padding:5px" cemr-require-global-documentvariable="Urine_Drug_Screen_Results_textBoxAdd0" ng-model="DocumentData.Urine_Drug_Screen_Results_textBoxAdd0" ng-model-options="{ debounce: 250 }" md-select-on-focus></textarea>

    </md-input-container>

'''


text:
Q: How to use ActiveRecord none method properly? I have the following in my controller:
@registrations = Registration.where('id > 1000000000')
Event.unarchived.each do |event|
  event.registrations.by_submitted.each do |reg|
    @registrations << reg
  end
end

There has to be a better way to do this.  I've tried replacing the first line with:
@registrations = Registration.none

But when I do that, the final @registrations variable always comes up with zero records.
What is the proper way to use the none method here?

A: I would recommend you to do it this way:
registration_ids = []
Event.unarchived.each do |event|
  registration_ids << event.registrations.by_submitted.pluck(:id)
end
@registrations = Registration.where(id: registration_ids.flatten)


text:
Q: How to get child_object in python-ldap I'm totally new in using LDAP with python, am trying to perform a query on the LDAP tree that is shown in the image.

Using the package python-ldap . as you see, the tree is like this :
ou=Organization >> ou=Company >> ou=Brasil >>
Then after the country, there are many cities, I managed to reach this city .. but there are some other cities that have some kind of (Sub-Cities) under it as you see in ou=Sao Paulo, it has 3 sub-cities after it.
What I need to do is :
1- Get to the child cities after the main cities.
2- get to be able to loop over every CN=Gateway-**** inside every city.
3- Finally need to access the inner attributes for every CN and get the value of it.
The code I used in views.py is :

def index(request):
    cities_list = []
    gateways_list = []
    con = ldap.initialize('ldap://The_URI_For_IDAP/(|(OU=Brasil)(OU=Company)(OU=Organization))')
    some_dn = 'dc=*****,dc=com'
    query = "ou=*"
    result = con.search_s(some_dn, ldap.SCOPE_SUBTREE, query)
    for item in result:
        cities_list.append(city_name)
        print(item)
    context = {
        'cities_list': cities_list,
    }
    return render(request, 'index.html', context)

in the cities_list i get a list of every Parent city ou after ou=Brasil but i can't get to the inner Ou and also can't reach the CN part.

A: If you want to grab every entry under ou=Organization >> ou=Company >> ou=Brasil, you need to set the base dn accordingly and use objectclass=* as filter :
con = ldap.initialize('ldap://domain.com')
base_dn = 'ou=Brasil,ou=Company,ou=Organization,dc=domain,dc=com'
filter = "(objectClass=*)"
result = con.search_s(base_dn, ldap.SCOPE_SUBTREE, filter)


text:
Q: Changing the button style of certain buttons in a DataGridView I have a DataGridView with a Button column in it.
I want to be able to disable and enable the buttons in every row (and/or change the style of them), according to a cell value in the row.
So let's say we have the following code :
if(dataGridView1.Rows[1].Cells[1].Value.ToString()=="OK")
        {
            //button in the same row should be enabled or disabled
        }

Can this be done?

A: You can inherit a DataGridViewDisableButtonCell class from DataGridViewButtonCell to use in your DGV, as explained on MSDN. Then you'll be able to enable/disable the button inside that cell with the following code:
DataGridViewDisableButtonCell buttonCell = (DataGridViewDisableButtonCell)dataGridView1.Rows[e.RowIndex].Cells["Buttons"];
buttonCell.Enabled = myEnableConditionMet ? true : false;


text:
Q: Distribution of $ Y = X_1 + X_2-n_2 $ I have independent random variables $X_1$ and $X_2$ such that
$ X_1\sim Bin(n_1, 1/2) $ and $X_2\sim Bin(n_2,1/2)$ be independent random variables . Find the distribution of $Y = X_1-X_2+n_2$
Attempt :
$$ P[Y = X_1-X_2+n_2 ] = \binom{n_2}{x_1-x_2+n_2}*(1/2)^{x_1-x_2+n_2} *(1/2)^{x_1-x_2} \\
 =  \binom{n_2}{x_1-x_2+n_2} (1/2)^{n_2} $$
Is this right ?
It seems wrong since answer is independent of $n_1$ and I hadn't used the fact that both are independent random variables .

A: Your calculations are indeed wrong in any case. Here is a much simpler method. $\newcommand{bin}{\operatorname{binom}}$
By comparing pmfs – the expanded pmf of $X_2$ is $P(X_2=k)=\binom{n_2}k\left(\frac12\right)^{n_2}$, while we have the identity $\binom nk=\binom n{n-k}$ – we see that
$$n_2-X_2\sim X_2\sim\bin\left(n_2,\frac12\right)$$
Therefore
$$Y\sim X_1+X_2\sim \bin\left(n_1+n_2,\frac12\right)$$

A: The key point is that if $$X_2 \sim \operatorname{Binomial}(n_2, p),$$ then $$n_2 - X_2 \sim \operatorname{Binomial}(n_2, 1-p).$$  The proof is simple.  Since we have $$\Pr[X_2 = x] = \binom{n_2}{x} p^x (1-p)^{n_2 - x},$$ we then have $$\begin{align*}
\Pr[n_2 - X_2 = x] &= \Pr[X_2 = n_2 - x] \\
&= \binom{n_2}{n_2-x} p^{n_2 - x} (1-p)^{n_2 - (n_2 - x)} \\
&= \frac{(n_2)!}{(n_2 - x)! \, (n_2 - (n_2 - x))!} (1-p)^x p^{n_2 - x} \\
&= \binom{n_2}{x} (1-p)^x p^{n_2 - x},
\end{align*}$$
which is the PDF of a binomial distribution with parameters $n_2$ and $1-p$.  Of course, we can use an elementary counting argument to conclude the same, or we could also use the fact that a binomial distribution is the sum of IID Bernoulli variables.
In fact, this latter property is what we can now easily use to complete the answer:  Since $p = 1/2$ for $X_2$, then $n_2 - X_2$ is also binomial with parameter $1 - p = 1/2$, thus $X_1$ is the sum of $n_1$ IID Bernoulli variables and $n_2 - X_2$ is the sum of $n_2$ IID Bernoulli variables, and they all share the same parameter $p = 1 - p = 1/2$.  Thus $Y = X_1 + n_2 - X_2$ is the sum of $n_1 + n_2$ IID Bernoulli random variables with $p = 1/2$, thus $$Y \sim \operatorname{Binomial}(n_1 + n_2, 1/2).$$


text:
Q: Functions button effects another function I am trying to add multiple stop watches on a page for tracking tracking how much time it takes users to complete tasks.  I have a function that works, I copied it and tried to make a second function duplicate with certain things change the buttons effect the other function.  Any help would be appreciated.

html {

 size: 100%,100%;
 background-color: #f2f2f2;
}

h1{
 font-Family: Arial;
 color: #5573A9;
 font-size: 40px;
 position: static;
}

 body {
  display: block;
  margin:8px, dotted line;
  background-color: #f2f2f2;

 }

#output{
 position:center;
    width:120px;
    height:25px;
    background-color:#CCC;
    border:3px solid #999;
   }

#output2{
 position: relative;
    width:120px;
    height:25px;
    background-color:#CCC;
    border:3px solid #999;
   }

   table {
    display:table;
    border-collapse:seperate;
    border-spacing: 52px;
    border-color: #FFF;
   }

 <link rel="stylesheet" type="text/css" href="style.css">

  <title>Time Study</title>

Time Study

 Bin
 Bulk

  <button id="startPause" onclick="startPause()">Start</button>
  <button onclick="reset()">Reset</button>

  <button id="startPause2" onclick="startPause2()">Start</button>
  <button onclick="reset2()">Reset</button>


text:
Q: How to convert text file in order to be placed in my acharengine array? So I have this two classes called ReadFromFile (provided by @Pankaj Nimgade) and MainActivity to import and read my test.txt. I want the integers on the text file to be read in my app with library achartengine.They have to be formatted to be put in the int[] force_l and int[] force_r:
Can you help me to format the integers the way I need and how to put them in the int[] force_l and int[] force_r?
private void openChart() {
        int[] x = {0,1,2,3,4,5,6,7,8,9,10};
        int[] force_l = {0,25,24,25,15,16,17,25,24,21,24}; //replace this {} values with the ones from the text file
        int[] force_r = {0,48,36,26,43,45,30,33,33,28,42}; //replace this {} values with the ones from the text file

The test.txt is has two lines:
0 25 24 25 15 16 17 25 24 21 24
0 48 36 26 43 45 30 33 33 28 42

Now, how do I pass the integer string from ReadFromFile to be read in MainActivity?
The ReadFromFile class provided by @Pankaj Nimgade:
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class ReadFromFile {

    public static void main(String[] args) {

        int[] force_l = null;
        int[] force_r = null;
        try {

            File file = new File("test.txt");
            List<String> strings = FileUtils.readLines(file);
            int count = 0;
            for (String s : strings) {

                String[] integer_Strings = s.split(" ");
                if (count == 0) {

                    force_l = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) {
                        force_l[i] = Integer.parseInt(integer_Strings[i]);
                    }
                    count++;
                } else if (count == 1) {
                    force_r = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) {
                        force_r[i] = Integer.parseInt(integer_Strings[i]);
                    }
                }

            }

            System.out.println(Arrays.toString(force_l));
            System.out.println(Arrays.toString(force_r));

        } catch (Exception e) {
        e.printStackTrace();
        }
    }

}

The MainActivity class:
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import org.achartengine.ChartFactory;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

public class MainActivity extends AppCompatActivity {

    private View mChart;
    private String[] mTime = new String[]{
            "0",
            "1","2","3","4","5","6","7","8","9","10",
    };

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

        // Getting reference to the button btn_chart
        Button btnChart = (Button) findViewById(R.id.btn_chart);

        // Defining click event listener for the button btn_chart
        View.OnClickListener clickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Draw the Chart
                openChart();
            }
        };

        // Setting event click listener for the button btn_chart of the     SensorGraph layout
        btnChart.setOnClickListener(clickListener);

    }

    private void openChart() {
        int[] x = {0,1,2,3,4,5,6,7,8,9,10};
        int[] force_l;
        int[] force_r;

        // Creating an XYSeries for Right Force
        XYSeries force_rSeries = new XYSeries("Force R (N)");
        // Creating an XYSeries for Left Force
        XYSeries force_lSeries = new XYSeries("Force L (N)");
        // Adding data to Force Series
        for (int i = 0; i < x.length; i++) {
            force_lSeries.add(i, force_l[i]);
            force_rSeries.add(i, force_r[i]);
        }

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        // Adding Left Force Series to dataset
        dataset.addSeries(force_lSeries);
        // Adding Right Force Series to the dataset
        dataset.addSeries(force_rSeries);

        // Creating XYSeriesRenderer to customize Force R Series
        XYSeriesRenderer force_rRenderer = new XYSeriesRenderer();
        force_rRenderer.setColor(Color.RED); //color of the graph set to green
        force_rRenderer.setFillPoints(true);
        force_rRenderer.setLineWidth(2f);
        force_rRenderer.setDisplayChartValues(false);
        //setting chart value distance
        // force_rRenderer.setDisplayChartValuesDistance(10);
        //setting line graph point style to circle
        // force_rRenderer.setPointStyle(PointStyle.CIRCLE);
        //setting stroke of the line chart to solid
        force_rRenderer.setStroke(BasicStroke.SOLID);

        // Creating XYSeriesRenderer to customize Force L Series
        XYSeriesRenderer force_lRenderer = new XYSeriesRenderer();
        force_lRenderer.setColor(Color.BLUE);
        force_lRenderer.setFillPoints(true);
        force_lRenderer.setLineWidth(2f);
        force_lRenderer.setDisplayChartValues(false);
        //setting line graph point style to circle
        // force_lRenderer.setPointStyle(PointStyle.SQUARE);
        //setting stroke of the line chart to solid
        force_lRenderer.setStroke(BasicStroke.SOLID);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        XYMultipleSeriesRenderer multiRenderer = new     XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(0);
        //multiRenderer.setChartTitle("High Speed");
        multiRenderer.setXTitle("time (s)");
        multiRenderer.setYTitle("Force (N)");

        /***
         * Customizing graphs
         */
        //setting text size of the title
        multiRenderer.setChartTitleTextSize(28);
        //setting text size of the axis title
        multiRenderer.setAxisTitleTextSize(24);
        //setting text size of the graph lable
         multiRenderer.setLabelsTextSize(24);
         //setting zoom buttons visiblity
         multiRenderer.setZoomButtonsVisible(false);
         //setting pan enablity which uses graph to move on both axis
        multiRenderer.setPanEnabled(false, false);
        //setting click false on graph
        multiRenderer.setClickEnabled(false);
        //setting zoom to false on both axis
        multiRenderer.setZoomEnabled(false, false);
        //setting lines to display on y axis
        multiRenderer.setShowGridY(true);
        //setting lines to display on x axis
        multiRenderer.setShowGridX(true);
        //setting legend to fit the screen size
        multiRenderer.setFitLegend(true);
        //setting displaying line on grid
        multiRenderer.setShowGrid(true);
        //setting zoom to false
        multiRenderer.setZoomEnabled(false);
        //setting external zoom functions to false
        multiRenderer.setExternalZoomEnabled(false);
        //setting displaying lines on graph to be formatted(like using graphics)
        multiRenderer.setAntialiasing(true);
        //setting to in scroll to false
        multiRenderer.setInScroll(false);
        //setting to set legend height of the graph
        multiRenderer.setLegendHeight(30);
        //setting x axis label align
        multiRenderer.setXLabelsAlign(Paint.Align.CENTER);
        //setting y axis label to align
        multiRenderer.setYLabelsAlign(Paint.Align.LEFT);
        //setting text style
        multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
        //setting no of values to display in y axis
        multiRenderer.setYLabels(10);
        // setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 60.
        // if you use dynamic values then get the max y value and set here
        multiRenderer.setYAxisMin(0);
        multiRenderer.setYAxisMax(80);

        multiRenderer.setXLabels(4);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMin(0);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMax(61);
        //setting bar size or space between two bars
        //multiRenderer.setBarSpacing(0.5);
        //Setting background color of the graph to transparent
        multiRenderer.setBackgroundColor(Color.TRANSPARENT);
        //Setting margin color of the graph to transparent
        multiRenderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
        multiRenderer.setApplyBackgroundColor(true);
        multiRenderer.setScale(2f);
        //setting x axis point size
        multiRenderer.setPointSize(4f);
        //setting the margin size for the graph in the order top, left, bottom, right
        multiRenderer.setMargins(new int[]{30, 30, 30, 30});

        /*for(int i=0; i< x.length;i++){
            multiRenderer.addXTextLabel(i, mTime[i]);
        }*/

        // Adding Force L Renderer and Force R Renderer to multipleRenderer
        // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
        // should be same
        multiRenderer.addSeriesRenderer(force_lRenderer);
        multiRenderer.addSeriesRenderer(force_rRenderer);

        //this part is used to display graph on the xml
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
        //remove any views before u paint the chart
        chartContainer.removeAllViews();
        //drawing bar chart
        mChart = ChartFactory.getLineChartView(MainActivity.this, dataset, multiRenderer);
        //adding the view to the linearlayout
        chartContainer.addView(mChart);

    }
}

A: Use a BufferedReader to read the input file line by line(see this answer How to get file read line by line) and for each line make a split over the " "(space)
String line = "0 25 24 25 15 16 17 25 24 21 24"; /* this should be the line from file*/
String[] force_l  = line.split(" ");
force_l[0]; // this will contain "0"
force_l[1]; // this will contain " 25"

Then you can convert values to int like
Integer.parseInt(force_l[0])

Also add the file to assets, it will be easy for you not to use an absolute path like "C:/test.txt"

A: Things that you should pay attention is that you get individual line with line of integers separated by space, from this you can generate a String array like this String[] integer_Strings = s.split(" "); now that you have the string value for each integer you can convert this string value to int like this Integer.parseInt("2"). This method return 2 in int 2, code is also available in github
    int[] force_l = null;
    int[] force_r = null;
    try {

        File file = new File("file_json_test_three.txt");
        Path path = file.toPath();
        List<String> strings = Files.readAllLines(path);
        //List<String> strings = FileUtils.readLines(file); can be used with common-io-2.4 library
        int count = 0;
        for (String s : strings) {
            //System.out.println(s);
            String[] integer_Strings = s.split(" ");
            //System.out.println(Arrays.deepToString(integer_Strings));
            if (count == 0) {
                force_l = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) {
                    force_l[i] = Integer.parseInt(integer_Strings[i]);
                }
                count++;
            } else if (count == 1) {
                force_r = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) {
                    force_r[i] = Integer.parseInt(integer_Strings[i]);
                }
            }

        }

        System.out.println(Arrays.toString(force_l));
        System.out.println(Arrays.toString(force_r));

    } catch (Exception e) {
        e.printStackTrace();
    }

Output

[0, 25, 24, 25, 15, 16, 17, 25, 24, 21, 24]
[0, 48, 36, 26, 43, 45, 30, 33, 33, 28, 42]


text:
Q: avoid data showed with jquery.html lost after page reload when the user starts my app, there is a lot of data coming from a web service which is stored into the device´s database and then shown on the HTML-page using jquery`s .html() method. The problem is when the user selects another HTML page and then comes back, the data is not shown anymore, it has to be read out from the database again.
I know this isn't "rent a coder" but my question is: Is there a way to keep the data persistant on the HTML page even after the page is reloaded? Or do I have to pack everything into a single HTML document?

A: The solution could be to handle all navigation with AJAX, make your website a one page app and keeps things into cache. But i think this is a really big topic.
In any case a good Javascript MVC Framework like Backbone or Ember could help you.


text:
Q: GeoServer Vector Tiles show tile boundary issue in Mapbox GL JS I use GeoServer to provide Vector Tiles (based on the GeoServer Vector Tile Extension) of my biking trails as .pbf.
The data are added as vector source and visualized using Mapbox GL JS.
Additionally, I use the GeoServer perpendicularOffset to offset the lines (as I always have two directions of the biking trail).
A problem occurs when visualizing the data within Mapbox. The lines are cut at the tile edges, although they are visualized correctly using the layer preview on GeoServer.
The further I zoom in the map, the less the clipping of the lines happens and at a very detailed zoom, the lines are drawn correctly.
I already tried to use a large enough buffer and modify the tile size, as these were suggestions when researching the problem. Unfortunately, these settings had no effect.
I have another vector source layer for the base map, there I have no problems.
It seems to me, that offsetting the lines might be a problem.

Any idea what I can try?

A: the tile size of Geoserver's tile grid is 256x256 , but mapbox need 512x512, add a custom tile grid, set the tile size to 512x512, generate your vector tile with the custom tile grid should be ok.


text:
Q: Embed
A: $('<script>').attr({
  type: 'text/javascript',
  src: 'http://platform.twitter.com/widgets.js'
}).appendTo('#entries');

I think will do the trick. Also, try to use the .attr, .text, etc. parameters when using jQuery to insert code. Makes it a little more stable, and semi-protects you from XSS.
EDIT Actually, interestingly enough, I think this is referrer-inhibited. I can't seem to get it to import, even on jsfiddle, yet I can direct-access it. I'm looking in to it though...
Nevermind, seems to load, just doesn't show up in Google chrome/firebug DOM tree (yet chrome shows it loading in resources timeline).

A: edit
Wow, ignore me. I didn't read through your question well enough. The script is obviously not yours, since it is located on twitter.com haha. I'm sorry.

Is the tweet button's script what's being loaded in the widget.js script? If so, is it a custom script that you wrote? I ask because you could modify the click handler of the button to instead be live(), and then pass the string 'click' and the function you want for the handler. That would attach the handler to each button when it's added to the page dynamically.

A: Looks like your <a> is missing the class "twitter-share-button"
I think from the look of it that the script looks for links with that class and generates the button and tweet count (actually an iframe)
I would have thought you need only load the script once on the page, but it may not handle links built dynamically by javascript
Edit http://dev.twitter.com/pages/tweet_button_faq#multiple-buttons definitely says to load the script only once


text:
Q: Python - script doesn't execute the rest of code after is daemonized I have this code:
import os
import time

def createDaemon():
    try:
        pid = os.fork()

        if pid > 0:
            print ('PID: %d' % pid)
            os._exit(0)

    except OSError as error:
        print ('Unable to fork. Error: %d (%s)' % (error.errno, error.strerror))
        os._exit(1)

    doTask()

def doTask():
    file = open('/tmp/tarefa.log', 'w')

    while True:
        file.flush()
        time.sleep(2)

    file.close()

def myfunction():
    # do something, I am not implementing the code, it's useless for the question

createDaemon()
myfunction() # it is never executed.

As you see in the comment, I want to execute myfunction() but it doesn't. What can I do? I am not writing the content of myfunction() because it's useless for my question.

A: Your code never reaches the call to myfunction() because of this:
while True: # <-----
    file.flush()
    time.sleep(2)

The infinite loop causes the thread to sleep for 2 seconds indefinitely. Remove the loop, and it works.

A: So, lets think about this. After the fork you have 2 processes, one of which you close right after. The other process then goes into doTask which has an infinite loop, it will just sleep for 2 seconds indefinitely. That is why no process actually goes further than your createDaemon() call.


text:
Q: DidFinishLoading view change I have a login screen view and 5 tabs in the app.I want when I done with the LoginScreen and it should move to the Tabs views(5) .for this once Login Task is done,I have to remove the view and add the another view controller of the tab..how to do this...
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:self.viewController];

self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
return YES;
}

like this way I moves to the login view...now how to remove after completion of login and move to the tab1,tab2,tab3,tab4,tab5

A: You can create the following methods in you AppDelegate to switch between 2 navigation controllers.
+ (AppDelegate *)sharedDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

+ (void)showLogin {
    AppDelegate *selfInstance = [self sharedDelegate];

    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:self.viewController];
    selfInstance.window.rootViewController = nav;

}

+ (void)showTabs {
    AppDelegate *selfInstance = [self sharedDelegate];

    self.viewController2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];
    UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:self.viewController2];
    selfInstance.window.rootViewController = nav;
}

Your didFinishLaunchingWithOptions method should then look like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    if( isLoggedIn ){
        [AppDelegate showLogin];
    } else {
        [AppDelegate showTabs];
    }

    return YES;
}

Then from anywhere in you app you can do:
[AppDelegate showTabs];

Let me know if you need help implementing it.

A: You can make your UITabBarController as your initial view. There you can check if you need to log-in, or if you auto log-in. If you need to go to the login screen, just use a modal segue to display the login view and dismiss it when login is done.

A: Initially you add your firstViewController as subView to your addDelegate.window, then on buttonClick you can remove your navController and add tabBarController to appDelegate.window
Follow my answer for better result  Link


text:
Q: Better Javascript performance I'm currently building an app in React to learn the language. The App is a game and within the game i'm playing a lot of sounds using the Howler.js. Howler is great as it allows me to easily create sounds and also very importantly allows me to adjust the pitch of a sound meaning I can create melodies with just one sample.
The issue i'm starting to run into when I have a lot of different sounds at different pitches going on is performance. With the code I have setup to loop over my sound object is quite heavy and I am wondering if there is a way to optimize it (i'm by no means a Javascript expert so I wouldn't be surprised if there was a much leaner way to execute the sound object). Anyway here is my sound object below to give you an idea:
var testTrack = [{
        rowId:1,
        rowExtras:"notExpanded",
        rowSample:
            {
                sampleId:"1",
                notes:[
                    {
                        keyNumber:0,
                        noteDelay:0,
                        notePitch:1
                    },{
                        keyNumber:2,
                        noteDelay:460,
                        notePitch:1
                    },{
                        keyNumber:4,
                        noteDelay:920,
                        notePitch:1
                    },{
                        keyNumber:6,
                        noteDelay:1380,
                        notePitch:1
                    },{
                        keyNumber:8,
                        noteDelay:1840,
                        notePitch:1
                    },{
                        keyNumber:10,
                        noteDelay:2300,
                        notePitch:1
                    },{
                        keyNumber:12,
                        noteDelay:2760,
                        notePitch:1
                    },{
                        keyNumber:14,
                        noteDelay:3220,
                        notePitch:1
                    }
                ],
                sampleName:"Heavy Kick",
                sampleSource:"../../samplesWav/sample1.wav"
            }

        },{    ...there are 12 more objects in the array with different samples in them

Here is the code I use to loop over and play the sound with Howler.js. Please note the above object lives in my Apps state under this.state.trackObject:
  playTrack(){

    var audioArray = this.state.trackObject;

    for(var i=0; i <= audioArray.length - 1; i++) {

        var rowObject = this.state.trackObject[i]

        var notesLength = rowObject.rowSample.notes.length

        for(var j=0; j <= notesLength - 1; j++) {
            var notes = rowObject.rowSample.notes[j].noteDelay;
            var id = rowObject.rowSample.sampleId;
            var src = rowObject.rowSample.sampleSource;
            var pitch = rowObject.rowSample.notes[j].notePitch;

            playSample(id,notes,src,pitch)
        }

    }

    function playSample(id,notes,src,pitch){

        if(id != "null"){
        setTimeout(function(){

        //this is where howler is used
         var sound = new Howl({
              src: [src],
              rate:pitch
         })

         sound.play();

         }, notes);
      }
   }

}

I'm try to do thing as much as I can in the 'React' way but i'm still learning so not sure if there would be a better way to intergrate the play function with my Apps state for better browser performance.
I've thought about using Audio sprites (which actually are setup to work quite well in Howler). I tried using this one here . I actually had an installation issue and coudln't get it running but even if I managed to fix that then I don't think I could add sounds with a pitch bend applied from howlers API to the sprite?
Thanks and I welcome any suggestions on performance/ solutions anyone might have!

A: I'm not sure how your game works, but perhaps you don't need to iterate over the entire array. If you store the sounds in a hash, and access them by some unique identifier(maybe the sound name?), this should improve performance dramatically.
So instead of instead of declaring testTrack as an array like this ...
var testTrack = [{
  rowId:1,
  rowExtras:"notExpanded",
  rowSample: { // Code removed for brevity }
},{
  rowId:2,
  rowExtras:"notExpanded",
  rowSample: { // Code removed for brevity }
}];

Declare it like this ...
var testTrack = {
  "track1": {
    rowId:1,
    rowExtras: "notExpanded",
    rowSample: { }
  },
  "track2": {
    rowId:2,
    rowExtras:"notExpanded",
    rowSample: { }
  }
};

Then access the elements using one of the methods below, where "track1" would be the sound name ...
var myTrack = testTrack.track1;
var myTrack = testTrack['track1'];

Not sure if this makes sense in the context of your game, but this will at least save you iterating the entire loop.


text:
Q: a lot less now too meaning Is my understanding of the phrase a lot less now too in below context correct?

I go to stadium a lot less now too.

means

Now also, I go to stadium very rarely.

A:
I go to the stadium a lot less now (too).

"too" would not be used with this sentence by itself. There would need to be a previous phrase, for example:

I go to the city a lot less now, and I go to the stadium a lot less now too.

Now if we substitute the meaning you asked about:

I go to the city a lot less now. Now also, I go to the stadium very rarely.

Basically it is OK, but "a lot less" means "a lot less than before". It could have been 200 days/year before and now it is 50 days/year.
However, "very rarely" is "hardly at all", and should be a very small number in any case.


text:
Q: copy ajax text generated I tried to copy text after an ajax text generated
I am able to copy a text an inputtext but for the field inputtext generated by the ajax response, it does not work
this code below display the input generated by the ajax

    <button id="copyButton" class="btn btn-primary" data-clipboard-target="#chat-output">

     </button>

this script represent the element injected in chat-output
       $(document).ready(function() {
        // Initialize the clipboard
        var clipboard = new ClipboardJS("#copyButton");

        // Handler for when the copy button is clicked
        clipboard.on("success", function(e) {
          // Show a tooltip indicating that the text was copied
          $(e.trigger).attr("data-original-title", "Copied!").tooltip("show");
          e.clearSelection();
        });

        $("#send").click(function() {
          let message = $("#message").val();
          $.post("' . $url . '", {message: message}, function(data) {
            $("#chat-output").html(data);
          });
        });
      });

When the message is generated, I do not see the copy button.
Do you have an idea to implement the coy button afterthe text is generated ?
Thank you


text:
Q: error XA5301: Failed to generate Java type for class Building a xamarin project that comes with a book, I get this error building the project:

error XA5301: Failed to generate Java type for class:
Android.Support.V4.View.Accessibility.AccessibilityManagerCompat/IAccessibilityStateChangeListenerImplementor
due to MAX_PATH: System.IO.DirectoryNotFoundException: Could not find
a part of the path '

A: The actual project folder path was just too long, shortening that eliminated the problem.


text:
Q: For BGA rework, can a kitchen plate-/dish- warmer be used after preheating in oven? Doing some casual PCB reworks for repair purposes, I'm looking for ways to improve the process.
Currently, I'm using a (not yet) modified kitchen oven to preheat, and then hot air to reflow.
A problem of this method is that the circuit board tends to cool down when outside the oven.
I am aware of PCB preheaters, rework stations and read quite a lot about them.
However, I found out that second hand electric dish-warmers can be found quite easily on local marketplaces, and despite the fact that their temperature is not displayed and they are not able to follow a temperature profile (unless modified), I see to them several potential benefits:

*

*Often of large surface area, around 50x30cm.
This is much larger than thus of many PCB heating plates.

*Often very cheap when second hand (typically ~10$ to ~40$ including shipping)

*Maximal temperature around 95°C on a professional model, that presents no risk of damaging components, nor unsoldering chips accidentally.

*Presence of a "min-max" control knob on professional models.
I'm aware that 95° Celsius is low, but I assume that after preaheating the PCB at ~190°C in oven, the dish-warmer would still help reducing thermal losses during the hot air reflow.
Are there some major risks or drawbacks for the boards using such appliance?
For instance temperature distributed in an irregular way and possibly very hot locally?
As I don't have such appliance, I couldn't check yet the temperatures at the surface area.


text:
Q: displaying label values in multiline text from gridview I got one gridview which has hyperlink in one column, when the user clicks the link he will be directed to another page where the details of particular row will be displayed using individual labels. In those labels one of the label must be multilined for me because the text will be too long...
Please help me how to get that.
aspx page of label
<asp:Label ID="LblDescription" runat="server"
Font-Bold="True" Font-Names="Verdana"
Font-Size="X-Small" ForeColor="#0061C1" Height="16px"
Width="97px" BorderColor="#0061C1"
BorderWidth="1px" BackColor="White"></asp:Label>

A: Try this....
<asp:Label ID="lblName" runat="server" Text="User1" Font-Bold="True" Font-Names="Verdana"></asp:Label>
<br />
<asp:Label ID="lblDescription" runat="server" Font-Bold="True" Font-Names="Verdana"
       Width="300px" Text="I got one gridview which has hyperlink in one column, when the user clicks the link he will be directed to another page where the details of particular row will be displayed using individual labels. In those labels one of the label must be multilined for me because the text will be too long">
</asp:Label>

Setting the width property of label, will make the text multilined and the font size will remain the same, unless you specify the font name same for all the lables


text:
Q: Windows 10 close button bug when scaling is set to System Advanced I have this bug in my program, and many other program's
The close button misses one pixel, which makes you click trough the close button, and close the windows behind it. (Really annoying).
No scaling

System Advanced scaling

As you can see there is this small white line next to the close button which can be clicked trough.
Is there any fix for this?
(Its on basicly all applications using Advanced Scaling)
In my scenario i use 200% windows scaling combined with the Advanced Scaling setting.


text:
Q: характеристики категорий Один наверно из самых популярных вопросов :). Пытаюсь сделать доску объявлений . Хочу сделать что бы при добавлении категории можно было забивать в БД характеристики (цвет, объем, память, тип, модель и тд...)для данной категории. Что бы потом при выборе категории в подачи объявления можно было заполнять характеристики данного товара. Типа как на olx.ua
Сильно не критикуйте, исключительно делаю для собственной практики.
Набросал следующую структуру БД
CREATE TABLE IF NOT EXISTS `ads`.`categories` (
  `category_id` INT NOT NULL AUTO_INCREMENT,
  `parend_id` INT NULL DEFAULT 0,
  `name` VARCHAR(80) NOT NULL,
  `alias` VARCHAR(45) NULL,
  PRIMARY KEY (`category_id`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ads`.`ads` (
  `ads_id` INT NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(150) NOT NULL,
  `category_id` INT NOT NULL,
  `description` TEXT NULL,
  `created_at` DATE NOT NULL,
  PRIMARY KEY (`ads_id`),
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ads`.`properties` (
  `property_id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`property_id`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ads`.`property_value` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `property_id` INT NOT NULL,
  `value` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`id`),
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ads`.`property_category` (
  `property_id` INT NOT NULL,
  `category_id` INT NOT NULL,
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `ads`.`pvalue_ads` (
  `id` INT NOT NULL,
  `ads_id` INT NOT NULL,
  `value_id` INT NOT NULL,
  PRIMARY KEY (`id`)
ENGINE = InnoDB;

Хотелось бы выслушать мнения недоставка такого подхода.

*

*был вырезан код внешних ключей для меньшего объема.

A: Формально - все логично и верно - как по учебнику. Но, на практике, избыточная нормализация - не совсем оптимальный подход. Я-бы не стал разделять properties,  property_value и property_category и постарался-бы обойтись всего 3-ми таблицам - cats, props и cats_props_rel.


text:
Q: SharePoint SPGridView client side available options I've been looking in to a few grids that are currently built that I could just make use of however none that I have found so far provide the same functionality as an SPGridView in terms of filtering.
The closest I've managed to find is JSGrid which allows you to search each individual column.
What I'd like to do is to display all unique values for a specific column in the filtering option below the normal Ascending and descending much like the list view functionality you currently get in a document library or list.
Many Thanks
Truez


text:
Q: iOS to Android Bluetooth RFCOMM I know this has been asked many times, but things seem to evolve very fast and the answers seem outdated.
Is there a way to let iOS and Android communicate via a Bluetooth RFCOMM channel? Maybe opening sockets?

A: Unfortunately, this is impossible.  RFCOMM is NOT supported on iOS unless the communication is encrypted through one of Apples' proprietary encryption chips.  Since Android used "standards compliant" Bluetooth, and not Apple-encrypted Bluetooth, this won't work.


text:
Q: Why does AliceBundle Fixture DateTime give me an unexpected value? I'm currently working on a project in which I create fixtures with Alice-bundle to run tests to make sure my API-endpoints work properly. Everything works fine, except for the DateTime properties.
No matter what string I pass it, eg: <dateTime('2019-09-23 14:00:00')>, it always gives me the wrong date and time, usually something like: 1998-10-25T14:29:45+01:00.
Even using <dateTime('now')> does not work -- it gives me some pre-2000s date & time as well, while that's exactly what some examples I'd found do use.
A fixture could look something like this:
Path\To\Task\Entity:
  my_task:
    title: 'My tasks'
    description: 'These are all the tasks just for me!!!'
    startsAt: <dateTime('now')>
    endsAt: <dateTime('now')>
    createdBy: '@some_higher_user'
Ideally I just want to pass it a string so I can define both a Date and Time and make sure it works properly, in the right format.
And help would be appreciated.

A: Looking here https://github.com/nelmio/alice/blob/master/doc/advanced-guide.md#functions we read:

function can be a Faker or a PHP native (or registered in the global scope) function.

So I would recommend trying a PHP native function that creates a \DateTime object
<date_create_from_format ( 'Y-m-d H:i:s' , '2019-09-23 14:00:00')>
// or
<date_create('now')>

A: That's how it works. The <dateTime()> function takes an argument called $max. So what it does is create a date between a starting date (not sure which one, probably something in the 1900 range or so) and that $max argument.
I guess you will want to use <dateTimeBetween()> which takes a startDate and an endDate to create a fake date between them. So I suppose if startDate = endDate, then you'll get the desired fixed date.
Take a look at fzaninotto/Faker library documentation. It's the library used by AliceBundle to actually fake data. There you can see what DateTime related functions you can use.


text:
Q: Random Image Upload Issues (backend) I've been trying to track down this issue for a bit now for a client, but because of it not showing up all the time, it's been tough. Essentially when an image is being uploaded, it's says "Uploading...", but gets stuck there & doesn't proceed with finishing the upload process.
It's never done this for me, but for my client, it's both been successful & failed in IE/Firefox/Chrome/Safari on different computers on both PC/MC platforms on multiple different internet connections (at home & office).
I tried simulating heavier backend usage (was logged-in in multiple browsers & attempted to do multiple backend functions while an image upload was taking place & it uploaded fine). I also looked at the server usage logs & at all of the times they were having issues, there were no traffic spikes. They also have decently high speed internet. So I think it's safe to say we can rule out these things.
Not sure what else to check. Any ideas?
They're on Magento 1.9.0.1

A: You are trying as an end-user, try as a developer. Check the browser developer console for errors when uploading, check how far it goes in the upload function when it gets stuck, check the permissions of the file you are trying to upload, try uploading same file again and again and see it that works or not.


text:
Q: How to move an image smoothly across Imageview Android I have large landscape image, I want to move that image smoothly across the screen without loosing aspect ratio. If you cant understand my question, please have a look at Android Newsstand app in that the cover image on top of the screen moves smoothly across the screen back and forth. how can i achieve that. please have a look at the image attached. The background image needs to move smoothly to the right when it reaches end it should move back to left.. Where should i start ?. Thanks in advance.
Update: Solution
PanningView is a library which implements the animated background in the now playing screen of the Play Music app.

A: Have a look at this library https://github.com/flavioarfaria/KenBurnsView
It is exactly what you are asking i hope :-)
Also do give a look at my this, which is modified ken burns view
https://github.com/HasanFaraaz/BackBurn


text:
Q: Unable to login to a https website via the app after changing from http Put simply, I am unable to login to my site through the wordpress app. I was able to previously login, but since the update I have not been able to. I believe this may have happened since I moved the site to https from http
There is nothing in access/error logs just this entry with each login:
[28/Oct/2019:15:17:02 +0000] "POST /xmlrpc.php HTTP/1.1" 200 4131

The error received when logging in is: The username and password you entered is incorrect.
However logging in via the desktop/chrome mobile everything works without a problem. So I know it is not a php/server error.

A: Maybe it has to do with the reCaptcha Protection on your Login Page? This is not built into Wordpress, but has to be installed by plugin. If the plugin changes the login-procedure, then maybe the login by app is changed too.
Also, a "recaptcha on Login Page" is often times realized by security plugins, which also recently started to incorporate an option to disable logging in per XML-RPC, which is the Login Method used by the Wordpress App.
Try to disable the Plugin which puts the recaptcha on the login page and try logging in again. If you can log in again, you know to search in the options of this plugin.


text:
Q: How do I create any Collection given the collection name(ArrayList, LinkedList etc) and items in the collection? I am trying to create a method that accepts the type of collection and the type of items inside the collection.
ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);
How do I write the getCollection so that, given any Collection subclass and any Number subclass, the method should create a collection and populate it with random elements of Number or subtype of Number?

A: If you can, it would be better to pass in a Supplier for the collection, and a Function to convert from Number to the sub-type, such as:
    private static final SecureRandom RND = new SecureRandom();
    private static final int COUNT_MAX = 100;

    public static void main(String[] args) {
        ArrayList<Integer> ints = getCollection(ArrayList::new, Number::intValue);
        System.out.println(ints);
        Set<Double> doubles = getCollection(HashSet::new, Number::doubleValue);
        System.out.println(doubles);
    }

    private static <T extends Collection<U>, U extends Number> T getCollection(
        Supplier<T> supplier, Function<Number, U> fn) {
        T collection = supplier.get();
        int count = RND.nextInt(COUNT_MAX);
        for (int i = 0; i < count; i++)
            collection.add(fn.apply(RND.nextInt()));
        return collection;
    }

This way, you won't need any casting.
Update using streams:
    private static <T extends Collection<U>, U extends Number> T getCollection(
        Supplier<T> supplier, Function<Number, U> fn) {
        int count = RND.nextInt(COUNT_MAX);
        return RND.ints().limit(count).boxed().map(fn)
            .collect(Collectors.toCollection(supplier));
    }


text:
Q: Mono: "mdoc: There is an error in XML document" I modified a few lines of C# code in the source of Mono, and now it does not build anymore:
make[7]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs/mcs'
make[7]: Entering directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs/docs'
/usr/bin/make all-local
make[8]: Entering directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs/docs'
MDOC    [net_4_0] cs-errors.tree
mdoc: There is an error in XML document.
See `mdoc help' for more information.
make[8]: *** [cs-errors.tree] Error 1
make[8]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs/docs'
make[7]: *** [do-all] Error 2
make[7]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs/docs'
make[6]: *** [all-recursive] Error 1
make[6]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs'
make[5]: *** [profile-do--net_4_0--all] Error 2
make[5]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs'
make[4]: *** [profiles-do--all] Error 2
make[4]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/mcs'
make[3]: *** [all-local] Error 2
make[3]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1/runtime'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/nico/src/mono-roman/mono-2.10.8.1'
make: *** [build-stamp] Error 2
dpkg-buildpackage: error: debian/rules build gave error exit status 2
Build command 'cd mono-2.10.8.1 && dpkg-buildpackage -b -uc' failed.
E: Child process failed

The problem is mdoc: There is an error in XML document. MDOC is a kind of Javadoc for Mono. I am surprised that changing a few benign C# lines would make MDOC fail?
Any tip on what is going on here? I also have no idea what XML document this is about.

A: The initial analysis I posted in the comments seems to be right. MDOC is loading the cs-errors.config, and using the newly built runtime. The changes you have made produce the following exception while loading said file:
System.InvalidOperationException: Element 'FilesPath' has wrong order in sequence (expected - -1, actual - 0

This was added by your patch. I am guessing you might want to check readBySoapOrder as well, such as:
if (readBySoapOrder && info.ExplicitOrder != ind)
    throw new InvalidOperationException(string.Format("Element '{0}' has wrong order in sequence (expected - {1}, actual - {2}", Reader.LocalName, info.ExplicitOrder, ind));

With this little change MDOC is happy and compilation succeeds, but I have no idea if it is the correct behavior.

A: Try "make clean" before trying "make" again.


text:
Q: Elastic search filter documents that contain array with empty string I've documents in elastic search and I want to filter out the documents that contain an array of only empty strings or have nothing / empty array.
#doc 1
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["",""]
    }
  }
}

#doc 2
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": []
    }
  }
}

#doc 3
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["hello",""]
    }
  }
}

From the above documents is it possible to filter out only doc 1 and doc 2 as for these, the "field" either contains nothing in the array or only empty string(s).

A: Please check below query which will return only the document which have empty array or an array with all the empty string.
here first should clause will check if empty string is part of array or not, second clause will check if array field does not exist and must_not with wildcard will remove document from result which have atleast one element in array.
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "city.keyword": {
              "value": ""
            }
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "city.keyword"
                }
              }
            ]
          }
        }
      ],
      "must_not": [
        {
          "wildcard": {
            "city.keyword": "?*"
          }
        }
      ]
    }
  }
}

Below is sample document in my index :
{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 1.0,
        "_source" : {
          "city" : [ ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5A3P2H4BrzeQ9ErqhwUI",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5Q3q2H4BrzeQ9ErqOAXW",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            "sagar"
          ]
        }
      }
    ]
}

Sample output after executing above query:
{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 0.5619608,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 0.0,
        "_source" : {
          "city" : [ ]
        }
      }
    ]
}


text:
Q: How can I take a .java file as a command line parameter? I have a runnable jar file and a .java file. I want to make some processing on .java file (exp: how many operators or how many classes are there in .java file) and I can't take .java file as a parameter, It takes as a string. I wrote down:
C:\Users\aFurkan\eclipse-workspace\Odev1-1\dist>java -jar Program.jar Deneme1.java
Deneme1.java
But I want:
C:\Users\aFurkan\eclipse-workspace\Odev1-1\dist>java -jar Program.jar Deneme1.java
(Processes output from my code)

A: It depends on how your program accepts input.
Case 1: You pass the File Name as a command line parameter, which it seems you're currently trying to do. If so, you need to use the given filename inside your program to open the corresponding file and read from that.
Case 2: You pass the contents of the file you're trying to process as text input via stdin. If so, you can tell the command line to do so using <, in your case java -jar Program.jar < Deneme1.java


text:
Q: Add date to an image collection to export to CSV I calculate the number of fires for a region and export the result to Google Drive as a CSV file, but I can't add the date to the image collection to export, it gives the following error:

ImageCollection (Error) Error in map(ID=2019001): Image.addBands,
  argument 'srcImg': Invalid type. Expected: Image.
  Actual: Date.

Here is the code:
// Load country shapefile
var lsib = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017");
var vn_shape = lsib.filterMetadata('country_na', 'equals', 'Argentina');
print (vn_shape);

// Load fire counts image
var fire = ee.ImageCollection('FIRMS')
             .filterBounds(vn_shape)
             .filterDate('2019', '2020')
print(fire)

var scale = fire.first().projection().nominalScale();

// Filter fire with more than 50% confidence and add a new band representing areas where confidence of fire > 50%
var filterConfidence = function(image) {
  var line_number = image.select('line_number');
  var confidence = image.select('confidence');
  var conf_50 = confidence.gt(50).rename('confidence_50');
  var count_band = line_number.updateMask(conf_50).rename('count');
  // HERE IS THE PROBLEM!
  var date = image.date();
  return image.addBands(count_band)
              .addBands(date);
};

var fire_conf = fire.map(filterConfidence);
print('fire_conf', fire_conf);

// Count for individual image.
var countIndividualImg = function(image) {
  var countObject = image.reduceRegion({
    reducer: ee.Reducer.countDistinct(),
    scale: scale,
    geometry: vn_shape,
    maxPixels: 1e9
  });
  return image.set(countObject);
};
var fire_ind_count = fire_conf.map(countIndividualImg);
print('fire_ind_count', fire_ind_count);
Export.table.toDrive({
  collection: fire_ind_count,
  description: 'FireCounts_gt50_conf',
  selectors:['count','date'],
  fileFormat: 'CSV'
});
print('Total fire count', fire_ind_count.aggregate_sum('count'));

A: One way to do it is to move the date calculation from the function filterConfidence to after the reducer function countIndividualImg, here is the code:
// Load country shapefile
var lsib = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017");
var vn_shape = lsib.filterMetadata('country_na', 'equals', 'Argentina');
print (vn_shape);

// Load fire counts image
var fire = ee.ImageCollection('FIRMS')
             .filterBounds(vn_shape)
             .filterDate('2019', '2020')
print(fire)

var scale = fire.first().projection().nominalScale();

// Filter fire with more than 50% confidence and add a new band representing areas where confidence of fire > 50%
var filterConfidence = function(image) {
  var line_number = image.select('line_number');
  var confidence = image.select('confidence');
  var conf_50 = confidence.gt(50).rename('confidence_50');
  var count_band = line_number.updateMask(conf_50).rename('count');
  //
  // I don't calculate the date here !!!
  //
  return image.addBands(count_band);
};

var fire_conf = fire.map(filterConfidence);
print('fire_conf', fire_conf);

// Count for individual image.
var countIndividualImg = function(image) {
  var countObject = image.reduceRegion({
    reducer: ee.Reducer.countDistinct(),
    scale: scale,
    geometry: vn_shape,
    maxPixels: 1e9
  });
  //
  // Add the date here
  //
  return image.setMulti(countObject).set('date', image.date());
};

var fire_ind_count = fire_conf.map(countIndividualImg);
print('fire_ind_count', fire_ind_count);
Export.table.toDrive({
  collection: fire_ind_count,
  description: 'FireCounts_gt50_conf',
  selectors:['count','date'],
  fileFormat: 'CSV'
});
print('Total fire count', fire_ind_count.aggregate_sum('count'));


text:
Q: Were the Galleons Hermione passed out technically illegal? As Hermione, herself points out, the only danger with the fake coins used for communication among the DA (Dumbledore's Army) would be that someone might actually spend them. This brings up the possibility of using these Galleons to your advantage. While goblins can determine if a Galleon is fake, the regular wizard probably doesn't check for that kind of thing. Therefore, shouldn't those Galleons have been illegal?

A: No, they were not illegal to create or possess.
While they may be illegal to spend, there is evidence that it is legal to create.
In Goblet of Fire, Leprechauns distribute fake gold coins in the presence of the highest members of the Ministry of Magic:

Next moment, what seemed to be a great green-and-gold comet
  came zooming into the stadium. It did one circuit of the stadium,
  then split into two smaller comets, each hurtling toward the goal
  posts. A rainbow arced suddenly across the field, connecting the
  two balls of light. The crowd oooohed and aaaaahed, as though at
  a fireworks display. Now the rainbow faded and the balls of light reunited and merged; they had formed a great shimmering shamrock, which rose up into the sky and began to soar over the stands.
  Something like golden rain seemed to be falling from it —
  "Excellent!" yelled Ron as the shamrock soared over them, and
  heavy gold coins rained from it, bouncing off their heads and seats.
  "Leprechauns!" said Mr. Weasley over the tumultuous applause
  of the crowd, many of whom were still fighting and rummaging
  around under their chairs to retrieve the gold.

The Minister of Magic himself was present at the event:

The box filled gradually around them over the next half hour.
  Mr. Weasley kept shaking hands with people who were obviously
  very important wizards. Percy jumped to his feet so often that he
  looked as though he were trying to sit on a hedgehog. When Cornelius Fudge, the Minister of Magic himself, arrived, Percy bowed
  so low that his glasses fell off and shattered.

These coins were confusable with real currency, as we see:

"Well, the git paid us in leprechaun gold he'd caught from the
  Irish mascots."
  "So?"
  "So," said Fred impatiently, "it vanished, didn't it? By next
  morning, it had gone!"

And

"Leprechauns!" said Mr. Weasley over the tumultuous applause
  of the crowd, many of whom were still fighting and rummaging
  around under their chairs to retrieve the gold.

And

"There you go," Ron yelled happily, stuffing a fistful of gold
  coins into Harry's hand, "for the Omnioculars! Now you've got to
  buy me a Christmas present, ha!"

Yet this showering of fake gold was perfectly legal and done in full compliance with Ministry officials. Although they may not look like Galleons, they definitely looked enough like real currency to confuse people and it was still legal. Hence, it is safe to assume the Ministry does not have any strong anti-counterfeit laws on the books.

A: I don't have an exactly canon answer but possible a practical one.
At first I wondered if they were fake, or if she just enchanted real ones; besides it being expensive, I found the following quote:

She gave each of the members of the D.A. a fake Galleon (Ron became very excited when he first saw the basket and was convinced she was actually giving out gold).

That seems to confirm that they were fake.. but that doesn't necessarily mean they are illegal.  Counterfeit coins that are not meant to be used as coinage aren't exactly illegal; search the net, and you will find many 'Copy of 1XXX' coin sales. (Doing a quick search on a auction site, I found "Copy Silver Clad 1891-CC Morgan Silver Dollar - Rare Carson City Date" on the first page.)
As far as I know, they're not technically illegal if you neither create them, possess them, nor distribute them with the intent that they enter the monetary system as the coins they appear to be.  (Crimes tends to require an intent; sometimes it can assumed to be inherent in the object itself, but rarely -- usually it's what use you put it to or can be shown to intend to put it to that matters.)
A fine point, I'll admit, but it's also what allows parody money (like the $1,000,000 bills you can find at joke shops) and similar items to exist.  Usually they are done in such a way that it is clear at a glance that they are not real.  Prop money in Hollywood is similar, but visibly more believable; it can be told from the real thing, but not at a quick glance.
The statutes in the Muggle world tend to take a form such as:

"every person who possesses or receives, with the intent to pass or facilitate the passage or utterance of any forged, altered, or counterfeit items, [...] with the intent to defraud, knowing the same to be forged, altered, or counterfeit, is guilty of forgery."
  California Penal code §475(a) (forgery).

Note --  'Pass or facilitate the passage or utterance of' -- that's talking about passing them off as the real thing, or helping others to do so and 'with the intent to defraud.'
Or, for a UK example: (since, as Rand al'Thor points out, the books take place in the UK.) [Emphasis added by me]

"14. It is an offence for a person to make a counterfeit of a currency note or of a protected coin, intending that he or another shall pass or tender it as genuine."
Forgery and Counterfeiting Act 1981,

Mere possession isn't usually enough; in most places it has to be accompanied by criminal intent. (See: US v Cardillo and US v Ratner for examples of trying to prove intent, as mere possession wasn't enough.) That said, it can be pretty hard to explain why you have fake money.
Again, looking at the UK Forgery and Counterfeiting Act, Intent is important:
[Emphasis added by me]

"15 (1)It is an offence for a person—
  (a)to pass or tender as genuine any thing which is, and which he knows or believes to be, a counterfeit of a currency note or of a protected coin"

Were Hermione caught with them she might have a lot of explaining to do, but I don't think it's technically illegal.  That said, absent a book on Wizard Law, I'm not sure we can know. (Unless it's directly addressed, in one of the books, and I've just forgotten it.)
Caveat -  I'm not a lawyer; I don't even play one on TV.


text:
Q: Type inference using extended type in typescript I have a factory, that should return a function, based on provided enum key.
This is done in switch case and all the functions there has different payloads.
The goal I'm trying to achieve is to provide such typing to that function, that it will implicitly validate all the type of the payload and return type of the factory. See example below:
// the list of keys that are used for creation
enum keys {
    key1 = 1,
    key2 = 2
}
// here are interfaces, that tie each key with payload, that should be provided.
// Actually, payload is way more complex (another interfaces) but let's keep it simple
interface Test1 {
    key: keys.key1;
    payload: string;
}
interface Test2 {
    key: keys.key2;
    payload: number;
}

// this is the type, that comes to the function below
type tests = Test1 | Test2;

interface ReturnTypeOfTest1 { returnedObject1: number; }
interface ReturnTypeOfTest2 { returnedObject2: string; }
// this is how I'm configuring what should be returned depending on the key
// the return type is set to "ResourceModel", which infers a key from a function payload
// and identifies what exactly it should return
interface ModelOfTest {
    [keys.key1]: ReturnTypeOfTest1;
    [keys.key2]: ReturnTypeOfTest2;
}
type ResourceModel<R extends keys> = ModelOfTest[R];

ResourceModel type is created based on another stackoverflow question Typescript: Return type of function based on input value (enum)
Using type above I can either validate the type of the payload, but loose the validation of the return type:

function getTest(t: tests): any{
    switch (t.key) {
        case keys.key1: {
            const data = t.payload; // is string
            return {returnedObject1: 123 };
        } case keys.key2: {
            const data = t.payload; // is number
            return {returnedObject2: '123' };

        }
    }
}
getTest({key: keys.key1, payload: '1' }); // ReturnTypeOfTest1 | ReturnTypeOfTest2

Or get a proper return type, but loose a validation inside a switch case:
function getTest<T extends tests>(t: T): ResourceModel<T['key']> {
    switch (t.key) {
        case keys.key1: {
            const d = t.payload; // string | number
            return {returnedObject1: 123}; // also an error here, because it wants me to return both ReturnTypeOfTest1 & ReturnTypeOfTest2
        } case keys.key2: {
            const d = t.payload; // string | number
            return null;

        }
    }
}
 getTest({key: keys.key2, payload: 1 }); // ReturnTypeOfTest2

Is there a way to type this thing correctly? Would really appreciate any help on this.

A: This is essentially a missing feature in TypeScript (see microsoft/TypeScript#24085); the compiler cannot reason very well about an unspecified generic type parameter, such as T is inside the implementation of getTest().  When you call getTest(), T is specified, and the return type is computed properly then.  But when you implement getTest(), T is still an unspecified/unresolved type parameter, and the compiler essentially gives up.  Specifically, it does not try to use control-flow-based type analysis to narrow T extends Test1 | Test2 to Test1 or Test2 based on the value of t.key.  This means that at present, generic type signatures like this are more useful to function callers than they are to function implementers.
Perhaps someday there will be a solution to this in the language.  For now, there are workarounds.  The one that I use most often in this case is to add a single overload signature to the function.  Let the callers see the generic overload signature that's useful for them, while the implementation sees the non-generic union-typed signature that's useful for it:
// call signature, seen by callers
function getTest<T extends tests>(t: T): ResourceModel<T['key']>;
// implementation signature, seen only by implementation
function getTest(t: tests): ResourceModel<keys> {
  switch (t.key) {
    case keys.key1: {
      const d = t.payload; // string
      const ret: ResourceModel<keys.key1> = { returnedObject1: 123 };
      return ret;
    } case keys.key2: {
      const d = t.payload; // number
      const ret: ResourceModel<keys.key2> = { returnedObject2: '123' };
      return ret;
    }
  }
}

This still isn't truly type safe; the above would not complain if you switched around the return statements so that ReturnTypeOfTest1 comes back for Test2 and vice versa.  But it's close to the best we can do here, at least for now, so you need to be careful in your implementation.
Let's just make sure the call works as desired:
getTest({ key: keys.key1, payload: "1" }); // ReturnTypeOfTest1
getTest({ key: keys.key2, payload: 1 }); // ReturnTypeOfTest2

Looks good.  Anyway, I hope this helps; good luck!
Playground Link to code


text:
Q: Pass data from Activity in Dialog to another Activity I have an activity that is shown as Dialog and here is my code
/* Open Customer List  */
        final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
        show_customer_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(add_plan.this, customer_list.class);
                startActivity(i);

In that activity I have a code that gets the value from listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView position1    = (TextView) view.findViewById(R.id.list_name);
                TextView position2    = (TextView) view.findViewById(R.id.list_address);
                String customer_name    = position1.getText().toString();
                String customer_address = position2.getText().toString();
                finish();
            }
        });

                    EditText editText = (EditText)findViewById(R.id.cusname);
                    editText.setText(i.getStringExtra("customer_name"));
                }
            });

my problem is how can I pass it to the activity thats behind in my dialog activity


text:
Q: How to get Windows Indexing Service state from code? How to find, how to read Windows Indexing Service state (indexing state) from code? OS is Windows Server 2012 R2.

A: This can be done by using Microsoft.Search.Interop witch I get from here: https://www.nuget.org/packages/tlbimp-Microsoft.Search.Interop/
Then it is easy using documentation from: https://learn.microsoft.com/en-us/windows/win32/api/searchapi/ne-searchapi-catalogstatus to get indexing status.
    Dim status As _CatalogStatus
    Dim reason As _CatalogPausedReason
    Dim manager As CSearchManager = New CSearchManager()
    Dim catalogManager As ISearchCatalogManager = manager.GetCatalog("SystemIndex")
    catalogManager.GetCatalogStatus(status, reason)

All I did on Windows Server 2012 R2.


text:
Q: How to Enable/Disable TextField SWIFT I want to Enable/Disable a UITextField when i press a uibutton.
When I Press The Enable uibutton it enables me to type on a uitextfield
but when I press disable it disables me to type on my uitextfield.

A: Simply follow below steps to getting solution for your question :
1) Prepare IBOutlet for button and textfield
@IBOutlet var btnEnable : UIButton!
@IBOutlet var btnDisable : UIButton!
@IBOutlet var txtValue : UITextField!

2.) Now, in ViewDidLoad() put below lines for tagging button
self.btnEnable.tag = 0
self.btnDisable.tag = 1

3.) Now Create event and wired up this event with both button in storyboard. (note : same event wired up on both button Touch Up Inside)
@IBAction func btnTextfieldInteractionCalled(sender : UIButton)
{
    // "o" means called enable button and "1" means disable button
    if(sender.tag == 0)
    {
        self.txtValue.userInteractionEnabled = true
    }
    else if(sender.tag == 1)
    {
        self.txtValue.userInteractionEnabled = false
    }
}

4.) Now run and check your result. Its work fine.. :)


text:
Q: Modifying non-spatial data from an opengeo server I'm developping an web-application using opengeo server. The data is stored into a PostGIS database, and some tables contains non-spatial data (that is related to the geographical data).
Is there a way to access the data in the non-spatial tables (to populate Ext.data.Store) and modify it?
I've tried many things from now, but none of them have succeed.

*

*To read the data, I have for example set up a WFS layer, and then a WFS store in the web application. It gives me a read access, but no write access. Even if I get the record from the store, modify it, mark it as dirty and commit the changes, I see that the message that is sent to the server does not contain any modification (no updated records) - maybe because the store is not designed to work without layer.

*The REST api does not provide access to the data.

An option could be to use web frameworks, but in that case, which ones are the best to use with Opengeo? I prefer to avoid this solution because it would require to manage an other server application (and it will complicate the management of the creditentials, since authentication is required to access the data).
Thanks!


text:
Q: How to join two operations to create a new operation in Tensorflow? I have the following two operations that I'm repeating multiple times:

  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)

  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)
  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)
  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)
  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)
  x = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)
  x = BatchNormalization()(x)

And I want to create a new Tensorflow operations that joins the two operations into a single operation, with the name Conv3D_bnorm, so that it can be used like:
x = Conv3D_bnorm(2*feature_size, 3, activation="relu", padding="same", strides=2)(x)

BatchNormalization need not have custom parameters.
How do I do that?

A: Just define a function, for example:
def Conv3D_bnorm(x, feature_size):
    conv = Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2)
    bn = BatchNormalization()

    return bn(conv(x))

BUT more logical is to use a keras's Sequential module:
import tensorflow as tf

x = ...

Conv3D_bnorm = tf.keras.Sequential()
Conv3D_bnorm.add(Conv3D(2*feature_size, 3, activation="relu", padding="same", strides=2))
Conv3D_bnorm.add(BatchNormalization())

x = Conv3D_bnorm(x)


text:
Q: Delphi Post Values to php file but cannot access values from PHP files I am using delphi to post values to a php file for processing. I am using TWebPost from TMS and previously the module worked perfectly except for replacing all the spaces with a + now however i have tried to change the PostContentType from ctFormURLEncoded to ctMultiPartForm as they recommended.
Since the change I can no longer access the variables I post using the $_POST function in PHP.
Anybody have an idea on how the PHP file can access the variables?

A: There are same small example for using TWebPost and php script in a Delphi.
This example UwpdemoVersionProgram I was do based on the GitHub demo example for TWebPost link demo for Uwpdemo.pas
But better will be if you register at GitHub page  page for registering in a GitHub server
GitHub is a repository for many project , where developer can put own project and get acces to many project from other's developer's . After registering you can download many examples in a one ziped file .
unit UwpdemoVersionProgram;
interface
uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  WebPost, StdCtrls, ShellApi;

type
  TForm1 = class(TForm)
  WebPost1: TWebPost;
  Button1: TButton;
  procedure Button1Click(Sender: TObject);
 private
    { Private declarations }
  public
    { Public declarations }
   procedure GetVersionProgramFromRemote(var StringReceivedFromRemote:  AnsiString);
  end;
var
  Form1: TForm1;
  implementation
 {$R *.DFM}
 procedure TForm1.GetVersionProgramFromRemote(var StringReceivedFromRemote:  AnsiString);
var
 wpi:twebpostitem;
 Response: TMemoryStream;
 StrResponse: AnsiString ;
 begin
 Response := TMemoryStream.Create;
 webpost1.Server:='your_sever.com';;  //cannot be with http://
 webpost1.Action:='/subdirectory/GetVersionProgram_Post.php'; //  script php  with it will be cooperating program from Delphi
  webpost1.items.Clear;
 with webpost1.items do
  begin
   wpi:=add;
   wpi.name:='Name_program';
   wpi.value:= 'AWARD_SECRETARY.exe';
    //if you want obtain more data , repeat this there above lines with another's parameters
  end;
 if webpost1.execute then
  begin
   webpost1.savetofile('results.txt');
   Response:= TMemoryStream(webpost1.PostResult);
   StrResponse:=AnsiString( Response);
   StringReceivedFromRemote:=StrResponse;
   end;

procedure TForm1.Button1Click(Sender: TObject);
 var StringReceivedFromRemote: AnsiString;
  begin
   GetVersionProgramFromRemote(StringReceivedFromRemote);
  end;
----------------------------------------------------------------
 Php script GetVersionProgram_Post.php is as follow
<?PHP
include ('info.php');
 $link = mysql_connect($db_server, $db_username, $db_password);
 if (!$link) {
    die('Cannot conect : ' . mysql_error());
 }
 echo 'Connect was do '.chr(13)  ;
 mysql_select_db($db_database);
$Name_program=$_POST['Name_program'];   //this work work with  TWebPost - but value must be present not in a URL
                                                                            // but only in a webpost1.items  as this wpi.value:= 'AWARD_SECRETARY.exe';
 $result = mysql_query("SELECT *  FROM ACTUAL_PROGRAM_VERSION WHERE NAME_PROGRAM = '$Name_program' ");
 if (!$result) {
    echo 'Cannot run query : ' . mysql_error();
   exit;
 }
$row = mysql_fetch_row($result);
echo $row[0].chr(13)   ; // NAME_PROGRAM
echo $row[1].chr(13)   ; // ACTUAL_VERSION
echo $row[2].chr(13)   ; // CREATION_DATE
echo $row[3].chr(13)   ; // ID_PROGRAM
mysql_close($link);
?>

Structure in a MYSQL is:
   NAME_PROGRAM    varchar(32)
   ACTUAL_VERSION  varchar(32)
   CREATION_DATE   varchar(12)
   ID_PROGRAM      int(11)


text:
Q: How to use return value from ExecutorService I am running a for loop under ExecutorService (which sends emails)
If any of the return type is fail , i need to return return resposne as "Fail"
or else i need to return return resposne as "Success"
But i couldn't able  to return value in this case
I tried as this way
import java.text.ParseException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) throws ParseException {
    String response =   getDataCal();
    System.out.println(response);
    }
    public static String getDataCal() {
        ExecutorService emailExecutor = Executors.newSingleThreadExecutor();
        emailExecutor.execute(new Runnable() {

            @Override
            public void run() {
                try {

                    for(int i=0;i<2;i++)
                    {

                    String sss = getMYInfo(i);
                    System.out.println();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
        return sss;
    }

    public static String getMYInfo(int i)
    {
        String somevav = "success";//Sometimes it returns fail or success
        if(i==0)
        {
            somevav ="success";
        }
        else
        {
            somevav ="fail";
        }

        return somevav;
    }

}

A: It seems that you want to wait for the completion of the task that you've submitted (why use an ExecutorService?)
You can do that by submitting a Callable<T>, the submit method will then return a Future<T>. You can then get() to wait for completion and obtain the result.

A: Call your getMYInfo(i) in Callable<String>, submit this callable to executor, then wait for competition of Future<String>.
private static ExecutorService emailExecutor = Executors.newSingleThreadExecutor();

public static void main(String[] args) {
    getData();
}

private static void getData() {
    List<Future<String>> futures = new ArrayList<>();
    for (int i = 0; i < 2; i++) {
        final Future<String> future = emailExecutor.submit(new MyInfoCallable(i));
        futures.add(future);
    }
    for (Future<String> f : futures) {
        try {
            System.out.println(f.get());
        } catch (InterruptedException | ExecutionException ex) {
        }
    }
}

public static String getMYInfo(int i) {
    String somevav = "success";
    if (i == 0) {
        somevav = "success";
    } else {
        somevav = "fail";
    }
    return somevav;
}

private static class MyInfoCallable implements Callable<String> {

    int i;

    public MyInfoCallable(int i) {
        this.i = i;
    }

    @Override
    public String call() throws Exception {
        return getMYInfo(i);
    }

}


text:
Q: iOS push notifications and AppDelegate methods behaviour I did some research on lots of stackoverflow issues and websites in trying to figure out how do the iOS push notifications influence AppDelegate lifecycle methods and when is which method (not) getting triggered. Main focus of the research was on "standard" iOS push notifications (with alert field) and silent ones (with just content-available set to 1) and on AppDelegate's application:didReceiveRemoteNotification and application:didFinishLaunchingWithOptions methods.
I don't want to ask lots of questions for different scenarios, but would rather try to write down the statements about different test cases I tried and ask you after that:
Is there any statement that is wrong and if yes, which one and why?

Scenario 1: App has been used and put to background by tapping the home button.

*

*If standard push notification is sent, in the moment of push notification arrival, none of the methods gets triggered, app remains inactive in background. Once push notification has been tapped and app got opened because of it, application:didReceiveRemoteNotification method got called and application:didFinishLaunchingWithOptions doesn't get called. I tested this scenario right after putting the app to background and also after an app being in background for more than an hour - same behaviour. I guess that if for some reason iOS decided to kill my app while being in background, this test case becomes like Scenario 2, statement 1 from below, right?

*If silent push notification is sent, in the moment of the push notification arrival, application:didReceiveRemoteNotification method got called and application:didFinishLaunchingWithOptions doesn't get called.

Scenario 2: App has been used and killed by swiping it out of the list of running apps.

*

*If standard push notification is sent, in the moment of push notification arrival, none of the methods get triggered, app remains killed. Once push notification has been tapped and app got opened because of it, application:didReceiveRemoteNotification method got called and application:didFinishLaunchingWithOptions doesn't get called.

*If silent push notification is sent, none of the methods gets triggered since silent push notifications fail to be sent to the app that got killed. After opening an app after notification is sent, application:didFinishLaunchingWithOptions gets called as part of the normal flow and without any push notification information. application:didReceiveRemoteNotification doesn't get called.

If you can maybe think of some other real life scenarios that I maybe forgot to mention, I would be really grateful to find out about them and what happens in those cases.
Cheers

Update #1
Thanks to Sandeep Bhandari for the update and additional scenarios. I forgot to mention in my original question that I was exploring scenarios in which application is arriving to the app that is currently not in the foreground for whatever reason.
Adding Sandeep's scenarios to the list:

Scenario 3: App is being used and push notification arrives.

*

*If standard push notification is sent application:didReceiveRemoteNotification method will get called. application:didFinishLaunchingWithOptions will not get called.

*If silent push notification is sent application:didReceiveRemoteNotification method will get called. application:didFinishLaunchingWithOptions will not get called.

Scenario 4: App being alive in background.

*

*If standard push notification is sent application:didReceiveRemoteNotification method will get called. application:didFinishLaunchingWithOptions will not get called.

*If silent push notification is sent application:didReceiveRemoteNotification method will get called. application:didFinishLaunchingWithOptions will not get called.

A:
From an experience and digging alot on the iOS push notification. App
  being in foreground or alive in background. both situations triggers
  same delegate methods. only didReceiveRemoteNotification.

The silent push notification have a different handler: (content-available 1 means silent notification)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    }

When app is dead. didReceiveRemoteNotification never called for regular push notification. It must be handled in didFinishLaunchingWithOptions as following:
// handle notification when app is closed.
let notification = launchOptions?[.remoteNotification]
if notification != nil {
    self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable : Any])
}

Additional information:
To test receiving push notification when app is killed. remove from the list that appears when double tapping home button?
The proper way to see the logging and do debugging is by editting the run scheme and selecting Wait for executable to be launched:

Run the app from the xcode. Then send push notification from server and then tap the notification from notification center.

A: I don't see any issue in the statement you made there, but I believe you missed to iterate over two more scenarios that I can think of.

*

*App is in foreground and receives the push notification : didReceiveRemoteNotification gets called as soon as APNS gets delievered to iOS and you can handle it by checking application state in didRecieveRemoteNotification Method.

*App being alive in background : I believe you are aware of background modes of iOS. If app is making use of expiration handler, app will be alive even if you put it to background by tapping on home button. Duration the app lives in background depends on various factors (some tutorials say app remains alive for 3 mins which I can't guarantee) Even in this case didReceiveRemoteNotification gets called as soon as APNS gets delievered to iOS. Only this time app wont be in foreground but yet its alive!!!


text:
Q: Mysql Stored Procedures Column Type Reference In PL/SQL you can reference the type of a table column for procedure variables and arguments using the TABLE.COLUMN_NAME%type syntax. This makes code maintenance much easier.  Is there an equivalent of this in the mysql stored procedure language?
Where might one need this? Consider the following insert statement:
INSERT INTO NL_LIST (NAME, EMAIL)
    SELECT
        NAME,
        normalizeEmail(EMAIL)
    FROM
        RAW_NL_LIST;

For this i would like to be able to define normalizeEmail in(roughly) the following way:
CREATE FUNCTION normalizeEmail(email RAW_NL_LIST.EMAIL%type)
RETURNS NL_LIST.EMAIL%type
BEGIN
... implementation here
END;

A: No, you cannot automatically match the type used in the table definition with the type in a stored procedure.
You will have to lookup the table definition yourself and enter the correct type.
See: http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html
Here it says:
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body

CREATE
    [DEFINER = { user | CURRENT_USER }]
    FUNCTION sp_name ([func_parameter[,...]])
    RETURNS type
    [characteristic ...] routine_body

proc_parameter:
    [ IN | OUT | INOUT ] param_name type

func_parameter:
    param_name type

type:
    Any valid MySQL data type    <<<-- no special magic allowed

....


text:
Q: Find the number of inequivalent two-dimensional complex representations of the group $Z_4$ Find the number of inequivalent two-dimensional complex representations of the group $Z_4$
Any hints will be greatly appreciated. Thank you all

A: Hint: Using Maschke's Theorem, any such two-dimensional representation of $\mathbb{Z}_4$ is the direct sum of irreducible representations of $\mathbb{Z}_4$. You need to find the irreducible representations of the group (which all turn out to be one-dimensional because the group is abelian). Thus, any two-dimensional representation is the sum of two of these irreducible representations. The question then becomes a combinatorial one: how many ways can you choose two irreducible representations?


text:
Q: How to fix: "Cannot assign value of type 'SelfieListViewController' to type '(UIImagePickerControllerDelegate & UINavigationControllerDelegate)?'" I am getting this error:
Cannot assign value of type 'SelfieListViewController' to type '(UIImagePickerControllerDelegate & UINavigationControllerDelegate)?'
For this function:
@objc func createNewSelfie()
    {
        //Create a new image picker
        let imagePicker = UIImagePickerController()

        //If a camera is a available, use it; otherwise, use the photo library
        if UIImagePickerController.isSourceTypeAvailable(.camera)
        {
            imagePicker.sourceType = .camera

            //If the front-facing camera is available, use that
            if UIImagePickerController.isCameraDeviceAvailable(.front)
            {
                imagePicker.cameraDevice = .front
            }
        }
        else
        {
            imagePicker.sourceType = .photoLibrary
        }

        //We want this object to be notified when the user takes a photo
        imagePicker.delegate = self

        //Present the image picker
        self.present(imagePicker, animated: true, completion: nil)
    }


text:
Q: How to use the spread operator and bash variables with mkdir (to create subfolders) - Bash script Problem 1: I'm trying to create subfolders for the projects that started at certain year. To do that,I tried to use the spread operator but the result was simply {<start_year>..<end_year>}.  I tried with the comma operator,and it worked. Maybe i'm missing something.
    └── projects
        ├── 2018
        ├── 2019
        ├── 2020
        └── 2021

## The code

declare -i START_DATE=$(date --date="3 years ago" +'%Y')
declare -i END_DATE=$(date +'%Y')

mkdir -p projects/{$START_DATE..$END_DATE}

________________________________________
result:

         projects
         └── {2018..2021}

Problem 2: If I try to use a variable SUB_PROJECTS={$START_DATE,$END_DATE} to be readable and easier to change values, the bash command cannot distiguish the symbols, only assume as a whole string. How I can solve this?
SUB_PROJECTS={$START_DATE,$END_DATE}
mkdir -p projects/$SUB_PROJECTS
________________________________________

result:

         projects
         └── `{2018,2021}`


text:
Q: Link for iOS app rating I've been trying to direct users to the app store (iTunes) to rate my app.
I can't get the right link. Users say that when they click the button, nothing happens.
This is the current link I'm using:
tms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXX

And in my code, which is for Adobe AIR, this is the line:
navigateToURL(new URLRequest("tms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXX"));

(Of course XXXXX is replaced with my App ID).
Appreciate any help.
Thanks.

A: This is core objective-c code. Its very self-explanatory. All you need to do is to check whether the device is running iOS 7 or prior. In iOS 7, the URL for rating page is different.
URL Format for iOS 7 or prior:   itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXXXX
URL Format for above iOS 7:   itms-apps://itunes.apple.com/app/idXXXXXX
In Objective-C, it looks like this:
NSString *cAppleID = @"YOUR_APP_ID";
NSString* iOS7AppStoreURLFormat = @"itms-apps://itunes.apple.com/app/id%@";
NSString* iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@";
NSString* url = [[NSString alloc] initWithFormat: ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f) ? iOS7AppStoreURLFormat : iOSAppStoreURLFormat, cAppleID];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];

In AS3, it would look more like this (iOSVersion getter from How to determine the IOS version from within an Flex mobile app (AIR)):
//Put in a Utils class
public static function get iOSVersion():uint {
    var iosVersion:String = Capabilities.os.match( /([0-9]\.?){2,3}/ )[0];
    return Number( iosVersion.substr( 0, iosVersion.indexOf( "." ) ) );
}

var osVersion:Number = Utils.iOSVersion;
var url:String;
if (osVersion >= 7.0) {
    url = "itms-apps://itunes.apple.com/app/idXXXXXX";
} else {
    url = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXXXX";
}

navigateToURL(new URLRequest(url));