text:
Q: cannot do .hide on a dialog ERROR: Attempt to invoke virtual method on a null object I'm trying to dismiss my costume alert dialog but it errors me -

Attempt to invoke virtual method 'void android.app.Dialog.dismiss()'
  on a null object reference

but the object isn't null i initialize it before hand. and i don't understand why it is null,
but then when i do - mainDialog.hide()
it errors me out that I'm trying to do hide on a null reference.
I don't really know why this is happening.
this is my activity
package apps.radwin.wintouch;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.concurrent.Callable;

import apps.radwin.wintouch.devicePackage.wifiWrapper;
import apps.radwin.wintouch.screenManagers.aligmentManager;

public class Scanning_Barcode_Activity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    //declare locals
    ImageView backgroundImage;
    Button scanButton, nextButton;
    TextView scanBarcodeText, loaderScreenMainText;
    ProgressBar progressBar;
    SharedPreferences boxSharedPref;
    SharedPreferences.Editor editor;
    Dialog mainDialog;

    aligmentManager aligmentManagerClass =  new aligmentManager();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

        //brings up the toolbar to view
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //inserts the Fab Button
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        //navigation view handler
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        /////////////////////////////////////////////////////////
        //START OF IMPLEMENTATION
        //CASTING and POINTING TO DISPLAY
        backgroundImage = (ImageView) findViewById(R.id.scanningBarcodeScreen_imageView_bacgkroundImage);
        scanButton = (Button) findViewById(R.id.scanningBarcodeScreen_button_scanButton);
        nextButton = (Button) findViewById(R.id.scanningBarcodeScreen_button_nextButton);
        scanBarcodeText = (TextView) findViewById(R.id.scanningBarcodeScreen_textView_scanHeadline);

        //prepers the shared prefrence
        boxSharedPref = getSharedPreferences("ULCSharePrefrenceTable", Context.MODE_PRIVATE);
        editor = boxSharedPref.edit();

        //add listeners
        scanButton.setOnClickListener(this);
        nextButton.setOnClickListener(this);

        //assining an image
        backgroundImage.setImageResource(R.drawable.barcodeactivitybg);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        //notify's the aligment manager that the screen has entered
        aligmentManagerClass.barcodeScreenInitilized(getApplicationContext());

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.scanning__barcode_, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_aligment) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Scanning_Barcode_ Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://apps.radwin.wintouch/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Scanning_Barcode_ Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://apps.radwin.wintouch/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    //listener for buttons
    @Override
    public void onClick(View v) {

//
//        loadToastModule loadToastMD = new loadToastModule();
//        LoadToast lt = loadToastMD.getWidget(this, "Loading");

        switch (v.getId()) {

            //scan button was pressed
            case R.id.scanningBarcodeScreen_button_scanButton:

                aligmentManagerClass.pressedScanBarcodeButton(); //notify aligment manager scan was pressed

                new IntentIntegrator(this).initiateScan(); // opens up Scan intent > ZXING

                break;

            //next button was pressed
            case R.id.scanningBarcodeScreen_button_nextButton:

                //showLoadingScreen();
                aligmentManagerClass.pressedNextButtonFromBarcodeScreen();

                break;

        }

    }

    public void showLoadingScreen() {

    }

    Callable  wifiStateCallback = new Callable() {

        @Override
        public Object call() throws Exception {

            return null;
        }
    };

    //Interface for the callback function - Defyining the interface
    public interface isWifiOnCallableInterface {

        void isWifiOnCallable(boolean result);
    }

    //the actual callback that will be called once the call will come back
    isWifiOnCallableInterface callbackFunctionForisWifiOn  = new isWifiOnCallableInterface() {

        @Override
        public void isWifiOnCallable(boolean result) {

            Log.d ("myLogs", "One?");

            if (result == true) { //wifi is ON

            }else { //wifi is OFF

                try {
                    mainDialog.hide(); //THIS IS MY PROBLEM IN HERE , THIS IS MY PROBLEM IN HERE
                } catch (Exception e) {
                    e.printStackTrace();
                }

//                AlertDialog offdialog = getAlertDialogForWifiOff(); //shows to user alert dialog for wifi is off
//                offdialog.show(); // show it

            }
        }
    };

    public AlertDialog getAlertDialogForWifiOff () {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                Scanning_Barcode_Activity.this);

        alertDialogBuilder.setTitle("Wifi Problem");// set title

        alertDialogBuilder // set dialog message
                .setMessage("Yopur wifi is OFF please click Turn On to turn it back on")
                .setCancelable(false)
                .setPositiveButton("Turn ON",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) { //on button clicked

                        wifiWrapper WifiWrapper = new wifiWrapper();
                        WifiWrapper.toggleWiFi(Scanning_Barcode_Activity.this, true); // turns wifi ON

                    }
                })
                .setNegativeButton("Exit APP",new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog,int id) { // exit app button clicked
//                        dialog.cancel(); - cancels the dialog
                        Scanning_Barcode_Activity.this.finish(); // exits app
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        return alertDialog;

    }

    //results when activity enters a callback sent out to another activity
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); //retrieve scan result

        aligmentManagerClass.gotScanFromBarcode();

        if (scanningResult != null) {

            String scanContent = scanningResult.getContents(); //we have a result
            String scanFormat = scanningResult.getFormatName();

            try { //sets the text to scan content

                Log.d("myLogs", "length is: " + scanContent.length()); //scan sucssesful
                scanBarcodeText.setText(scanContent);

                editor.putString("boxID", scanContent); //saves the data as antenaNamein shared prefrences
                editor.commit();

                if (checkIfIdMatched(scanContent) == true) { //checkks if id is maching the one in the workorder

                    aligmentManagerClass.scanFromBarcodeApproved(); //ID MACHED

                    wifiWrapper myWifiWrapper = new wifiWrapper(); //- INIZILIZING WIFI
                    myWifiWrapper.checkWifiState(this, callbackFunctionForisWifiOn);
                }

            } catch (Exception e) {
                e.printStackTrace();
                //do something in case scan fails
                aligmentManagerClass.scanFromBarcodeFailed(); //ID MACHED

            }

            mainDialog = getCostumeDialog ();
            mainDialog.show(); //initlizes the costume dialog

        } else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    //gets a costume dialog to use
    private Dialog getCostumeDialog() {

        Dialog loadingDialog = new Dialog(this);
        //loadingDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        loadingDialog.setContentView(R.layout.aligment_manager_loader_layout);
        //dialog.setTitle("Loading");
        //sets the dialog Cancelable
        loadingDialog.setCancelable(true);

        //set up text
        //loaderScreenMainText.setText("Loading Wifi");

        //progressBar = (ProgressBar) dialog.findViewById(R.id.barcodeScanning_spinkit);
        //DoubleBounce doubleBounce = new DoubleBounce();
        //progressBar.setIndeterminateDrawable(doubleBounce);
        //loadingProgressBar.setVisibility(ProgressBar.VISIBLE);

        //now that the dialog is set up, it's time to show it

        return loadingDialog;

    }

    //checkks if id is maching the one in the workorder
    private boolean checkIfIdMatched(String unitId) {
        boolean isMached = true;
        //for now just simulates a working order that returns true
        return isMached;
    }

}

can someone help me on this?

A: You have his error because your variable mainDialog is null when you call the hide method.
I don't know the logic of your code, but the easiest way to get rid of this error is to check if the mainDialog variable has been initialized :
if (mainDialog != null) {
    mainDialog.hide();
}

A:  mainDialog = getCostumeDialog ();

call this on create since mainDialog is global , in this manner it will be initialized then button click will happen and onactivityResultback will get called


text:
Q: Zero stroke-width in SVG Having used Postscript for years, I am now learning SVG. There is a feature of PS that I have not been able to replicate so far: zero-width lines. In PS, a line with zero width is always visible: PostScript converts zero line width to the smallest printable width. On the screen, when zooming they never get any thinkness, yet are visible no matter the scale. I have used them when I wanted to render very thin lines, without worring about the final resolution I was going to use, and they turned out really useful.
However, in the official SVG docs (https://www.w3.org/TR/svg-strokes/) it says that:

A zero value causes no stroke to be painted. A negative value is invalid.

Is there a way in SVG to build zero-width lines in the sense of PostScript?

A: As Robert said, the nearest thing to what you want in SVG is vector-effect="non-scaling-stroke".  This fixes the stroke width at 1 no matter how the SVG is scaled.
This works on Chrome and Firefox (and probably Opera - haven't checked), but AFAIK not IE/Edge.

<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"
        fill="none" stroke="black" stroke-width="1"
        vector-effect="non-scaling-stroke"/>
</svg>

Note that antialiasing will come into play depending on the position of the lines. The position will be affected by the scale.
If your lines are rectilinear (horizontal or vertical), you might also want to use shape-rendering="crispEdges". This will turn off antialiasing for the shape on which it is used, resulting in sharp one-pixel lines.

<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="80" height="80"
        fill="none" stroke="black" stroke-width="1"
        vector-effect="non-scaling-stroke" shape-rendering="crispEdges"/>
</svg>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Можно ли в Python присвоить переменной вызов функции? В командной строке Windows для очистки вывода используется команда cls.
Для того, чтобы очистить вывод интерпретатора, вызванного в командной строке, нужно уже прописывать такой код:
>>> import os
>>> os.system('cls')

Это можно упростить, создав функцию:
>>> def cls():
...     os.system('cls')
...
>>>

И вызывать ее уже вот так: >>> cls()
Но все же хотелось бы как-то добиться нужного результата именно командой cls, без скобок от функции.
Первое, что пришло в голову - присвоить вызов функции переменной. Но это, к сожалению, не работает :(
Как можно реализовать мою идею? Если можно вообще...

Вот попытки присвоения вызова функции переменной, ниже их результат.
>>> cls = lambda: cls()

>>> cls
<function <lambda> at 0x01D76D60>

>>> from functools import partial
>>> cls = partial(clr)

>>> cls
functools.partial(<function cls at 0x01CA7778>)

A: Можно переопределить __repr__. Именно этот метод вызывается когда нужно показать значение объекта в виде строки.
Приблизительно так:
class CLS:
    def __repr__(self):
        os.system('cls')
        return ''

cls = CLS()

Теперь ввод одного лишь cls в командную строку будет вызывать CLS.__repr__.


text:
Q: how Python Regex work for an expression like (\w+) vs (\w.+) Please consider the following example
line="18/11/1992"

Here's the program I wrote.Please pay attention to the regex expressions I've used try to match the above line
matchob1 = re.search(r'([\w+\/+])',line)
matchob2 = re.search(r'([\w\/]+)',line)    if matchob1 != None :
    print('The match produced the following info for matchob1 - '+matchob1.group(1))
else:
    print('Sorry no match found in the line : '+str(line)+' for matchob1')
if matchob2 != None :
    print('The match produced the following info for matchob2 - '+matchob2.group(1))
else:
    print('Sorry no match found in the line : '+str(line)+' for matchob2')

When I ran the script I got the following output
The match produced the following info for matchob2 - 1
The match produced the following info for matchob1 - 18/11/1992

I'd like to know whether my understanding is right
The first regex matched only 1 because it looked for \w+ or /+ inside the range [].
The second regex looked for either a word (\w+) or / (/+) followed by any number of occurrences of the pattern within the range []. Is my understanding right or can someone give me a more definitive answer  to help me understand this better ?

A: [\w+\/+] matches a single character from the given list that is, it would match a word character or + or / . Character class like this [+++] or [+]
 would match all the literal + symbols. So you don't need to repeat the same pattern twice inside a character class.
[\w\/]+ + after the character class would repeat  pattern inside the character class one or more times. So this would match word characters or / one or more times. And () called capturing groups.

A: The match produced the following info for matchob2 - 1
Because the character class you mentioned will match only one character as you had not quantified it.So it matched the first character 1.
Note:+ inside character class loses special quantifying powers.
The match produced the following info for matchob1 - 18/11/1992
Because it cannot match space it matches any words with can include \.


text:
Q: Numerical Computation of the Helmholtz-Leray Projection Let

*

*$d\in\mathbb N$

*$\Lambda\subseteq\mathbb R^d$ be bounded and open

*$u\in L^2(\Lambda,\mathbb R^d)$

It's well-known that there is a weakly differentiable $p\in L_{\text{loc}}^2(\Lambda)$ with $\nabla p\in L^2(\Lambda)$, $$\Delta p=\nabla\cdot u\;,\tag 1$$ i.e. $$\langle\nabla p,\nabla\phi\rangle_{L^2(\Lambda,\:\mathbb R^d)}=\langle u,\nabla\phi\rangle_{L^2(\Lambda,\:\mathbb R^d)}\;\;\;\text{for all }\phi\in C_c^\infty(\Lambda)\;,\tag 2$$ and $$\left.\frac{\partial p}{\partial\nu}\right|_{\partial\Lambda}={\rm n}\cdot u\tag 3\;,$$ where $\nu$ denotes the outer unit normal field of $\partial\Lambda$.

Now, I want to compute $p$ numerically in the case $\Lambda=(0,a)\times(0,b)$ with $a,b>0$.

I'm not searching for a state-of-the-art algorithm; just a simple solver. However, I would be happy about any book/paper where this problem is considered; no matter which method is used.


text:
Q: converting a python string to a variable I have read almost every similar question but none of them seems to solve my current problem.
In my python code, I am importing a string from my bashrc and in the following, I am defining the same name as a variable to index my dictionary. Here is the simple example
obs = os.environ['obs']
>> obs = 'id_0123'

id_0123 = numpy.where(position1 == 456)
>> position1[id_0123] = 456
>> position2[id_0123] = 789

But of course, when I do positions[obs], it throws an error since it is a string rather than an index (numpy.int64). So I have tried to look for a solution to convert my string into a variable but all solution suggesting to either convert into a dictionary or something else and assign the string to an integer, But I can not do that since my string is dynamic and will constantly change. In the end, I am going to have about 50 variables and I need to check the current obs corresponding to which variable, so I could use it as indices to access the parameters.
Edit:
Position1 and Position 2 are just bumpy arrays, so depending on the output of os.environ (which is 'id_0123' in this particular case), they will print an array element. So I can not assign 'id_0123' another string or number since I am using that exact name as a variable.
The logic is that there are many different arrays, I want to use the output of os.environ as an input to access the element of these arrays.

A: You could use the fact that (almost) everything is a dictionary in Python to create storage container that you index with obs:
container = lambda:None

container.id_0123 = ...

...

print(positions[container.__dict__[obs]])

Alternatively, you can use globals() or locals() to achieve the desired behavior:
import numpy
import os
def environment_to_variable(environment_key='obs', variable_values=globals()):
    # Get the name of the variable we want to reference from the bash environment
    variable_name = os.environ[environment_key]
    # Grab the variable value that matches the named variable from the environment. Variable you want to reference must be visible in the global namespace by default.
    variable_value = variable_values[variable_name]
    return variable_value

positions = [2, 3, 5, 7, 11, 13]
id_0123 = 2 # could use numpy.where here
id_0456 = 4

index = environment_to_variable(variable_values=locals())

print(positions[index])

If you place this in a file called a.py, you can observe the following:
$ obs="id_0123" python ./a.py
5
$ obs="id_0456" python ./a.py
11

This allows you to index the array differently at runtime, which is what it seems like your intention is.

A: If you wanted to use a dictionary instead, this would work.
obs = 'id_0123'
my_dict = {obs: 'Tester'}
print (my_dict [obs])
print (my_dict ['id_0123'])


text:
Q: Parsing XML in Python with ElementTree - findall() I'm using the documentation here to try to get only the values (address , mask ) for certain elements.
This is an example of the structure of my XML:
    <?xml version="1.0" ?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:52622325-b136-40cf-bc36-85332e25b6f3" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
    <data>
            <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
                    <interface>
                            <GigabitEthernet>
                                    <name>1</name>
                                    <ip>
                                            <address>
                                                    <primary>
                                                            <address>192.168.40.30</address>
                                                            <mask>255.255.255.0</mask>
                                                    </primary>
                                            </address>
                                    </ip>
                                    <logging>
                                            <event>
                                                    <link-status/>
                                                    </event>
                                            </logging>
                                            <mop>
                                                    <enabled>false</enabled>
                                                    <sysid>false</sysid>
                                            </mop>
                                            <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
                                                    <auto>true</auto>
                                            </negotiation>
                                    </GigabitEthernet>
                                    <GigabitEthernet>
                                            <name>2</name>
                                            <ip>
                                                    <address>
                                                            <primary>
                                                                    <address>10.10.10.1</address>
                                                                    <mask>255.255.255.0</mask>
                                                            </primary>
                                                    </address>
                                            </ip>
                                            <logging>
                                                    <event>
                                                            <link-status/>
                                                    </event>
                                            </logging>
                                            <mop>
                                                    <enabled>false</enabled>
                                                    <sysid>false</sysid>
                                            </mop>
                                            <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
                                                    <auto>true</auto>
                                            </negotiation>
                                    </GigabitEthernet>
                                    <GigabitEthernet>
                                            <name>3</name>
                                            <ip>
                                                    <address>
                                                            <primary>
                                                                    <address>30.30.30.1</address>
                                                                    <mask>255.255.255.0</mask>
                                                            </primary>
                                                    </address>
                                            </ip>
                                            <logging>
                                                    <event>
                                                            <link-status/>
                                                    </event>
                                            </logging>
                                            <mop>
                                                    <enabled>false</enabled>
                                                    <sysid>false</sysid>
                                            </mop>
                                            <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
                                                    <auto>true</auto>
                                            </negotiation>
                                    </GigabitEthernet>
                                    <GigabitEthernet>
                                            <name>4</name>
                                            <logging>
                                                    <event>
                                                            <link-status/>
                                                    </event>
                                            </logging>
                                            <mop>
                                                    <enabled>false</enabled>
                                                    <sysid>false</sysid>
                                            </mop>
                                            <negotiation xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ethernet">
                                                    <auto>true</auto>
                                            </negotiation>
                                    </GigabitEthernet>
                            </interface>
                    </native>
            </data>

Working off this example in the documentation, I've tried something like this:
import xml.etree.ElementTree as ET
tree = ET.parse("C:\\Users\\Redha\\Documents\\test_network\\interface123.xml")
root = tree.getroot()

for i in root.findall('native'):
  print(i.tag)

But it returns nothing . I've tried other things to no success. Any ideas? All advice appreciated. Thank you!

A: Consider using namespaces when referencing XML elements:
import xml.etree.ElementTree as ET

# declare XML namespaces
namespaces = {'native': 'http://cisco.com/ns/yang/Cisco-IOS-XE-native'}

tree = ET.parse("C:\\Users\\Redha\\Documents\\test_network\\interface123.xml")
root = tree.getroot()

# call findall() using previously created namespaces map
for i in root.findall('.//native:native', namespaces):
  print(i.tag)


text:
Q: Run mongodb query in a loop I have a user collection with IDs. I would like to run this query for all of them
db.user.updateMany(
    {
        "_id": ObjectId(USER_ID)
    },
    {
        $set: {
            "player_ids": db.player.find(
                {
                    "author._id": ObjectId(USER_ID)
                }
            ).toArray().map(function(u) {
                return u._id;
             })
        }
    })

the script runs correctly for hardcoded USER_ID. I would like to run it for all IDs automatically.

A: Unfortunately you cannot use $lookup in the set pipeline.  You will have to do it in a 2-step loop:
db.user.find().forEach(function(doc) {
    var ids = [];
    db.player.find({"author._id": doc['user']}).forEach(function(d2) {
                        ids.push(d2['_id']);
            });
    db.user.update({"_id": doc['_id']}, {$set: {"player_ids":ids}});
    });


text:
Q: Determine a theoretically optimal screw shape wrt holding or withdrawal strength I was stating at a hex screw sort of in awe of the physics underlying this rather simple mechanical system. It got me thinking, how would one go about determining the optimal shape for a screw to maximize its holding strength for a given volume of material? What maths and engineering concepts are required to solve it and has this already been considered?

A: Screws come in various types depending on their application.  As @Nielsneilson said, they have indeed been optimized (approximately) over a long time, but the "fitness function" for optimization depends on multiple factors. You asked specifically about holding strength in a given material.  The brittleness and elasticity of the material, as well as the coefficient of friction between the material and the material of the screw, are both important.  If the concern is only that the screw may become "unscrewed" due to vibration or other such causes, the important factor is the friction.  If the concern is that the screw may get pulled out of the material, breaking the material in the process, it is a more difficult problem.
An extreme case is that of screws designed for anchoring in drywall (plasterboard). Because drywall crumbles easily, closely space threads in a screw will simply turn the drywall to powder so the screw has essentially nothing to hold it in place.  The solution is to shape drywall anchor screw threads a bit like an auger: a thin helical blade that slices a spiral path through the plaster, leaving intact most of the plaster that is within the cylindrical envelope of the screw.
Another extreme case is that of machine screws, designed to clamp two pieces of metal together solidly despite vibration.  In that case, the material (the metal pieces or a nut) is plenty strong and the important thing is to be able to exert maximal compression between the pieces.  For that purpose, it is advantageous to use narrow screw threads with a small helix angle https://www.afi.cc/blog/screw-thread-terminology.  Larger thread depth for a given helix angle results in weaker threads, but stronger grip.
Given a specific fitness function (i.e., what does "better" mean in a given context?", it is fairly straightforward to set up an optimization procedure that selects the best screw shape for a specific application.  For example, a genetic algorithm incorporating all the necessary factors and relationships can quickly find an optimal shape.  (Transparency note: this link is to something I wrote about 25 years ago.)


text:
Q: SQLite FTS4: A query containing a single unary not expression? The SQLite3 FTS4 documentation regarding the standard query unary - operator states:

An FTS query may not consist entirely of terms or term-prefix queries
  with unary "-" operators attached to them.

Is there any way around this?  Specifically, I want to retrieve all the rows in my table that do not contain a term or term-prefix.
sqlite> select * from search;
1|Clock
2|Un
sqlite> select id from search where text match 'Un';
2
sqlite> select id from search where text match 'clock -Un';
1
sqlite> select id from search where text match '-Un';
Error: malformed MATCH expression: [-Un]
sqlite> select id from search where text match '-Un*';
Error: malformed MATCH expression: [-Un*]

A: select id
from search
where docid not in (select docid
                    from search
                    where text match 'Un')


text:
Q: Why hasn't my CentOS partition resized? I am running CentOS 6.5 in Hyper-V. It originally started off with a 5GB virtaul hard disk (VHDX) but I later decided I wanted to increase the size. I changed it in Hyper-V settings to 20GB, then booted partition magic live CD and changed /dev/sda to 20GB. I then ran the following to increase the LVM:
lvextend -l +100%FREE /dev/mapper/vg_condor-lv_root

I though this was enough, but it still seems to be limited to the original ~4GB. Here's some details, but please ask for any specific stuff you need as I'm pretty new to this:
[root@condor leonard]# fdisk -l

Disk /dev/sda: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0006a679

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          64      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              64        2611    20458496   8e  Linux LVM

Disk /dev/mapper/vg_condor-lv_root: 20.4 GB, 20409483264 bytes
255 heads, 63 sectors/track, 2481 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg_condor-lv_swap: 536 MB, 536870912 bytes
255 heads, 63 sectors/track, 65 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

[root@condor leonard]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_condor-lv_root
                      3.9G  1.1G  2.6G  29% /
tmpfs                 495M     0  495M   0% /dev/shm
/dev/sda1             477M   82M  370M  19% /boot

[root@condor leonard]# lsblk
NAME                         MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0                           11:0    1 1024M  0 rom
sda                            8:0    0   20G  0 disk
├─sda1                         8:1    0  500M  0 part /boot
└─sda2                         8:2    0 19.5G  0 part
  ├─vg_condor-lv_root (dm-0) 253:0    0   19G  0 lvm  /
  └─vg_condor-lv_swap (dm-1) 253:1    0  512M  0 lvm  [SWAP]

Ultimately, how do I correctly increase the space available to the / folder?

A: You still need to resize the filesystem contained in the LV (assuming it's one of the ext filesystems):
resize2fs /dev/mapper/vg_condor-lv_root

If you want to resize a logical volume and its filesystem in a single operation, use fsadm:
fsadm resize /dev/mapper/vg_condor-lv_root

This supports the ext filesystems as well as ReiserFS and XFS.


text:
Q: Background pixel in fragment shader There is some method to access the background pixel in a fragment shader in order to change the alpha blending function?
I try to implement the fragment shader from page 5 of Weighted Blended Order-Independent Transparency but I don't know how to get Ci.

A: In standard OpenGL, you can't read the current value in the color buffer in your fragment shader. As far as I'm aware, the only place this functionality is available is as an extension in OpenGL ES (EXT_shader_framebuffer_fetch).
I didn't study the paper you linked, but there are two main options to blend your current rendering with previously rendered content:
Fixed function blending
If the blending functionality you need is covered by the blending functions/equations supported by OpenGL, this is the easiest and likely most efficient option. You set up the blending with glBlendFunc() and glBlendEquation() (or there more flexible variations glBlendFuncSeparate() and glBlendEquationSeparate()), enable blending with glEnable(GL_BLEND), and you're ready to draw.
There are also extensions that enable more variations, like KHR_blend_equation_advanced. Of course, like with all extensions, you can't count on them being supported on all platforms.
Multiple Passes
If you really do need programmable control over the blending, you can always do that with more rendering passes.
Say you render two passes that need to be blended together, and want the result in framebuffer C. The conventional sequence would be:
set current framebuffer to C
render pass 1
set up and enable blending
render pass 2

Now if this is not enough, you can render pass 1 and pass 2 into separate framebuffers, and then combine them:
set current framebuffer to A
render pass 1
set current framebuffer to B
render pass 2
set current framebuffer to C
bind color buffers from framebuffer A and B as textures
draw screen size quad, and sample/combine A and B in fragment shader

A and B in this sequence are FBOs with texture attachments. So you end up with the result of each rendering pass in a texture. You can then bind both of the textures for a final pass, sample them both in your fragment shader, and combine the colors in a fully programmable fashion to produce the final output.


text:
Q: golang fifo buffered channel from my understanding: buffered channels in GO are not FIFO when the channel is full.
I need this behaviour in my application (FIFO behaviour).
How can I achieve that behaviour? Is there any open source for that?
Thanks in advance
EDIT:
some people disliked the question so let me be more clear:
I meant that when a buffered channel is full and multiple senders are blocked
while trying to add items to the channel the order in which they'll be released
is not FIFO. You can also read this discussion: https://github.com/golang/go/issues/11506
So yeah, I was looking for a third party library that implements that behaviour.
Sorry for not being clear.

A: You could make use of Linked List.
The container/list package (https://golang.org/pkg/container/)  implements a doubly linked list which can be used as a queue. Perhaps, it also implements Heap which allows you to create queues with priority. Anyhow, the simplest way is Linked List IHMO:
queue := list.New()

queue.PushBack("Hello ") // Enqueue
queue.PushBack("world!")

for queue.Len() > 0 {
    e := queue.Front() // First element
    fmt.Print(e.Value)

    queue.Remove(e) // Dequeue
}

A: Buffered channels in Go are always FIFO. The specification clearly says:

Channels act as first-in-first-out queues.

If the values coming out of the channel are not FIFO, then this is a bug in the channel implementation.
The following code should always print 1, 2, 3, 4 in this correct order:
package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 3)
    ch <- 1
    ch <- 2
    ch <- 3

    go func() {
        ch <- 4
    }()

    time.Sleep(time.Second)

    for i := 0; i < 4; i++ {
        fmt.Println(<-ch)
    }
}

Playground link
Please note, that there is no guaruantee which value will be send first when there are multiple concurrent senders. If there are multiple waiting senders and someone removes one element from the channel buffer (or in the case of an unbuffered channel, tries to receive from the channel) the runtime will randomly choose one of the sending goroutines.
Example:
package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 2)
    ch <- 1

    go func() {
        ch <- 2
    }()

    go func() {
        ch <- 3
    }()

    time.Sleep(time.Second)

    for i := 0; i < 3; i++ {
        fmt.Println(<-ch)
    }
}

Playground link
If you run this code multiple times, you can see that the output will sometimes either be 1, 2, 3 or 1, 3, 2. (This doesn't work on the playground, as the output is cached)


text:
Q: While loop for alphabet I am trying to code the following example.
Input  ABCDEFGHIJKLMNOPQRSTUVWXYZ

Output  ZYXWVUTSRQPONMLKJIHGFEDCBA

If user types in A it will output Z.  It has to go past 25 characters to reach Z. So I am guessing a while loop will be needed, then if B it has to go through 23 times, so – 2 and so on until it reaches M as it will skip though 1 to reach N, then start again at 25.
Any suggestion on how to approach this?

A: Capital ASCII characters range according to the ASCII-table from 65 (0x41, 'A') to 90 (0x5A, 'Z').
This is the algorithm:
// inputChar is a char holding your character
char inputChar = getCharFromUser();
int inputVal = inputChar - 65; // e.g. 0 for 'A', 1 for 'B'
char outputChar = 90 - inputVal; // e.g. 90 - 1 = 89 = 'Y'
outputCharToUser(outputChar);

And this is how you might implement it in C#:
while (true)
{
    var key = Console.ReadKey(intercept: true);
    var inputChar = char.ToUpper(key.KeyChar);
    var outputChar = (char)('Z' - inputChar + 'A');
    Console.Write("{0}={1} ", inputChar, outputChar);
}

A: You could use two dictionaries which enable to lookup the char from index and vice-versa:
var indexLookup = "abcdefghijklmnopqrstuvwxyz"
    .Select((chr, index) => new { chr, index })
    .ToDictionary(x => x.chr, x => x.index);
var charLookup = "abcdefghijklmnopqrstuvwxyz"
    .Select((chr, index) => new { chr, index })
    .ToDictionary(x => x.index, x => x.chr);

Now it's simple, the essential part is charLookup[25 - indexOfChar]:
string userInput = "B";

bool isUpper = char.IsUpper(userInput[0]);
char inputChar = Char.ToLowerInvariant(userInput[0]);
if(indexLookup.ContainsKey(inputChar))
{
    int indexOfChar = indexLookup[inputChar];
    char oppositeChar = charLookup[25 - indexOfChar];
    string result = isUpper ? Char.ToUpperInvariant(oppositeChar).ToString() : oppositeChar.ToString();
    Console.Write(result); // Y
}

Actually you don't need two dictionaries but only one since the string can already be used to lookup a char by index. Here is a class which provides the logic:
public class CharSwap
{
    private string alphabet;
    private Dictionary<char, int> indexLookup;

    public CharSwap() : this("abcdefghijklmnopqrstuvwxyz") { }
    public CharSwap(string alphabet)
    {
        if(alphabet == null) throw new ArgumentNullException("alphabet");
        this.alphabet = alphabet;
        indexLookup = alphabet.Select((chr, index) => new { chr, index }).ToDictionary(x => x.chr, x => x.index);
    }

    public char? OppositeChar(char input)
    {
        char lowerChar = Char.ToLowerInvariant(input);
        if (!indexLookup.ContainsKey(lowerChar))
            return null;
        int indexOfChar = indexLookup[lowerChar];
        int indexOpposite = alphabet.Length - 1 - indexOfChar;
        return Char.IsUpper(input)
            ? Char.ToUpperInvariant(alphabet[indexOpposite])
            : alphabet[indexOpposite];
    }
}

Test:
CharSwap cw = new CharSwap();
char? oppositeChar = cw.OppositeChar('B');
Console.Write(oppositeChar);

A: How about something like this?
 char[] alphabet = {'A','B', 'C'} // and so on
 char[] mapsTo = {'Z', 'Y', 'X'} // and so on, excluded for brevity
 public function string changeLetter(char input)
 {
   int i = 0;
   foreach (char c in alphabet) {
      if (c == input) {
       return mapsTo[i];
      }
     i++;
   }
   return '';
 }

Converted to c#:
char[] alphabet = {'A','B', 'C'}; // and so on
char[] mapsTo = {'Z', 'Y', 'X'}; // and so on, excluded for brevity
public string changeLetter(char input)
{
   int i = 0;
   foreach (char c in alphabet) {
      if (c == input) {
       return mapsTo[i].ToString();
      }
     i++;
   }
   return default(char).ToString();
}

You would call this function like this (for instance):
public static void RunProgram()
{
 Console.WriteLine("Please type in character");
 input = Console.ReadKey().KeyChar;
 Console.WriteLine("You typed in " + input + ". This results in: " + ChangeInput(input));
}

... where "ChangeInput" is the function defined earlier.

A: char input = 'B';
string Range = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char result = Range[Range.Length - 1 - Range.IndexOf(input)]; //Y

or maybe another approach
char input = 'B';
string Range = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char result = Range.Reverse().ElementAt(Range.IndexOf(input)); //Y

A: The easy way to solve this is to use a Dictionary<char, char>:
public class Atbash {

    static string source = "abcdefghijklmnopqrstuvwxyz";
    static List<char> keys = source.ToList();
    static List<char> values = source.Reverse().ToList();
    static Dictionary<char, char> Converter = keys.ToDictionary(x => x, x => values[keys.IndexOf(x)]);

    public static char Convert(char input)
    {
        char output;
        bool isUpper = char.IsUpper(input);
        input = char.ToLowerInvariant(input);
        if(Converter.ContainsKey(input)) {
            output =  Converter[input];
            return (isUpper) ? char.ToUpperInvariant(output) : output;
        }
        throw new ArgumentOutOfRangeException("Input char is unknown");
        // of course, it can return default(char) instead of throwing an exception.
    }

}

Why Atbash? read about it here.


text:
Q: JSON object parsing without keys and concatenate inner json values I have a column in DB which stored data in following json format like below:
{"ad002":"5601087282462117","be003":"{"1":"ABC","2":"DEF","3":"DEF"}","ze024":"18"}
I want to iterate the data without keys as there are thousand of keys in data and if some element found like be003 where it has further key values then all the values should be concatenate and return that value.
I tried below solution
JSONObject outerObject = new JSONObject(jsonInput); String ad002Value = outerObject.optString("ad002"); JSONObject be003Object = new JSONObject(outerObject.optString("be003"));
but here I need to depend in keys which is not required as there are thousand of keys. I need to further set values to some object.

A: Use JSON library such as Josson to do the transformation.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
    "{" +
    "    \"ad002\": \"5601087282462117\"," +
    "    \"be003\": \"{\\\"1\\\":\\\"ABC\\\",\\\"2\\\":\\\"DEF\\\",\\\"3\\\":\\\"DEF\\\"}\"," +
    "    \"ze024\": \"18\"" +
    "}");

Transformation
JsonNode node = josson.getNode(
    "entries()" +        // Step 1
    ".field(value" +
    "       .if(startsWith('{')," + // Assume it is an object
    "           json().entries().value.@join()," +
    "           ?)" +
    "       )" +         // Step 2
    ".map(key::value)" + // Step 3
    ".mergeObjects()");  // Final step
System.out.println(node.toPrettyString());

Output
{
  "ad002" : "5601087282462117",
  "be003" : "ABCDEFDEF",
  "ze024" : "18"
}

Path Trace
You can use function getPathTrace() to see the output of each step.
PathTrace trace = josson.getPathTrace(...)

Step 1 output
[ {
  "key" : "ad002",
  "value" : "5601087282462117"
}, {
  "key" : "be003",
  "value" : "{\"1\":\"ABC\",\"2\":\"DEF\",\"3\":\"DEF\"}"
}, {
  "key" : "ze024",
  "value" : "18"
} ]

Step 2 output
[ {
  "key" : "ad002",
  "value" : "5601087282462117"
}, {
  "key" : "be003",
  "value" : "ABCDEFDEF"
}, {
  "key" : "ze024",
  "value" : "18"
} ]

Step 3 output
[ {
  "ad002" : "5601087282462117"
}, {
  "be003" : "ABCDEFDEF"
}, {
  "ze024" : "18"
} ]


text:
Q: DataGridDragDropTarget: Change Icon depending on the drop target I'm currently writing a tool to assign entities from one DataGrid to entities in another DataGrid via drag-and-drop.
With some fiddling, I got everything to run smoothly, with one minor annoyance: Some entities cannot be assigned to some other entities, which isn't reflected by the UI (yet).
So, the behavior I want to achieve is the following: When the user drags the assignee over the other entity, the icon should change to the "you can't drop that here" icon if the entities aren't compatible.
This is my code (attached to the DataGridDragDropTarget.DragOver event of the target DataGrid):
private void DragDropTarget_OnDragOver(object sender, Microsoft.Windows.DragEventArgs e)
{
    var sw = sender as DataGridDragDropTarget;

    if (sw == null)
    {
        return;
    }

    if(GetAssignmentCondition(e))
    {
        // TODO: Show link-icon
    }
    else
    {
        // TODO: Show drop-disabled-icon
    }
}

What I've tried so far:
I've set e.Effects, the DragDropTarget's AllowedSourceEffects property and the underlying ItemDragEventArgs's AllowedEffects and Effects to DragDropEffects.None, to no avail. Googling also didn't yield any meaningful results, and I'm out of ideas.

A: This helps in situations with TextBox and FlowDocument controls, so it should work with DataGrid.
The key here is to set the event to Handled to keep the control from doing its shenanigans.
Something like so:
Code behind (just for demonstration - preferably use a more MVVM friendly solution):
private void DragDropTarget_DragEnter(object sender, Microsoft.Windows.DragEventArgs e)
{
    var sw = sender as DataGridDragDropTarget;

    if (sw == null)
    {
        return;
    }

    if(GetAssignmentCondition(e))
    {
        // TODO: Show link-icon
        e.Effects = DragDropEffects.Link;
    }
    else
    {
        // TODO: Show drop-disabled-icon
        e.Effects = DragDropEffects.None;
    }

    // Add this
    e.Handled = true;
}

A: Changing the Effects property of DragEventArgs  in the OnDragOver event handler without setting the Handled property to 'true' does not works because as you can see here in the DragDropTarget.cs source code. If OnDragOver is not handled (args.Handled=true;) in any of event handlers, the args.Effects will revert back to args.AllowedEffects.
    protected virtual void OnDragOver(SW.DragEventArgs args)
    {
        foreach (SW.DragEventHandler handler in _dragOver)
        {
            handler(this, args);
            if (args.Handled)
            {
                return;
            }
        }

        OnDragEvent(args);
    }

    protected virtual void OnDragEvent(SW.DragEventArgs args)
    {
        SW.DragDropEffects effects = args.AllowedEffects;

        ///removed for clarity

        if (!args.Handled && effects != args.AllowedEffects)
        {
            args.Effects = effects;  // revert back to args.AllowedEffects
            args.Handled = true;
        }
    }


text:
Q: Correcting cumulatives in Pandas I have a DataFrame that has the following columns:

DeviceId | Timestamp | Total_Data
   001          08/12/2014     500
   001          08/13/2014     600
   001          08/14/2014     750
   001          08/15/2014     150 (device restarted here) (correct value:750+150)
   001          08/16/2014     300 (correct value: 750+150+300)
   002          10/01/2014     98
  ...
  ..

For a bunch of different devices, I have the data they consumed on different occasions (noted by the timestamps).
The Total_Data column is cumulative in nature and therefore, for a given device, calculates the total data consumed over time. For example, if device A used 3KB on 12 August 2012 and 5KB on 14 August 2012, the DataFrame would have two entries with the second entry having its Total_Data value as 8KB.
The glitch however, is that the cumulative values reset to 0 (and started counting again) when the devices were rebooted. And therefore, need to be corrected. What would be the best way to alter my current DataFrame in Pandas to solve this problem
Until now, I've thought of iterating through the DataFrame on a row by row basis but it just seems too complex.

A: *

*First divide your Dataframe according to your reset

*Make cumulative sum in each part

*Add extra value from previous part

Code is given below:
grouped = df.groupby((df.TotalData.diff() <= 0).cumsum())
parts = [g.reset_index(drop=True) for k, g in grouped]

for i in range(1, len(parts)):
    parts[i]['TotalData']=parts[i]['TotalData'].cumsum().add(parts[i-1]['TotalData'].max())

DF = pd.concat(parts)

print DF

Result:
           Date  TotalData
   0 2014-08-12        500
   1 2014-08-13        600
   2 2014-08-14        750
   0 2014-08-15        900
   1 2014-08-16       1200

A: Here's the code sample solving your issue.
I assumed that if there was a reboot, then the TotalData value is less than previous value.
df = pd.DataFrame({'Date': pd.Series([datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16)]),
                   'TotalData': pd.Series([500, 600, 750, 150, 300])
                   })
df['PrevTotalData'] = df['TotalData'].shift(1)
df.loc[0, 'PrevTotalData'] = 0

# Assuming here that the amount of data day after reboot is always less then
# the total amount of data in previous day
rebooted = df['PrevTotalData'] > df['TotalData']
df['DataBeforeLastReboot'] = 0
df.ix[rebooted, 'DataBeforeLastReboot'] = df['PrevTotalData']
df['DataBeforeLastReboot'] = df['DataBeforeLastReboot'].cumsum()
df['TotalDataFixed'] = df['TotalData'] + df['DataBeforeLastReboot']

print(df)

The data frame before:
        Date  TotalData
0 2014-08-12        500
1 2014-08-13        600
2 2014-08-14        750
3 2014-08-15        150
4 2014-08-16        300

And after:
        Date  TotalData  PrevTotalData  DataBeforeLastReboot  TotalDataFixed
0 2014-08-12        500              0                     0             500
1 2014-08-13        600            500                     0             600
2 2014-08-14        750            600                     0             750
3 2014-08-15        150            750                   750             900
4 2014-08-16        300            150                   750            1050

In case the the data frame consists of different machines, the solution is a bit more complex.
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'Machine': pd.Series([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]),
                   'Date': pd.Series([datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16),
                                      datetime(2014, 8, 12),
                                      datetime(2014, 8, 13),
                                      datetime(2014, 8, 14),
                                      datetime(2014, 8, 15),
                                      datetime(2014, 8, 16)]),
                   'TotalData': pd.Series([500, 600, 750, 150, 300,
                                           100, 200, 300, 100, 200])
                   })
df = df.reset_index(drop=True)
df = df.set_index(['Machine', 'Date'])
grouped_by_machine = df.groupby(level=[0])
df['PrevTotalData'] = grouped_by_machine['TotalData'].shift(1)
df['PrevTotalData'] = df['PrevTotalData'].fillna(value=0)

# Assuming here that the amount of data day after reboot is always less then
# the total amount of data in previous day
rebooted = df['PrevTotalData'] > df['TotalData']
df['DataBeforeLastReboot'] = 0
df.ix[rebooted, 'DataBeforeLastReboot'] = df['PrevTotalData']
df['DataBeforeLastReboot'] = grouped_by_machine['DataBeforeLastReboot'].cumsum()
df['TotalDataFixed'] = df['TotalData'] + df['DataBeforeLastReboot']
print(df)

Data frame before:
                    TotalData
Machine Date
0       2014-08-12        500
        2014-08-13        600
        2014-08-14        750
        2014-08-15        150
        2014-08-16        300
1       2014-08-12        100
        2014-08-13        200
        2014-08-14        300
        2014-08-15        100
        2014-08-16        200

and after:
                    TotalData  PrevTotalData  DataBeforeLastReboot  TotalDataFixed
Machine Date
0       2014-08-12        500              0                     0             500
        2014-08-13        600            500                     0             600
        2014-08-14        750            600                     0             750
        2014-08-15        150            750                   750             900
        2014-08-16        300            150                   750            1050
1       2014-08-12        100              0                     0             100
        2014-08-13        200            100                     0             200
        2014-08-14        300            200                     0             300
        2014-08-15        100            300                   300             400
        2014-08-16        200            100                   300             500


text:
Q: Alert box when pressing button and there's user input that's not saved I have multiple pages with some input fields. On this page, I have a previous and next button as well as a save (submit) button. When I press the save button, it will save the user input in the database.
However when I press next or previous, I'll get an alert with:'The user input is not saved yet, untill you click the save button.' Pressing OK will go to the next page and cancel will make it stay on this page. This is what I want, however the alert will always pop up whenever I press next or previous even when there's no user input or in case of editting the user input has not changed. So I dont want the alert to popup whenever nothing has changed or nothing is filled in.
This is my javascript function:
function something(evt) {
        if ( ! confirm("The user input is not saved yet, untill you click the save button.") ) evt.preventDefault();
}

buttons:
<a onclick="something(event)" href=""> </a>

Also on some pages, there are select boxes as well. These have standard values and the select boxes cant be empty so I can't check on the select boxes. The check should only be on textareas and textfield.
I am not able to figure out how to accomplish this.
How would I get to check if the user input(textarea, textfield) has changed or is not empty in my case?

A: In the something() function do a check if the input field is empty first:
function something(evt) {
  var input= document.getElementsByTagName('input')[0];
  if(input && input.value !=""){
    if ( ! confirm("The user input is not saved yet, untill you click the save button.") ) evt.preventDefault();
  }
}

A: you can save your input change in cookies and check them on clicking link whether it is edited or not. Note- include jquery library
$('input').change(function(){
 document.cookie="input="+$(this).val();

});
$("a").click(function(e){
    var inputChange= getCookie('input');

    if(inputChange!=$('input').val()){
         var ask = confirm('The user input is not saved yet, untill you click the save button.');
         if(!ask){
             e.preventDefault();
         }
    }

});
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}


text:
Q: How to display images in simple listview listadapter in android I want to display image in simple listview,
   we have arraylist HashMap which have values like city, description, etc.
& also the base64 image string which we have to convert to image and set to the each row of of the ListView and List row xml is listview_row.xml
This is my code for displaying the text fields in listview, which is done:
ArrayList<HashMap<String, String>> arllist = new ArrayList<HashMap<String, String>>();
Intent intent = getIntent();
arllist = (ArrayList<HashMap<String, String>>) intent.getSerializableExtra("map");

int length = arllist.size();
for(int i=0; i<length; i++)
{
    try{
        String stringToConvert = arllist.get(i).get("image");
        byte[] decodedString = Base64.decode(stringToConvert, Base64.NO_PADDING);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        ImageView image = (ImageView)this.findViewById(R.id.img);
        image.setImageBitmap(decodedByte);
    }
    catch (Exception e) {
        // TODO: handle exception
        Toast.makeText(productlist.this, e.toString(), Toast.LENGTH_LONG).show();
    }
}

SimpleAdapter listadapter = new SimpleAdapter(this, arllist, R.layout.list_item,
      new String[] {"city", "category", "description", "mobile", "landmark"},
      new int[] {R.id.city, R.id.category, R.id.desc, R.id.mobile, R.id.landmark});

ListView list=(ListView)findViewById(R.id.list);
list.setAdapter(listadapter);

My question is how to convert and bind image to adapter to display it on listview's each row
and also get's error on converting image --- bad base64

A: I think This Tutorial is exactly what you're looking for.
Edit:
Try this:
Android Encode-Decode

A: For converting Base64 string, try this-
Assuming your image data is a String called myImageData:
 byte[] imageAsBytes = Base64.decode(myImageData.getBytes());
    ImageView image = (ImageView)this.findViewById(R.id.ImageView);
    image.setImageBitmap(
            BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
    );


text:
Q: Does a C++ style cast operator change the pointer it casts? I am quite happy using the C++ style casting operators within my code but I cannot say that I truly understand what goes on behind the scenes. I am basically wondering what actually is happening to the pointer during the following short process:
class A {};
class B : public A {};
class C : public B {};

A* pC = new C();

B* b = static_cast<B*>(pC);    // Is the value of pC changed by the cast?
C* c = static_cast<B*>(pC);    // Is the value of pC changed by the cast?
B* b2 = static_cast<B*>(c)     // Is the value of c now equal to the value of b2?

I realise that the object pointed to by pC is always of type C but after the first cast is made, I assume that the address stored in b is no longer equal to that of pC. But if the cast changes the value of pC my assumption is wrong. In a nutshell, can the cast operators actually change the address of the pointer they cast? This may seem a pretty facile question, but in my mind the picture is just not clear of how objects with an inheritance hierarchy are stored within memory and how the pointers get manipulated via the casts.
In my head the value of pC remains unchanged no matter how many casts are performed on it but is this thinking correct?

A: In no case does a cast change its operand. All it does is to change how the compiler sees the operand.
The value of pC will not be changed; the result of the cast might be an identical value but different type (e.g. in the case of a const_cast or a reinterpret_cast), or it might actually be both a different type and a different value (e.g. in the case of a static_cast in a case of multiple inheritance, see Andrew's answer).
To really understand in which cases a different result value would happen, you would have to read up on C++ ABIs, i.e. how objects are stored in memory exactly.

A: In your case, it doesn't change the pointer.
But for multiple inheritance, it will have to change the pointer.
You can write a sample program to confirm that.

A: The casted pointer can point to another location. In case of multiple inheritance for example. Good read
The original pointer will be preserved

A: Short answer:
With casts you just tell the compiler how to interpret an object, i.e. of what type I is supposed to think the object is.
A cast does not change the value of an object.


text:
Q: Why does the HTML5 header element require a h tag? According to HTML5Doctor.com and other HTML5 introductory sites, the header element should contain a h1-h6 tag plus other navigational or introductory content. However, the traditional 'header' on most websites consists of just a logo and some navigational elements.
A lot of major sites including Facebook and Twitter use a h1 tag for their logo, which seems illogical to me, since the logo is not the most important or most informative element on the page.
A h1 tag appears in the content section of 95% of websites, not the header section. So why are we instructed to include a h tag in the header? If we must, why don't Facebook and Twitter use a h6 tag instead?

A: You should take a look at the outline algorithm for HTML5.
You probably want your site title/logo to be a h1.
Imagine a small webpage, consisting of a page header (logo, site name, …), a site navigation and a blog entry (main content of this page):

 ACME Inc.

…

Lorem Ipsum

…

Here the only heading is the h1 inside the div. Semantically this would mean, that all content of this page is in the scope of this heading. See the outline of this page:

*

*Lorem Ipsum

But this would not be true (in the semantic way): hierarchically, the page header "ACME Inc." is not "part" of the blog entry. Same goes for the navigation; it's a site navigation, not navigation for "Lorem Ipsum".
So the site header and the site navigation need a heading. Let's try to give them a h1, too:

ACME Inc.

Site navigation

…

Lorem Ipsum

…

Way better! The page outline now looks like:

*

*ACME Inc.

*Site navigation

*Lorem Ipsum

But it's still not perfect: they are all on the same level, but "ACME Inc." is what makes all the webpages to form a website, it's the whole point why there are webpages at all. The navigation and the blog entry are parts of "ACME Inc.", which represents the company and the website itself.
So we should go and change the navigation and blog entry headings from h1 to h2:

ACME Inc.

Site navigation

…

Lorem Ipsum</h2

…

Now we have this outline:

*

*ACME Inc.

*

*Site navigation

*Lorem Ipsum

And this is exactly what the content of the example webpage means.
(By the way, this would work in HTML 4.01, too.)
As explained in the link, HTML5 gives us sectioning elements, which play an important role for the outline (instead of div, which doesn't influence the outline) We should use them:

ACME Inc.

Site navigation

…

Lorem Ipsum</h2

…

The outline stays the same. We could even change the h2 (inside of the nav and the article) back to h1, the outline would stay the same, too.
If you don't want an "explicit" heading for the navigation, you are free to remove it: the outline stays the same (now with an implicit/"unnamed" heading for the nav). Each section has a heading, whether you add it or not.
You could even change the h1 inside the header to h6 and it wouldn't change the outline. You can think of this heading as the "heading of the body".
Additional notes

*

*The header element is not needed in these examples. I only added it because you mentioned it in your question.

*If you want to use a logo instead of a textual name ("ACME Inc."), you should still use a h1 and add the img as a child. The value of the alt attribute should give the name then.

*The top level heading doesn't have to be "the most important or most informative element on the page". This is not what headings are used for. They give the structure/outline and "label" their scoped content. In this example, you could assume that the article (with its heading inside) is the most important content.

*If you use the sectioning elements everytime whend needed, you don't need h2…h6 anymore (but you are free to use them, for clarity or backwards compatibility).

*You can play around and test some markup constructs with the HTML Outliner: http://gsnedders.html5.org/outliner/ (it had some unfixed bugs) the HTML5 Outliner.

A: Don't get confused by "should" contain and "must" contain. You aren't required to have anything inside the header you don't want but the 'semantic' purpose of the header is that is where you should look for and place such things, at the head of a document. Just as you would look for the title or introduction or table of contents at the top of a printed page.

A: This is a flexible but important concept for SEO and basic HTML programming. While there is some room for wiggling through this standard, it will not make or break your site.
For example, you mention Facebook has the logo instead of an H1 in their header. This is half true as they have their header within a pair of h1 tags, making it function essentially the same as any other H1 text might:

Facebook logo

Again, not exactly ideal, but they are Facebook and can do what they want. You on the other hand might want to be more mindful of these best practices when building out a site.


text: Q: jquery mobile ajax does not apply css Im trying to create a scroll down ajax everything works fine but the css doesn't apply to the new content. Here what I have. Is their anyway to fix it. What makes it for jquery mobile ajax to lose its css.


text:
Q: Linear independence, if $ |a_{kk}| > \sum_{i=1, i \neq k}^{s} |a_{ik}| $ I found task written below, but I cannot prove it.

Given is system of $s$ vectors ($a_i = (a_{i1}, a_{i2}, \dots a_{in})$ for $i = 1, \dots, s$), where $s \leq n$. Prove that, if for
  all $1 \leq k \leq s$  is satisfied inequality: $$ |a_{kk}| > \sum_{i=1, i \neq k}^{s} |a_{ik}| $$
  Then system is linear independent.

So I made (square) matrix:
$$
\left\|\begin{split}
a_{11}~&~a_{12}~&~\cdots~&~a_{1s}\\
a_{21}~&~a_{22}~&~\cdots~&~a_{2s}\\
\cdots~&~\cdots~&~\cdots~&~\cdots\\
a_{s1}~&~a_{s2}~&~\cdots~&~a_{ss}\\
\end{split}  \right\|
$$
And I'm trying to prove that determinant is not equal to zero. (I don't see easiest way, to prove it.) But without positive effect. I tried to use GM inequality.
$$
|a_{kk}| > (s-1) \cdot \sum_{i=1, i \neq k}^{s} \frac{|a_{ik}|}{s-1}>(s-1)\cdot \sqrt[s-1]{\prod_{i=1, i\neq k}^{s} |a_{ik}}
$$
Or induction proof. But I don't know how I can end the proof. Could you give me some hints?

A: It is easier to solve the linear system. Let $(x_1,..,x_n)$ be a non zero vector in the kernel, and conisder an index $k$ such that $\vert x_k\vert$ is maximal.
As $\sum _{j=1}^n a_{jk}x_j=0$, we have $a_{kk} x_k=-\sum _{j\not =j}a_{jk}x_j$.
Therefore $\vert a_{kk}\vert \vert x_k\vert \leq \sum _{j\not =k}\vert a_{jk}\vert \vert x_j\vert \leq (\sum _{j\not =k}\vert a_{jk}\vert ) \vert x_k\vert$. Contradiction.


text:
Q: List in List (Usage of Range with for) I am new to programming and trying to learn from application. I have a function in python:
def eps(u):
    return as_vector([u[i].dx(i) for i in range(3)] + [u[i].dx(j) + u[j].dx(i) for i, j in [(0, 1), (0, 2), (1, 2)]])

I understand that in the above function, the statement i in range(3) is going to run a loop for u[0].dx(0)....u[2].dx(2) but I don't understand the for i, j in [(0, 1), (0, 2), (1, 2)]]) part. How is this entire statement going to execute? Can someone pls. explain.
Similarly I have:
def tangent(t):
  return as_matrix([[t[i*6 + j] for j in range(6)] for i in range(6)])

I believe the expression t[i*6 + j] will run 6 times for i = 0:5 and for each value of 'i', we will have 'j = 0:5'. Hence, I will get a 6x6 matrix. Is that correct?

A: A trivial way to determine what a particular piece of code does, is usually to run it and print the values used in that code:
for i, j in [(0, 1), (0, 2), (1, 2)]:
    print (i, j)

This prints
0, 1
0, 2
1, 2

In order words, this creates a list of tuples and the for-loop iterates over each tuple by unpacking each element of the tuple into the variables i and j, which you can use to do what ever you want

Also you are correct in assuming that you get a 6x6 array from the expression:
[[t[i*6 + j] for j in range(6)] for i in range(6)]
Again, you could just print the resulting array to confirm this


text:
Q: Modelsim is not working after ubuntu 11.10 upgrade? I have the error when I tried to run the modelsim 6.6d and display this below and it was fine in previously 11.04 version

Error: cannot find
  /home/mark/altera/11.0/modelsim_ase/bin/../linux_rh60/vlog The vlog
  should be in directory of /home/mark/altera/11.0/modelsim_ase/bin/vlog

But, I don't understand why is looking for linux_rh60/vlog?
Has anyone seen this error before?

A: To  fix this, you have to edit the vsim file with
gksu gedit vsim

in the bin directory. The thing is that if the linux version is 3.x.x.x there a condition that searches in an unexistent directory, so edit the line (204 aprox.)
  *)                vco="linux_rh60" ;;

to:
***)                vco="linux" ;;**

also, you have to change the line 13 (first non-comment line)
  mode=${MTI_VCO_MODE:-""}

to
  **mode=${MTI_VCO_MODE:-"32"}**


text:
Q: Changing foreground color binding of cells based on condition WPF Im trying to change the default color of a cell to red based on if the value is over a set limit. Currently, what is happening is that I have a grid with a list of oils with a checkbox. When a checkbox for any particular oil is checked, that oil is added to another grid where I can manipulate its amount. For example, if I check 1 oil, its "UsagePercentage" becomes 100. If I check another, the percentages are updated to 50/50. From there, if I click a button to increment its value by 1, it will change to 66.6/33.3 and so on.
What Im trying to implement based on my code is that if the oil's UsagePercentage is more than the UsageLimit, change the foreground text to red, otherwise keep it LightGray. But when I run the program, the UsagePercentage text is black. I dont't understand why binding UsagePercentage works, but ForegroundColor doesn't.
Oil.cs
public float UsagePercentage
    {
        get { return mUsagePercentage; }
        set
        {
            mUsagePercentage = value;
            NotifyPropertyChanged("UsagePercentage");
        }
    }

OilList.cs
public void UpdateFormulaWeight()
    {
        float ftw = mOils.Sum(oil => oil.TotalWeight);
        mFormulaTotalWeight = ftw;

        NotifyPropertyChanged("UsagePercentage");

        foreach (Oil oil in mOils)
        {
            oil.UsagePercentage = (oil.TotalWeight / mFormulaTotalWeight) * 100f;

            if (oil.UsagePercentage > oil.UsageLimit)
                ForegroundColor = "Red";
            else
                ForegroundColor = "LightGray";

            NotifyPropertyChanged("ForegroundColor");
            NotifyPropertyChanged("UsagePercentage");
        }
    }

private string ForegroundColor
    {
        get { return mForegroundColor; }
        set
        {
            mForegroundColor = value;
            NotifyPropertyChanged("ForegroundColor");
        }
    }

GrayToRed.cs
public class GrayToRed : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string input = value as string;

        switch(input)
        {
            case "Red":
                return Brushes.Red;
            case "LightGray":
                return Brushes.LightGray;
            default:
                return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

}
MainWindow.xaml
<Window.Resources>
    <converters:GrayToRed x:Key="GrayToRed" />
</Window.Resources>
...
<!-- USAGE PERCENTAGE -->
            <DataGridTextColumn Header="Formula %"  Binding="{Binding UsagePercentage,  StringFormat={}{0:F2}%}" IsReadOnly="True" Width="64">
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Background" Value="#1e1e1e"/>
                        <Setter Property="Foreground" Value="{Binding ForegroundColor, Converter={StaticResource GrayToRed}}"/>
                    </Style>
                </DataGridTextColumn.CellStyle>

                <DataGridTextColumn.ElementStyle>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="TextBlock.VerticalAlignment" Value="Center" />
                        <Setter Property="TextBlock.TextAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>


text:
Q: How to make version autoincrement in the latest .NET Core tooling? I am using the latest (as of today) .NET Core tooling. There, you specify version in an <Version> MSBuild property. However, unlike [assembly:AssemblyVersion], this does not appear to support wildcards. How do I make version increment automatically in the same way?
Explaining why this is a bad idea, and what should be done instead would also be a good answer.

A: The Version property in MSBuild does not support asterisks (wildcard) format as project.json did.
However, with MSBuild you can compute a version in other ways. There is no one right way to do it, but here is one approach. We use "VersionPrefix" instead. Microsoft.NET.Sdk will also automatically combine VersionPrefix and VersionSuffix to form the final value of "Version".
In file:
<PropertyGroup>
  <VersionPrefix>2.0.0</VersionPrefix>
</PropertyGroup>

On build server:
msbuild.exe /t:Pack /p:VersionSuffix=build00123

// or, the dotnet.exe equivalent
dotnet pack --version-suffix build00123

Result:
AssemblyVersion = 2.0.0.0
Package version = 2.0.0-build00123

Our build server generates the build number on each run.
If you want to use the old-school AssemblyVersion asterisk form, you can explicitly set the <AssemblyVersion> property in MSBuild. If not, this defaults to the major.minor.patch value of <Version>.
More details:
There are half-a-dozen "version" settings in Microsoft.NET.Sdk. See What is the difference between various MSBuild version properties, such as Version, VersionPrefix, and VersionSuffix? for more details.


text:
Q: Django handling cookie gdpr Quick question for django devs in Europe, how do you handle the cookie law in Europe in your django app?
I have seen a lot of solutions for an example cookiebot.com but I'm not sure if I want to use it. Also any other solution alternatives is appreciated.
All the best


text:
Q: Cup products in CW complexes (Hatcher, Example 3E.6) Let $X$ be obtained from $S^2 \times S^2$ by attaching a $3$-cell to the second $S^2$ factor by a map $S^2 \to S^2$ of degree $2$. Then from cellular cohomology it follows that $H^*(X;\Bbb Z)$ consists of $\Bbb Z$'s in dimensions 0,2, and 4, and a $\Bbb Z_2$ in dimension 3. Hatcher then says cup products (in $H^*(X;\Bbb Z)$) of positive-dimensional classes are zero because the only nontrivial product is the square of the 2-dimensional class, but this is zero as one sees by restricting to the subcomplex $S^2 \times S^2$.
I see that the only nontrivial product is the square of the $2$-dimensional class, but I can't see why we can conclude that it is zero by restricting to $S^2 \times S^2$. I know that $S^2 \times S^2 $ has cohomology $\Bbb Z[x_1,x_2]/(x_1^2, x_2^2)$ with $|x_1|=2=|x_2|$, so a square of any 2-dimensional class in $H^*(S^2\times S^2;\Bbb Z)$ is zero. But how can we conclude that the square of the $2$-dimensional class of $H^*(X,\Bbb Z)$ is zero?

A: Firstly it is not true that every class in $H^2(S^2\times S^2)$ squares to zero. For instance, in your notation, the class $x_1+x_2$ satisfies
$$(x_1+x_2)^2=x_1^2+x_1x_2+x_2x_1+x_2^2=x_1x_2+(-1)^{2\cdot 2}x_1x_2=2x_1x_2$$
and this is nonzero in $H^4(S^2\times S^2)\cong\mathbb{Z}$. Thus we have to work a little bit to check the statement in any case.
To begin consider the long exact sequence
$$\dots\rightarrow H^*(X,S^2\times S^2)\rightarrow H^*X\xrightarrow{j^*} H^*(S^2\times S^2)\rightarrow \dots$$
where $j:S^2\times S^2\hookrightarrow X$ is the inclusion. We have
$$H^*(X,S^2\times S^2)\cong\widetilde H^*(X/S^2\times S^2)\cong \widetilde H^*S^3$$
so the long exact sequence breaks up into a piece
$$0\rightarrow H^2X\xrightarrow{j^*} H^2(S^2\times S^2)\xrightarrow{\Delta} H^3S^3\rightarrow H^3X\rightarrow 0$$
and an isomorphism
$$0\rightarrow H^4X\xrightarrow{j^*} H^4(S^2\times S^2)\rightarrow 0.$$
It follows that $j^*$ is injective in dimensions $2$ and $4$, so if $u\in H^2X$, then $u^2=0$ if and only if $j^*(u^2)=(j^*u)^2=0$.
Now, where we have to work is to check what $j^*$ does in degree $2$. We know that in forming $X$ we have attached the $3$-cell to $S^2\times S^2$ along the composite map
$$\varphi:S^2\xrightarrow{2}S^2\xrightarrow{in_2}S^2\times S^2$$
We also know that the generators $x_1,x_2\in H^2(S^2\times S^2)$ are given by cohomology cross products. In particular, if $s\in H^2S^2$ is a generator then we can write
$$x_i=pr_i^*s,\qquad i=1,2,$$
where $pr_i:S^2\times S^2\rightarrow S^2$ is the projection onto the i$^{th}$ factor.
Knowing this, we can use a suspension isomorphism to identify $H^3S^3\cong H^2S^2$, and, with a bit of agility, calculate the action of the boundary map $\Delta$ above as
$$\Delta(x_1)=0,\qquad \Delta(x_2)=2\cdot s$$
where $s\in H^2S^2\cong H^3S^3$ is (the suspension of) the generator introduced above.
The point is that we get from exactness that $H^2X\cong\mathbb{Z}$, generated by a class $u$ satisfying
$$j^*u=x_1.$$
Now it is clear that
$$j^*(u^2)=(j^*u)^2=x_1^2=0$$
and hence that $u^2=0$.


text:
Q: Alexa: Emit not working in chaining of function I am trying to ask a question to the user and using AMAZON.yesIntent and noIntent to capture the response. In case I get response, I am calling other function which should emit something back to user. But the emit is not being called. Code below:
'use strict';

var Alexa = require("alexa-sdk");
var https = require('https');
var alexa;

exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.registerHandlers(handlers);
  alexa.execute();
};

var handlers = {
  'LaunchRequest': function() {
    alexa.emit(':ask', 'my text');
  },
  'oneShotIntent': function() {
    var self = this;
    // removed the code for simplicity
    self.attributes['yes_no'] = true;
    alexa.emit(':ask', 'sample yes no question');
    })
  },
  'AMAZON.YesIntent': function () {
    if (this.attributes['yes_no']) {
      delete this.attributes['yes_no'];
      alexa.emit('oneShotSecond');
    }
  },

  'oneShotSecond': function() {
    delete this.attributes['yes_no']; // already deleted
    // removed code for simplicity
      var self = this;
    // removed code for simplicity
        console.log(info);
        if (info) {
          console.log('here in if condition');
          self.emit(':tell', 'sample text');
        } else {
          self.emit(':tell', 'sorry failed');
        }
      });
  }
};

The first emit is working. The console.log in other function are happening. But emit is failing.
No logs in cloudwatch also. It just ends after printing the console.log data points.
Any help?

A: I am not sure if I understand
alexa.emit('oneShotSecond');

However I would have done it like below
oneShotSecond(this);

And then
'oneShotSecond': function(self) { // use self.emit}


text:
Q: Showing a map is not bijective I'm trying to show that the middle third Cantor set expressed in base 3 mapped to the set of real numbers in the interval $[0,1]$ expressed in base 2 according to the rule:
$0.a_1a_2a_3...\rightarrow 0.b_1b_2b_3...$
where $b_i=\frac{a_i}{2}$ is not a bijection.
I know that the map is surjective and not injective because some binary decimal has 2 expansions. However, I don't know how to prove this.

A: Note that each $x \in C$ has a unique representation $x = 0.a_1a_2a_3...$ with $a_i \in \lbrace 0, 2 \rbrace$ wheras some $y \in I$ have two distinct representations $y = 0.b_1b_2b_3...$ with $b_i \in \lbrace 0, 1 \rbrace$ (see Bungo's comment). In other words you have a bijection $\varphi : \Pi_{i=1}^\infty \lbrace 0, 2 \rbrace \to C$ and a surjection $\psi : \Pi_{i=1}^\infty \lbrace 0, 1 \rbrace \to I$ which is not injective. Your map is the composition $\psi \circ b \circ \varphi^{-1}$, where $b :\Pi_{i=1}^\infty \lbrace 0, 2 \rbrace \to \Pi_{i=1}^\infty \lbrace 0, 1 \rbrace$ is the bijection given by $b((a_i)) = (a_i/2)$.


text:
Q: Cannot start child instances in Apache Karaf I may have a problem creating 'instances' in Apache Karaf 2.3.0.
karaf@root> admin:create FOO
...<some verbose lines on file copy activity>...
karaf@root> admin:list

This is what I got:
  SSH Port   RMI Ports         State       Pid  Name
[    8101] [1099/44444     ] [Started ] [ 5168] root
[    8107] [1105/44450     ] [Stopped ] [    0] FOO
karaf@root>

I tried admin:start FOO but nothing happens.
Karaf.log didn't indicate any errors.
Am I missing something? I was following 'Getting Started' guide on karaf.apache.org.
Could it be a bug?

A: You need to start the new instance
admin:start FOO
Cheers


text:
Q: Ansible GCP dynamic inventory: pick hostname from inventory field I'm using GCP Dynamic Inventory, using IP addresses as keys. This is my inventory config:
hostnames:
  - public_ip

This is good, but the inventory_hostname variable is then set to the IP address, and setting hostname from that results in a wrong configuration. I was trying to tell Ansible to use another inventory field as username, but I failed so far.
I added
hostname_variable = name

to ansible.cfg but it doesn't work. Is it possible to keep using the IP as main field for inventory, and use the VM name as as hostname?
The other option I found is to use
hostnames:
  - name

in inventory config, but then I need to assign a different field for the ssh connection (that would be the public IP)


text:
Q: Can a control blindly proxy another URL, including PostBack? It is possible to have a control that would proxy requests to another domain/Web site, including postback?
In this control, you would specify the URL you wanted to execute, and whenever the control executed, it would make a GET request to this other URL, and render the HTML return.  (This part is not hard.)
However, when the page is posting back, it would make a POST request, with all of its postback variables intact, to this other page.
I'm really looking for a blind proxy.  Some control that will take the incoming request and throw it another URL, and render the results. The other page would really have no idea it wasn't interacting with a human.
I want to think I could develop this, but I can't be the first person who wants to do it, so there has to be some reason why Google isn't revealing the solution to me.  I suspect I'm going to run into the same Big Problem that anyone else with this idea has run into.

A: I'm not exactly sure what the value of this is; which is probably why you haven't found a solution yet.
However, it seems to me that there are two possible solutions.

*

*When the page is rendered have the control modify the form action to point elsewhere; or,

*on post back, have the control execute a web request to the alternate URL with the post variables and decide what to do with the results at that time.

A: In this end, this never had much of a chance of working.  I experimented with it for a while, but Postback requires intimate knowledge of the control tree, and there's no way that you're going to be able to apply a postback from the calling page to the other page and have it overlay correctly because the control trees between the two pages are totally different.
Now, if you wanted to write the backend app as a more traditional Web app (even something not in ASP.Net), it might work.  During postback, you could iterate the Request.Form values and send them back, and just have your backend app prepared to accept those incoming values and deal with them, but this wouldn't be a traditional postback.


text:
Q: combining oracle sql AND OR queries in Codeigniter using oci8 database drivers I am using codeigniter OCI8 database drivers can anybody help me how to  use $this->db->group_start().
If this not work in oci8 then any alternate option
I am using ajax based datatables.
On page load datatables works but in case of search datatable return this error

Fatal error:  Call to undefined method CI_DB_oci8_driver::group_start()

here is my code
function _get_datatables_query(){
    $this->db->from($this->table);

    $i = 0;

    foreach($this->column_search as $item){
        if(strtoupper($_POST['search']['value'])) // if datatable send POST for search
        {
            if($i===0) // first loop
            {
                $this->db->group_start();
                $this->db->like($item, strtoupper($_POST['search']['value']));
            }
            else
            {
                $this->school_db->or_like($item, strtoupper($_POST['search']['value']));
            }
            $this->db->group_end();
          //  if(count($this->column_search) - 1 == $i) //last loop
             //   $this->db->group_end(); //close bracket
        }
        $i++;
    }

    if(isset($_POST['order'])) // here order processing
    {
        $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    }
    else if(isset($this->order))
    {
        $order = $this->order;
        $this->db->order_by(key($order), $order[key($order)]);
    }
}

A: i've no idea which error gets thrown - but your function won't work that way - try the following instead
function _get_datatables_query()
{
    $this->db->from($this->table);

    $this->db->group_start();
    foreach($this->column_search as $item)
    {
        if(strtoupper($_POST['search']['value'])) // if datatable send POST for search
        {
            $this->db->or_like($item, strtoupper($_POST['search']['value']));
        }
    }
    $this->db->group_end();

    if(isset($_POST['order'])) // here order processing
    {
        $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    }
    else if(isset($this->order))
    {
        $order = $this->order;
        $this->db->order_by(key($order), $order[key($order)]);
    }
}

A: I have Solved this problem with some custom coding.
I just put Like in Where clause
$this->db->where("(" .$item . " LIKE '%".strtoupper($_POST['search']['value']."%'"));
Here is solution that work for me
private function _get_datatables_query()
{

    $this->db->from($this->table);

    $i = 0;
    foreach ($this->column_search as $item)
    {
        if(strtoupper($_POST['search']['value'])) // if datatable send POST for search
        {
            if($i===0) // first loop
            {
                if(count($this->column_search) > 1)
                    $this->db->where("(" .$item . " LIKE '%".strtoupper($_POST['search']['value']."%'"));
                else
                    $this->db->where("(" .$item . " LIKE '%".strtoupper($_POST['search']['value']."%')"));
            }
            else
            {
                if(count($this->column_search) - 1 == $i)
                    $this->db->or_where($item . " LIKE '%".strtoupper($_POST['search']['value']."%')"));
                else
                    $this->db->or_where($item . " LIKE '%".strtoupper($_POST['search']['value']."%'"));
            }
        }
        $i++;
    }

    if(isset($_POST['order'])) // here order processing
    {
        $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
    }
    else if(isset($this->order))
    {
        $order = $this->order;

        $this->db->order_by(key($order), $order[key($order)]);
    }
}


text:
Q: How to calculate the height of buildings from satellite/aerial images using MATLAB I want to calculate the height of buildings from satellite/aerial images using MATLAB automatically with no or least possible human interaction.  I am not using LIDAR or any DEM information.  Can anyone help me out in this?
My project is simple but very difficult to be completed. There are some GIS tools available for determining height of buildings but they are proprietary software and not automatic. What I am trying to do is to read satellite images in MATLAB and calculate the heights of buildings present in the images. There is no compulsion of what type of images I should use i.e I can use aerial or satellite images, normal or stereo images or oblique images.
I hope this information is sufficient to answer my question, I would be really happy to provide further clarification if needed.
Thanks in advance.

A: I suggest you learn the differences between aerial and satellite images first. They are not the same! The image geometry is different and therefore you would have to have different processing. Stereo images are an advantage, yes, but quite expensive. Lidar is expensive too and you cannot cover a huge area.
What are your requirements; height accuracy, resolution, budget .. etc.

i.e I can use aerial or satellite images, normal or stereo images or oblique images.

Making the whole process without (much) human interaction is a challenge. You would have to start first by extracting buildings (maybe image segmentation). Then you need a solution on how to deal with shadows, vegetation etc.


text:
Q: Standard Objects Limits Is there a way to know programmatically what are SOQL limits on objects?
some way that given a standard object tells that to query this object you need to use filters on the fields [x,y,z,...]?
to avoid exceptions like this:

[MalformedQueryFault [ApiQueryFault [ApiFault
  exceptionCode='MALFORMED_QUERY' exceptionMessage='Implementation
  restriction: ContentDocumentLink requires a filter by a single Id,
  ContentDocumentId or LinkedEntityId using the equals operator']

I know these limits are stated in the documentation but I need a on-the-fly way
Thanks,

A: I'm going to go out on a limb here and say that, no, you can't use the currently available meta data to determine the special query requirements as outlined in SOQL Limits on Objects.
Take for example, ContentDocumentLink. The special SOQL requirement here is:

A SOQL query must filter on one of Id, ContentDocumentId, or LinkedEntityId.

There is currently no meta data in DescribeSObjectResult that can tell you that one of those fields must defined in the SOQL where clause.
You have queryable on DescribeSObjectResult and filterable on Field. However, there is currently no way to know which combination of fields are required.

With NewsFeed the requirement is:

No SOQL limit if logged-in user has "View All Data" permission. If not, specify a LIMIT clause of 1,000 records or fewer.

Again, there is no meta data available to indicate that a LIMIT clause is required or what the maximum value is based on the users permissions.