Q: unfortunately app has stopped error when Changing the graphical layout I'm new to android development. I created a simple app that adds two numbers Using eclipse. It worked fine. But when I run the app after changing the positions of buttons and textViews, using graphical layout without directly editing xml files, "unfortunately app has stopped" error shown in Emulator. This happens to me few times. Please can someone figure why is that?
logCat
06-10 16:51:36.690: E/Trace(1343): error opening trace file: No such file or directory (2)
06-10 16:51:36.886: D/AndroidRuntime(1343): Shutting down VM
06-10 16:51:36.886: W/dalvikvm(1343): threadid=1: thread exiting with uncaught exception (group=0xa624b288)
06-10 16:51:36.890: E/AndroidRuntime(1343): FATAL EXCEPTION: main
06-10 16:51:36.890: E/AndroidRuntime(1343): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a/com.example.a.MainActivity}: java.lang.ClassCastException: android.widget.RadioGroup cannot be cast to android.widget.Button
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.os.Looper.loop(Looper.java:137)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread.main(ActivityThread.java:4745)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at dalvik.system.NativeStart.main(Native Method)
06-10 16:51:36.890: E/AndroidRuntime(1343): Caused by: java.lang.ClassCastException: android.widget.RadioGroup cannot be cast to android.widget.Button
06-10 16:51:36.890: E/AndroidRuntime(1343):     at com.example.a.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:75)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.Activity.performStart(Activity.java:5018)
06-10 16:51:36.890: E/AndroidRuntime(1343):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
06-10 16:51:36.890: E/AndroidRuntime(1343):     ... 11 more

fagment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#EB7474"
tools:context="com.example.a.MainActivity$PlaceholderFragment" >

<EditText
    android:id="@+id/n1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="23dp"
    android:layout_marginTop="119dp"
    android:ems="10"
    android:background="#FFE9E9"
    android:hint="num2" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/n2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/n1"
    android:layout_alignBottom="@+id/n1"
    android:layout_alignParentRight="true"
    android:layout_marginRight="20dp"
    android:ems="10"
    android:background="#FFE9E9"
    android:hint="num2" />

<Button
    android:id="@+id/b1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/radioGroup1"
    android:layout_marginTop="99dp"
    android:layout_toRightOf="@+id/n1"
    android:text="Answer" />

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/b1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="69dp"
    android:background="#FFE9E9"
    android:text="@string/hello_world" />

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/n1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="132dp"
    android:orientation="horizontal" >

    <RadioButton
        android:id="@+id/r0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="+" />

    <RadioButton
        android:id="@+id/r1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="-" />

    <RadioButton
        android:id="@+id/r2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="X" />

    <RadioButton
        android:id="@+id/r3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="/" />
</RadioGroup>

</RelativeLayout>

activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.a.MainActivity"
tools:ignore="MergeRootFrame" />

mainActivity.java
package com.example.a;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    Button A;
    TextView B;
    EditText n1;
    EditText n2;
    RadioGroup radioButtonGroup;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        A = (Button) rootView.findViewById(R.id.b1);
        B = (TextView) rootView.findViewById(R.id.tv1);
        n1 = (EditText) rootView.findViewById(R.id.n1);
        n2 = (EditText) rootView.findViewById(R.id.n2);
        radioButtonGroup = (RadioGroup) rootView.findViewById(R.id.radioGroup1);

        A.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
                View radioButton = radioButtonGroup.findViewById(radioButtonID);
                int idx = radioButtonGroup.indexOfChild(radioButton);

                int num1 = Integer.parseInt(n1.getText().toString());
                int num2 = Integer.parseInt(n2.getText().toString());
                int total = 0;
                switch (idx)
                {
                case 0:
                    total = num1+num2;
                    break;

                case 1:
                    total = num1-num2;
                    break;

                case 2:
                    total = num1*num2;
                    break;

                case 3:
                    total = num1/num2;
                    break;

                case -1:
                    break;
                }

                String ttl = String.valueOf(total);
                B.setText(ttl);

            }
        });

        return rootView;
    }
}

}

A: I usually get this error when all I am doing is swapping view in xml layout. It is a ecllipse bug(sometimes) when and as a result your resource is not synced with the adt builder. When I get his error first thing I do is close ecllipse, end process adb.exe from task manager(windows) and then start ecllipse again. If this doesnot help then Android tools -> fix project properties and project -> clean.

A: android.widget.RadioGroup cannot be cast to android.widget.Button

*

*Your XML contains a RadioGroup item

*Your Fragment class is getting that item with findViewById and tries to cast it as a Button. Like that for instance:
Button btn = (Button) getView().findViewById(r.id.myRadioButton);
You'll need to either change your XML to make that a  element or to change your fragment to get a RadioGroup variable:
RadioGroup grp = (RadioGroup) getView().findViewById(r.id.myRadioButton);

A: The problem is that you are trying to cast a RadioGroup to a Button, which you can't do. This is happening in MainActivity.
Post the code for MainActivity if you can't find the problem.

A: As I suspected, I don't see any invalid casting going on.  My guess is that you're receiving this error because there is some disconnect between what has been deployed and what you've got built in your IDE.  R.java is probably stale.  You need to clean (remove bin, gen, lib, obj directories) and rebuild your project.
Here's a similar post where this same thing happened: Android ClassCastException for RadioGroup into RadioButton
Their issue was resolved by shutting down the emulator and restarting the IDE.

A: this is simple one!
I had came across this once. It seems quite baffling & frustrating at first, but the only thing you need to do is help eclipse get aware of the fact that the position and layout of a few (or all) components have been modified/altered.
And this you are supposed to achieve by building the work space from scratch.
For that all you need to do is close and restart eclipse.
That'll do.


Q: Running Multiple Versions of PHP Using Apache on Gentoo I have a Gentoo Linux web server that serves a few PHP-based web applications using Apache. Most of the applications will run on the latest version of PHP (i.e. 7.2); however, one application needs to run on a very old version of PHP (i.e. 5.6). How can I run multiple versions of PHP simultaneously on the same web server?

*

*Gentoo (profile 17).

*Web Server is Apache 2.4.

*Need to run PHP 7.2 and PHP 5.6.

*Apache is currently configured to serve PHP 7.2 via mod_php but PHP 5.6 is also installed.

*Gentoo is configured to use eselect to change which version of PHP is used for Apache/mod_php.

A: This answer is specifically for Gentoo with Profile 17. It will probably work with a few versions plus and minus. I used Red Hat's PHP Configuration Tips page for inspiration. The same idea should work for other Linux distributions (of course the specific commands will differ).
The solution is to use PHP-FPM (FastCGI Process Manager). Each version of PHP gets its own PHP-FPM service that listens on a socket. Apache passes the PHP execution requests to a particular PHP-FPM service depending on which version of PHP is required.
You can use mod_php for one version of PHP and PHP-FPM for the other(s) but I decided to drop mod_php altogether. First, I read somewhere that you can save some memory overhead by disabling mod_php. Second, the solution seemed a little cleaner with all versions of PHP being handled in the same way. Third, it is always better to have the least amount of/only the necessary software installed from a security perspective.

*

*Change your USE flags for dev-lang/php to add fpm and remove apache2.
Current Gentoo convention is to create a file like /etc/portage/package.use/php and specify the USE flags here. If you specify exact versions in the file, make sure all versions of PHP you want to use pick up the these USE flags.

*Install/reinstall the versions of PHP you are going to be using.
# emerge -av =dev-lang/php-7.2.3
# emerge -av =dev-lang/php-5.6.7

*Change your APACHE2_MODULES variable to build the proxy and proxy_fcgi Apache modules.
You specify what Apache modules using by adding/updating the APACHE2_MODULES variable in /etc/portage/make.conf. Like USE flags, Gentoo has some defaults already set-up for your profile. Unlike USE flags, it seems that you need to explicitly tell Gentoo to start with the defaults by prepending $APACHE2_MODULES to the variable:
APACHE2_MODULES="$APACHE2_MODULES proxy proxy_fcgi"

*Reinstall Apache.
# emerge -av apache

*Install PHP-FPM.
# emerge -av php-fpm

*Create PHP-FPM startup scripts for each version of PHP you are using with Apache.
The PHP-FPM installation creates a single startup script (/etc/init.d/php-fpm) that allows you to to choose the version of PHP to run using eselect or by changing the script's file name suffix (e.g. php-fpm-php5.6, php-fpm-php7.2, etc.). Since we would only want to use eselect if we only wanted to use a single version of PHP at a time or if we wanted to use no more than two versions with mod_php for one and PHP-FPM for the second, we will use the suffix method. Instead of copying the script, we want to symlink it (valid suffixes are those directory names from ls -ld /usr/lib64/php* e.g. php5.6, php7.2, etc.):
# cd /etc/init.d
# ln -s php-fpm php-fpm-php5.6
# ln -s php-fpm php-fpm-php7.2

*Change the PHP-FPM configuration so that each PHP version's service runs on a different port.
The specific file names vary between versions but you want to edit a config file for each PHP version in these general locations: /etc/php/fpm-php*/*.conf so that the listen directive has a different port for each.

*Configure PHP-FPM services to start.
# rc-update add php-fpm-php5.6 default
# rc-update add php-fpm-php7.2 default
# /etc/init.d/php-fpm-php5.6 start
# /etc/init.d/php-fpm-php7.2 start

*Edit the Apache start-up configuration to enable proxy modules.
Edit /etc/conf.d/apache2 to add -D PROXY and remove -D PHP from APACHE2_OPTS.

*Edit the Apache configuration to tie specific directory locations to specific instances of PHP-FPM.
There are many ways to handle this depending on your specific Apache configuration. I decided to edit the <Directory> entry associated with my web root so that the default PHP handler was version 7.2 by adding:
<FilesMatch \.php$>
    SetHandler "proxy:fcgi://127.0.0.1:9972" # <-- Note port num.
</FilesMatch>

With PHP 5.6 used only by exception, I added <Directory> directives for each application that needed to use the old version of PHP:
<Directory /var/www/oldapp>
    <FilesMatch \.php$>
        Sethandler "proxy:fcgi:/127.0.0.1:9956" # <-- Note diff port num.
    </FilesMatch>
</Directory>

*Add index.php as a valid directory index file.
In Gentoo /etc/apache2/modules.d/70_mod_php.conf includes a directive to add index.php as a directory index file in the same way index.html usually is. Since we disabled mod_php in Step 9, 70_mod_php.conf no longer exists to set this up. To fix this, add DirectoryIndex index.php to the Apache configuration. Otherwise, if you visit paths like /oldapp/ you will get a 403 error.

*Restart Apache.
# /etc/init.d/apache restart

Other Notes

*

*If you set-up specific configuration settings in your php.ini file (e.g. max POST values, timezone, etc), you will need to set these in all of your /etc/php/fpm-php*/php.ini files (for each version).

*PHP-FPM defaults to running as user=nobody / group=nobody. You may need to change these (in /etc/php/fpm-php*/php-fpm.conf) to match whatever your web server is running.

*To handle multiple virtual hosts, perform Steps 10 and 11 for each.


Q: How to show Product Attributes in Magento 1.9 Frontend? How to show Product Attributes in Magento 1.9 Front-end?

A: You can get attribute on frontend :
<?php $_product->getAttributeText('attribute_code'); ?>

or
<?php $_product->getResource()->getAttribute('attribute_code')->getFrontend()->getValue($_product); ?>


Q: How can I change the background color of table cell (td) using two buttons for different colors? My HTML file:
<!DOCTYPE html>

    <title>Wolf and Rabbit Game</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="wolf&rabbit_game.css">

<input id="button1" type="button" value="I'm red" onclick="setColorRed">
<input id="button2" type="button" value="I'm green" onclick="setColorGreen">

My CSS file:
    table{
        text-align: center;
        margin: auto;
    }
td{
    border: 1px black solid;
    width: 25px;
    height: 25px;
}

#button1,#button2{
    text-align: center;
    margin-top: 20px;
    font-size: 1em;
    font-family: Myriad Pro;
    font-weight: semibold;
    color: white;
    border-radius: 15px;
    padding: 1%;
}

#button1{
    background: red;
}

#button2{
    background: green;
}

body{
    text-align: center;
}

img{
    width: 25px;
    height: auto;
}

My JavaScript file:
function setColor(){
  if ("#button1").click {
    document.getElementById("#tableCell").style.backgroundColor="red";
  };
  if ("#button2").click {
    document.getElementById("#tableCell").style.backgroundColor="green";
  };
};

A: Check this JS Fiddle
JsFiddle link
There is no need of calling two different methods on two different buttons, a single method to accept the color parameter and change the desired element's color is good enough.
You have to modify your code like this and make sure javascript code comes before your button markup.

        test

<input id="button1" type="button" value="I'm red" onclick="setColor('red')">
<input id="button2" type="button" value="I'm green" onclick="setColor('green')">


Q: Efficient Way to Replace Unicode Hex Character Codes in Snowflake String I currently have an issue where text I am importing includes Unicode Hex Character Codes in item descriptions.
For example,   may appear for a no-break space, ê may appear for the French language "ê", etc.
I am wanting the text returned in a view to show the actual characters, rather than the hex character codes.
The best solution I have found so far involves doing something like the below:
CREATE OR REPLACE FUNCTION ENTITY_TO_SYMBOL(STRING VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
  return STRING.replace(/À/g, "À").replace(/Á/g, "Á").replace(/Â/g, "Â").replace(/Ã/g, "Ã").replace(/Ä/g, "Ä").replace(/Å/g, "Å").replace(/à/g, "à").replace(/â/g, "â").replace(/ã/g, "ã").replace(/ä/g, "ä").replace(/å/g, "å").replace(/Æ/g, "Æ").replace(/æ/g, "æ").replace(/ß/g, "ß").replace(/Ç/g, "Ç").replace(/ç/g, "ç").replace(/È/g, "È").replace(/É/g, "É").replace(/Ê/g, "Ê").replace(/Ë/g, "Ë").replace(/è/g, "è").replace(/é/g, "é").replace(/ê/g, "ê").replace(/ë/g, "ë").replace(/ƒ/g, "ƒ").replace(/Ì/g, "Ì").replace(/Í/g, "Í").replace(/Î/g, "Î").replace(/Ï/g, "Ï").replace(/ì/g, "ì").replace(/í/g, "í").replace(/î/g, "î").replace(/ï/g, "ï").replace(/Ñ/g, "Ñ").replace(/ñ/g, "ñ").replace(/Ò/g, "Ò").replace(/Ó/g, "Ó").replace(/Ô/g, "Ô").replace(/Õ/g, "Õ").replace(/Ö/g, "Ö").replace(/ò/g, "ò").replace(/ó/g, "ó").replace(/ô/g, "ô").replace(/õ/g, "õ").replace(/ö/g, "ö").replace(/Ø/g, "Ø").replace(/ø/g, "ø").replace(/Œ/g, "Œ").replace(/œ/g, "œ").replace(/Š/g, "Š").replace(/š/g, "š").replace(/Ù/g, "Ù").replace(/Ú/g, "Ú").replace(/Û/g, "Û").replace(/Ü/g, "Ü").replace(/ù/g, "ù").replace(/ú/g, "ú").replace(/û/g, "û").replace(/ü/g, "ü").replace(/µ/g, "µ").replace(/×/g, "×").replace(/Ý/g, "Ý").replace(/Ÿ/g, "Ÿ").replace(/ý/g, "ý").replace(/ÿ/g, "ÿ").replace(/°/g, "°").replace(/†/g, "†").replace(/‡/g, "‡").replace(/</g, "<").replace(/>/g, ">").replace(/±/g, "±").replace(/«/g, "«").replace(/»/g, "»").replace(/¿/g, "¿").replace(/¡/g, "¡").replace(/·/g, "·").replace(/•/g, "•").replace(/™/g, "™").replace(/©/g, "©").replace(/®/g, "®").replace(/§/g, "§").replace(/¶/g, "¶").replace(/Α/g, "Α").replace(/Β/g, "Β").replace(/Γ/g, "Γ").replace(/Δ/g, "Δ").replace(/Ε/g, "Ε").replace(/Ζ/g, "Ζ").replace(/Η/g, "Η").replace(/Θ/g, "Θ").replace(/Ι/g, "Ι").replace(/Κ/g, "Κ").replace(/Λ/g, "Λ").replace(/Μ/g, "Μ").replace(/Ν/g, "Ν").replace(/Ξ/g, "Ξ").replace(/Ο/g, "Ο").replace(/Π/g, "Π").replace(/Ρ/g, "Ρ").replace(/Σ/g, "Σ").replace(/Τ/g, "Τ").replace(/Υ/g, "Υ").replace(/Φ/g, "Φ").replace(/Χ/g, "Χ").replace(/Ψ/g, "Ψ").replace(/Ω/g, "Ω").replace(/α/g, "α").replace(/β/g, "β").replace(/γ/g, "γ").replace(/δ/g, "δ").replace(/ε/g, "ε").replace(/ζ/g, "ζ").replace(/η/g, "η").replace(/θ/g, "θ").replace(/ι/g, "ι").replace(/κ/g, "κ").replace(/λ/g, "λ").replace(/μ/g, "μ").replace(/ν/g, "ν").replace(/ξ/g, "ξ").replace(/ο/g, "ο").replace(/&piρ;/g, "ρ").replace(/ρ/g, "ς").replace(/ς/g, "ς").replace(/σ/g, "σ").replace(/τ/g, "τ").replace(/φ/g, "φ").replace(/χ/g, "χ").replace(/ψ/g, "ψ").replace(/ω/g, "ω").replace(/•/g, "•").replace(/…/g, "…").replace(/′/g, "′").replace(/″/g, "″").replace(/‾/g, "‾").replace(/⁄/g, "⁄").replace(/℘/g, "℘").replace(/ℑ/g, "ℑ").replace(/ℜ/g, "ℜ").replace(/™/g, "™").replace(/ℵ/g, "ℵ").replace(/←/g, "←").replace(/↑/g, "↑").replace(/→/g, "→").replace(/↓/g, "↓").replace(/&barr;/g, "↔").replace(/↵/g, "↵").replace(/⇐/g, "⇐").replace(/⇑/g, "⇑").replace(/⇒/g, "⇒").replace(/⇓/g, "⇓").replace(/⇔/g, "⇔").replace(/∀/g, "∀").replace(/∂/g, "∂").replace(/∃/g, "∃").replace(/∅/g, "∅").replace(/∇/g, "∇").replace(/∈/g, "∈").replace(/∉/g, "∉").replace(/∋/g, "∋").replace(/∏/g, "∏").replace(/∑/g, "∑").replace(/−/g, "−").replace(/∗/g, "∗").replace(/√/g, "√").replace(/∝/g, "∝").replace(/∞/g, "∞").replace(/&OEig;/g, "Œ").replace(/œ/g, "œ").replace(/Ÿ/g, "Ÿ").replace(/♠/g, "♠").replace(/♣/g, "♣").replace(/♥/g, "♥").replace(/♦/g, "♦").replace(/ϑ/g, "ϑ").replace(/ϒ/g, "ϒ").replace(/ϖ/g, "ϖ").replace(/Š/g, "Š").replace(/š/g, "š").replace(/∠/g, "∠").replace(/∧/g, "∧").replace(/∨/g, "∨").replace(/∩/g, "∩").replace(/∪/g, "∪").replace(/∫/g, "∫").replace(/∴/g, "∴").replace(/∼/g, "∼").replace(/≅/g, "≅").replace(/≈/g, "≈").replace(/≠/g, "≠").replace(/≡/g, "≡").replace(/≤/g, "≤").replace(/≥/g, "≥").replace(/⊂/g, "⊂").replace(/⊃/g, "⊃").replace(/⊄/g, "⊄").replace(/⊆/g, "⊆").replace(/⊇/g, "⊇").replace(/⊕/g, "⊕").replace(/⊗/g, "⊗").replace(/⊥/g, "⊥").replace(/⋅/g, "⋅").replace(/&lcell;/g, "⌈").replace(/&rcell;/g, "⌉").replace(/⌊/g, "⌊").replace(/⌋/g, "⌋").replace(/⟨/g, "⟨").replace(/⟩/g, "⟩").replace(/◊/g, "◊").replace(/'/g, "'").replace(/&/g, "&").replace(/"/g, "\"").replace(/é/g,"é").replace(/'/g,"'").replace(/ê/g,"ê").replace(/à/g,"à").replace(/ /g," ").replace(/°/g,"°").replace(.replace(/±/g,"±");
$$;

This is obviously a nightmare to read, and in order for it to truly be inclusive I would likely need to write a script to generate all the replaces needed.
While I could do this, it does not necessarily seem like the most efficient way to essentially manually replace each character.
I had seen on a different site someone recommending using a lookup table to do this. I could figure out how to do something like this in Python, but was not sure if there was an easy approach for this in Snowflake.
The idea would be having a table where one column is the code, another is the value, and then the UDF would basically replace all instances of any codes with their corresponding values.
This seems like it would be a common problem, but I have not come across any specific solutions.
Any advice regarding how to do this and whether it would be best practice would be appreciated. I know ideally we would parse before loading, but due to the nature of our platform I need to do these transformations in Snowflake.

A: You can do this easily with a Python UDF:
create or replace function py_unescape(X string)
returns string
language python
handler = 'x'
runtime_version = 3.8
as $$
import html

def x(s):
    return html.unescape(s)
$$
;

select py_unescape('À makes me feel Á');
-- À makes me feel Á


Q: Element implicitly has type 'any', because expression of type 'any' cannot be used to index type '{}' I'm trying to solve the duplicateCount() function.
Here is my code :
export const duplicateCount = (text: string): number => {
  let countObj = {}
  if (text.length === 0) return 0
  let allLetters = text.toLowerCase().split("")
  allLetters.forEach(letter => {
      if(countObj[letter]) {
          countObj[letter] ++
      }else {
          countObj[letter] = 1
      }
  })
}

I get an error that says Element implicitly has type 'any', because expression of type 'string' cannot be used to index type '{}'. I don't really understand what it mean, can someone explain how to solve it?

A: I finally end up with this solution code:
export const duplicateCount = (text: string): number => {
  let countObj: Record<string, number> = {}
  let count: number = 0
  if (text.length === 0) return 0
  let allLetters = text.toLowerCase().split("")
  allLetters.forEach((letter) => {
    if (countObj[letter]) {
      countObj[letter]++
    } else {
      countObj[letter] = 1
    }
  })
  for (const key in countObj) {
    if (countObj[key] > 1) {
      count++
    }
  }
  return count
}

I'm open for any suggestion refactoring


Q: Parse v. TryParse What is the difference between Parse() and TryParse()?
int number = int.Parse(textBoxNumber.Text);

// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);

Is there some form of error-checking like a Try-Catch Block?

A: The TryParse method allows you to test whether something is parseable.  If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.
As a footnote, passing in null to most TryParse methods will throw an exception.

A: TryParse and the Exception Tax
Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.

A: If the string can not be converted to an integer, then

*

*int.Parse() will throw an exception

*int.TryParse() will return false (but not throw an exception)

A: Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.
TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.
In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

A: TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

A: For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign  number to zero.
        if (!Int32.TryParse(txt,out tmpint)) {
            tmpint = 0;
        }

and:
        try {
            tmpint = Convert.ToInt32(txt);
        } catch (Exception) {
            tmpint = 0;
        }

For c#, the best option is to use tryparse because try&Catch alternative thrown the exception
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.

A: I know its a very old post but thought of sharing few more details on Parse vs TryParse.
I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.
Old Code:
dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");

New Code:
DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);

Have to declare another variable and used as Out for TryParse.

A: double.Parse("-"); raises an exception, while
double.TryParse("-", out parsed); parses to 0
so I guess TryParse does more complex conversions.


Q: How to show the preview of the input photo in page? I have an img tag and an input type file,
Functionality
The functionality is i will input one jpg file using input type file, i need to show this image in the image tag.
How is it possible in angular 2 ?
My tries
I tried to get the file path on change event of input button and assign it to the src of image file.
Tried to solve it using an external js file.
but both these tries are failure, whats the solution for this.
Code
HTML

   <input type="file" multiple (change)="onUpload(input)" #input >

Component.ts
import { Component, OnInit, NgModule } from '@angular/core';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
})
export class FormComponent implements OnInit {
//DECLARATION
  imagePath:string;

  constructor() {
    this.onInitial();
    }

  ngOnInit() {}

  onInitial(){
    this.imagePath="../../assets/images/1.jpg"
  }
  onUpload(event){
    console.log(event);
  }

}

What the code i need to write inside the onUpload() to assign the path of the input image to the variable imagePath.
Please help me.

A: Have not tried Angular2. Though you should be able to set img src to Blob URL of first File object of input.files FileList.
At chromium, chrome you can get webkitRelativePath from File object, though the property is "non-standard" and possibly could be set to an empty string; that is, should not be relied on for the relative path to the selected file at user filesystem.
File.webkitRelativePath

This feature is non-standard and is not on a standards track. Do not
  use it on production sites facing the Web: it will not work for every
  user. There may also be large incompatibilities between
  implementations and the behavior may change in the future.

File

The webkitRelativePath attribute of the File interface must return
  the relative path of the file, or the empty string if not specified.

4.10.5.1.18. File Upload state (type=file)

EXAMPLE 16 For historical reasons, the value IDL attribute
  prefixes the file name with the string "C:\fakepath\". Some legacy
  user agents actually included the full path (which was a security
  vulnerability). As a result of this, obtaining the file name from the
  value IDL attribute in a backwards-compatible way is non-trivial.

See also How FileReader.readAsText in HTML5 File API works?

<!DOCTYPE html>

  <input type="file" multiple onchange="onUpload(this)" id="input" accepts="image/*" />

A: At last i got the answer my self,
https://github.com/ribizli/ng2-imageupload
this will work for you. It may help you for this issue.


Q: JavaMail with gmail SMTP - How to handle an unexisting email addresses In my project I'm using a JavaMail implementation to send emails through GMAIL's SMTP server.
The general concept is ok, my custom validators checks whether the e-mail was correctly formulated etc...
Everything is fine, however I am not able to catch anything what should be considered, as unsent email. I went deeper into JavaMail docs, and they advised to catch SendMailException and MessageException, but based on the code, it handles only an incorrectly formulated e-mail addresses or an empty Strings. If the user will come up with an unexisting email, but well formulated, the API will not inform that anything happened.
Did anyone handle with the similar issue and knows how to go forward?
Thanks in advance for your help.
@Bean
public JavaMailSender javaMailSender(EmailProperties prop) {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(prop.getHost());
    mailSender.setPort(prop.getPort());
    mailSender.setUsername(prop.getUsername());
    mailSender.setPassword(prop.getPassword());
    mailSender.setDefaultFileTypeMap(FileTypeMap.getDefaultFileTypeMap());
    mailSender.setJavaMailProperties(getProperties(prop));
    mailSender.setProtocol(prop.getProtocol());
    mailSender.setDefaultEncoding("UTF-8");
    return mailSender;
}

private Properties getProperties(EmailProperties prop) {
    Properties props = new Properties();
    props.put("mail.transport.protocol", prop.getProtocol());
    props.put("mail.smtp.auth", prop.getAuth());
    props.put("mail.smtp.starttls.enable", prop.getStarttls());
    props.put("mail.debug", prop.getDebug());
    return props;
}


Q: Retrieve multiple data from firebase database in one cloud function I am faced with the problem of retrieving two data values of a single node from my firebase database and reference it in my javascript file but don't know how to go about it. I have been able to retrieve just one data value from a node (in this case "message") but I would like to add "from" as well. Most tutorials just reference one so I am really confused. So how do I get multiple data values?
This is my code...
JS file
exports.sendNotification7 = functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}/message')
.onWrite(( change,context) =>{

// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = change.after.val();
var str = "New message from System Development Group Chat: " + eventSnapshot;
console.log(eventSnapshot);

var topic = "Management.Information.System";
var payload = {
    data: {
        name: str,
        click_action: "Student_SystemsDevt"

    }
};

// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
    .then(function (response) {
        // See the MessagingTopicResponse reference documentation for the
        // contents of response.
        console.log("Successfully sent message:", response);
        return;
    })
    .catch(function (error) {
        console.log("Error sending message:", error);
    });
});

A: You can read from however many nodes you want in a Cloud Function. However, only one can trigger the function to run.
To read from your database use the following code:
admin.database().ref('/your/path/here').once('value').then(function(snapshot) {

var value = snapshot.val();

});

You will probably want to read from the same place that the Cloud Function was triggered. Use context.params.PARAMETER to get this information. For the example you posted your code would turn out looking something like this:
admin.database().ref('/GroupChat/'+context.params.Modules+'/SDevtChat/'+context.params.SDevtChatId+'/from').once('value').then(function(snapshot) {

var value = snapshot.val();

});

A: Just trigger your function one level higher in the JSON:
exports.sendNotification7 =
functions.database.ref('/GroupChat/{Modules}/SDevtChat/{SDevtChatId}')
.onWrite(( change,context) =>{

    // Grab the current value of what was written to the Realtime Database.
    var eventSnapshot = change.after.val();
    console.log(eventSnapshot);
    var str = "New message from System Development Group Chat: " + eventSnapshot.message;
    var from = eventSnapshot.from;

    ...


Q: Extracting Multiple Elements with same html criteria in python I'm novice with python and beautiful so this answer may be obvious.
I'm using beautiful soup to parse the following html and extract the Date.
html='''

Event:Meeting

Date: Mon, Apr 25, 2016, 11 am

Price:$20.00

Event:Convention

Date: Mon, May 2, 2016, 11 am

Price:$25.00

Event:Dance

Date: Mon, May 9, 2016, 11 am

Price:Free

'''

I parsed the date when there is only one date using the following code but having a hard time when encountering multiple dates (only gets one date).
date_raw = html.find_all('strong',string='Date:')
date = str(date_raw.p.nextSibling).strip()

Is there a way to do this in bs4 or should I use regular expressions.  Any other suggestions?
Desired list output:
['Mon, Apr 25, 2016, 11 am','Mon, May 2, 2016, 11 am','Mon, May 9, 2016, 11 am']

A: I would probably iterate of every found element and append it to a list.  Something like this maybe (untested):
date_list = []
date_raw = html.find_all('strong',string='Date:')

for d in date_raw:
    date = str(d.p.nextSibling).strip()
    date_list.append(date)

print date_list

A: Rookie mistake...fixed it:
for x in range(0,len(date_raw)):
    date_add = date_raw[x].next_sibling.strip()
    date_list.append(date_add)
    print (date_add)


Q: How to split strings based on "/n" in Java I have got a string
$key1={331015EA261D38A7}
$key2={9145A98BA37617DE}
$key3={EF745F23AA67243D}

How do i split each of the keys based on "$" and the "next line" element?
and then place it in an Arraylist?
The output should look like this:
Arraylist[0]:
$key1={331015EA261D38A7}

Arraylist[1]:
$key2={9145A98BA37617DE}

Arraylist[2]:
$key3={EF745F23AA67243D}

A: If you just want to split by new line, it is as simple as :
yourstring.split("\n"):

A: yourstring.split(System.getProperty("line.separator"));

A: Don't split, search your String for key value pairs:
\$(?<key>[^=]++)=\{(?<value>[^}]++)\}

For example:
final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
    parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));

Output:

Key 'key1' has value '331015EA261D38A7'
  Key 'key2' has value '9145A98BA37617DE'
  Key 'key3' has value 'EF745F23AA67243D'


Q: Unit root tests for panel data in R I have the plm package and would like to run unit root tests on some variables. I get the following error:
> purtest(data$tot.emp)
Error in data.frame(baldwin = c(59870, 61259, 60397, 58919, 57856, 57227,  :
  arguments imply differing number of rows: 14, 19, 11, 12, 1, 20, 18, 10, 13

I assume that I'm getting this error because my panel is unbalanced. Two questions:

*

*Can you use panel unit root tests (Levin, Lin and Chu (2002), Im, Pesaran and Shin (2003), or others) for unbalanced panels?

*If so, is it implemented in R?

A: At the current moment (version 1.2-10, 2012-05-05) it seems that the unbalanced case is not supported. Edit: The issue of unbalanced panel data is solved in version 2.2-2 of plm on CRAN (2020-02-21).
Rest of the answer is assuming version 1.2-10:
I've looked at the code, and the final data preparation line (no matter what is your initial argument) is the following:
 object <- as.data.frame(split(object, id))

If you pass unbalanced panel, this line will make it balanced by repeating the same values. If your unbalanced panel has time series with lengths which divide each other then even no error message is produced. Here is the example from purtest page:
 > data(Grunfeld)
 > purtest(inv ~ 1, data = Grunfeld, index = "firm", pmax = 4, test = "madwu")

Maddala-Wu Unit-Root Test (ex. var. : Individual Intercepts )

  data:  inv ~ 1
  chisq = 47.5818, df = 20, p-value = 0.0004868
  alternative hypothesis: stationarity

This panel is balanced:
 > unique(table(Grunfeld$firm))
  [1] 20

Disbalance it:
 > gr <- subset(Grunfeld, !(firm %in% c(3,4,5) & year <1945))

Two different time series length in the panel:
 > unique(table(gr$firm))
  [1] 20 10

No error message:
> purtest(inv ~ 1, data = gr, index = "firm", pmax = 4, test = "madwu")

    Maddala-Wu Unit-Root Test (ex. var. : Individual Intercepts )

data:  inv ~ 1
chisq = 86.2132, df = 20, p-value = 3.379e-10
alternative hypothesis: stationarity

Another disbalanced panel:
  > gr <- subset(Grunfeld, !(firm %in% c(3,4,5) & year <1940))
  > unique(table(gr$firm))
  [1] 20 15

And the error message:
 > purtest(inv ~ 1, data = gr, index = "firm", pmax = 4, test = "madwu")
  Erreur dans data.frame(`1` = c(317.6, 391.8, 410.6, 257.7, 330.8, 461.2,  :
  arguments imply differing number of rows: 20, 15

A: Did you try to convert your data to pdata.frame? I have an unbalanced panel also, but purtest seems to work with unbalanced panel if the data is pdata.frame. But I might be wrong too:)
However in ?purtest authors write:
"object, x

Either a 'data.frame' or a matrix containing the time series,
a 'pseries' object, a formula, or the name of a column of a 'data.frame',
or a **'pdata.frame'**
on which the test has to be computed; a'purtest' object for the print
and summary methods,"

So I guess if one uses pdata.frame the purtest "understands" that panel is unbalanced.
Am I wrong???

A: You can use for sure the IPS test on unbalanced data, as long as you test for the Wtbar or Ztbar statistic.
Fore example, the following R code can be used to test sattionarity in unbalanced heterogeneous panel data, with IPS test (plm package):
`purtest(data$tot.emp, test = c("ips"), ips.stat="Ztbar", exo="intercept",dfcor=TRUE, lags = c("AIC"), pmax = 10)`

A: Eviews 5 allows you to test the panel unit roots for the unbalanced data that is not possible with R and Stata. For example, even though Im–Pesaran–Shin and Fisher-type tests can be applied for unbalanced panel in Stata, it is not possible if we have some observations , with the gap i.e. we have data of country i for year 2002 and 2004 but not 2003 (assuming the lag to be greater than one). I think that Eviews drop all such observations while performing tests, for our example this is country i. However, if you manually drop all such observations, you can still perform the tests with R and Stata.


Q: Disable weaker TLS ciphers for a Linux hosted ASP.NET Core app I am looking at disabling RC4 and 3DES TLS ciphers in my application and wondering how to implement this?
The application is Angular/ASP.NET Core currently in the latest versions of both technologies. The application is hosted on a Red Hat 7 server.

A: Application level
You may try to force your app to only support TLS 1.3.
TLS 1.3 supports only ciphers thought to be secure.
This post explains how to do it for TLS 1.2, you would just have to change the
s.SslProtocols = SslProtocols.Tls12;

to
s.SslProtocols = SslProtocols.Tls13;

More informations here
Feel free to test it with SSL Labs

You can stay on TLS 1.2 and manually choosing your ciphers by doing this.
Proceed with absolute caution when doing this. You want to do this only if you absolutely know what you're doing.
var ciphersArray = new TlsCipherSuite[]
{
    TlsCipherSuite.TLS_AES_256_GCM_SHA384, // etc
};

var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureWebHost(webHostBuilder =>
{
    webHostBuilder.ConfigureKestrel(kestrelServerOptions =>
    {
        kestrelServerOptions.ConfigureHttpsDefaults(w =>
        {
            w.OnAuthenticate = (x, s) =>
            {
                var ciphers = new CipherSuitesPolicy(ciphersArray);
                s.CipherSuitesPolicy = ciphers;
            };
        });
    });
});

OS Level
It's not your OS version but this RHEL 8 doc could be interesting to you. As you can see the DEFAULT option doesn't allow RC4 and 3DES


Q: Angular 2: How to render a multiple event in fullcalndar I am using FullCalendar in angular 2, Events for fullcalendar coming from other source, problem is how should i render the events which contain only multiple event on the day,need to hide or not clickable which show only single event.
Please help me


Q: problems populating list view from text file Android Ok so I am trying to populate a list view in android from a linked list of objects. I am reading lines from a text file, splitting out two values from each line of the text file separated by a "," storing each of these values into a linked list of objects. Then I'm pulling the name field of each object to populate a list view. I know it's sloppy I'm just starting with Android :E It won't run at all at this point but there are no errors in the code.
here's my activity.java file
package com.pkuCalc.pkuCalc;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Bundle;

public class PkuCalcActivity extends Activity {
    private ListView lv;
List<Food> foodlist = new LinkedList<Food>();
int numFoodItems = 0;
/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    lv = (ListView) findViewById(R.id.listView1);

    try{

        InputStream inputStream = getResources().openRawResource(R.raw.food);

        if (inputStream != null) {

            InputStreamReader inputreader = new InputStreamReader(inputStream);

            BufferedReader r = new BufferedReader(inputreader);

            String strLine;

            while (( strLine = r.readLine()) != null)   {
                int z = 0;
                int length = strLine.length();
                int ind = strLine.indexOf( ',' );
                String name = "";
                for (int i = 0; i < ind; i++) {
                    name = name + strLine.charAt(i);
                }
                String sphe = "";
                for (int i = ind + 2; i < length; i++) {
                    sphe = sphe + strLine.charAt(i);
                }
                int phe = Integer.parseInt(sphe);

                Food newFood = new Food(name, phe);
                foodlist.add(newFood);

                numFoodItems = z;
                z++;
            }

        }

        inputStream.close();

    } catch (IOException e){    //Catch exception if any
        e.printStackTrace();
    }

    ArrayList<String> values = new ArrayList<String>();

    for (int i = 0; i <= numFoodItems; i++) {
        values.add((foodlist.get(i)).getName());
    }

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
    lv.setAdapter(arrayAdapter);

    setContentView(R.layout.main);

}

}

A: You cannot find a view by it's ID until AFTER the call to
setContentView(R.layout.main);

Put the above line as the 2nd line of your onCreate function and it will work.

A: As a suggestion, a handy java function is String.split(String pattern).  Still assuming that each line in your text will always be: string, integer.  We can re-write you reader loop:
while (( strLine = r.readLine()) != null) {
    String[] pair = strLine.split(",");
    Food newFood = new Food(pair[0], Integer.parseInt(pair[1]));
    foodlist.add(newFood);
}

I'm not too sure what z nor numFoodItems are doing since they are set to zero on each loop so I left them out. If you want to know how many food items you have in foodlist you can always call foodlist.size();
You can condense this loop even more, but at some point you start to lose readability so it's up to you.
Addition
Aha, that is what you are trying to do with numFoodItems. Let's change the loop you use to build values:
for (Food foodItem : foodlist) {
    values.add(foodItem.getName());
}

For-Each loops like these are faster, according to Oracle, and as a bonus they are shorter to type.  Now you might get more than one row in your ListView.


Q: How to create hashMap that has a list of hashmap in kotlin?
What I am trying to achieve is is a map that has a list of maps in which the first key is ID and value obviously is a map of which the key is Session and the value is an OBJECT.

var newSession = ConcurrentHashMap<String, ConcurrentHashMap<WebSocketSession, String>>()

What if I want to save multiple session maps with the same ID? Whenever I pass an ID I want to get a map from which I should be able to search a particular session?
Sorry for not being so clear, but I am stuck here for a while and am kinda newbie in Kotlin!
Thanks in advance!


Q: How to remove something from one list and add it to another in python I have a nested list that has certain elements with an [x] at the beginning. I want the function to remove those elements and move them to the last list in list1 (at index 2). But it should remove the [x] from it before placing it in the last list. It should also count how many were removed from each list.
For example:
list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']

# After:

list1 = [['stretch'], ['school'], ['sleep','midterm', 'homework', 'eat', 'final']]

# Output:
# 2 removed from 1st list
# 1 removed from 2nd list

A: This is how you would do that:
list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
for x in range(0,len(list1)-1):
    lst = list1[x]
    count =  0
    to_be_removed = []
    for str in lst:
        if str[0:3] == "[x]":
            to_be_removed.append(str)
            list1[-1].append(str[3:])
            count += 1
    for str in to_be_removed:
        lst.remove(str)
    print(f"{count} items were removed from list {x+1}" )
print(list1)

A: list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
new_list = [list() for i in range(len(list1))]
new_list[2] = list1[2]

items = 0
for i in range(len(list1)-1):
    for j in list1[i]:
        if "[x]" in j:
            new_list[2].append(j.replace("[x]", ""))
            items += 1
        else:
            new_list[i].append(j)

print(list1, new_list, items)

A: I think you have a data structure problem.  Your code shouldn't match user input, you should get away from that as soon as possible, and separate display and storage.  That being said, you can take a step towards those changes by still discarding the silliness asap:
Example of running:
$ python code.py
[['[x]homework', '[x]eat', 'stretch'], ['[x]final', 'school'], ['sleep', 'midterm']]
changed count is 0
[['stretch'], ['school'], ['sleep', 'midterm', 'homework', 'eat', 'final']]

with source code like below
def main():
    list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']]
    print(list1)
    count, list2 = process(list1)
    print(f'changed count is {count}')
    print(list2)

def parse(silly_item):
    if silly_item.startswith('[x]'):
        finished = True
        raw_item = silly_item[3:]
    else:
        finished = False
        raw_item = silly_item
    return finished, raw_item

def process(silly_data_format):
    todos, done = silly_data_format[:-1], silly_data_format[-1]
    count = 0
    new_todos = []
    new_done = done[:]
    for todo in todos:
        new_todo = []
        for silly_item in todo:
            finished, raw_item = parse(silly_item)
            target = new_done if finished else new_todo
            target.append(raw_item)
        new_todos.append(new_todo)
    new_silly_data_format = new_todos + [new_done]
    return count, new_silly_data_format

if __name__ == '__main__':
    main()


Q: shorter way to execute a function named as $_POST value if (isset($_POST['fn'])) {
    if ($_POST['fn'] == 'giveme_lb') {giveme_lb();}
    elseif ($_POST['fn'] == 'giveme_lc') {giveme_lc();}
    elseif ($_POST['fn'] == 'ico_save') {ico_save();}
    ...
}

So I need to execute a function with the name of $_POST['fn'] value.
Any shorter way to say this?
something like $_POST['fn']();

A: call_user_func($_POST['fn']);

See http://php.net/call_user_func.
But in fact $_POST['fn']() will work in all non-ancient PHP versions as well (5.3+ if I remember correctly).
But you absolutely need to whitelist the value first, so users can't invoke arbitrary code on your system:
$allowed = ['giveme_lb', ...];
if (!in_array($_POST['fn'], $allowed)) {
    throw new Exception("Not allowed to execute $_POST[fn]");
}


Q: Filling form fields in Word automatically with pywin32 I have a little problem to solve, but I don´t get an acceptable solution. I try to have a script that automaticcaly fills in FormFields in Word with entries of dictionaries. So far I used pywin32 for that task and somehow I managed to find a solution that works at all. At least as long as I update the word  document.
The command that I use so far in a loop is "marks(i).Result = keyValue". Here "marks" is - as far as I understand - a formfields object, which I get by "marks = doc.FormFields".
As I said, all this works to some extent, but as soon as I update the document in Word, all entries disappear again.
Would be really great if someone could help me and knows how to make it that the entry remains permanent. Unfortunately I do not understand the documentation of pywin32 at all. Attached below is the whole function.
Thanks in advance!
def wordExport(window, excDict, docPath):

    wordApp = win32com.client.Dispatch('Word.Application') #Word App Object
    wordApp.Visible = False
    doc = wordApp.Documents.Open(docPath) #Open .docx
    marks = doc.FormFields # FormFields object
    cMarks = marks.Count # FormField count
    cMatches = 0 #Match counter
    cOverwrt = 0 #Fields overwritten

    for i in range(1, cMarks + 1):
        fieldName = str(marks(i).Name) #String object of FormField

        #Default Cases --------------------------------------------------------------------
        if fieldName in excDict:
            keyValue = excDict.get(fieldName) #Get value to key(FormField)
            resultIsEmpty = not marks(i).Result #No text has been entered before

            # No prior entry present
            if keyValue != "None"
                marks(i).Result = keyValue + " "
                cMatches += 1
                if not resultIsEmpty:
                    cOverwrt += 1

    doc.Close()
    wordApp.Visible = False


Q: Why when I click messagebox OK button the close code not execute? I have windows form application and I want to prevent making duplicate orders for the same patient
and I check if the patient have order today and if I try to make another order it will show message
patient have order today then when click ok button I need to close the window , but its not closing the window when click ok button ,
This is the code I used :
var patientNumber = order.GetPatientNumber(Convert.ToInt32(textPatientID.Text),Program.branch_id); // int?
            bool patientExists = patientNumber.HasValue;
            if (patientExists == true)
            {
                DialogResult dialogResult = MessageBox.Show("PATIENT HAS ORDER TODAY ", "DUPLICATE ORDER ", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                if (dialogResult == DialogResult.OK)
                {
                    this.Close();
                }

            }

I tried also to close the form without if but also not closing :
var patientNumber = order.GetPatientNumber(Convert.ToInt32(textPatientID.Text),Program.branch_id); // int?
            bool patientExists = patientNumber.HasValue;
            if (patientExists == true)
            {
                DialogResult dialogResult = MessageBox.Show("PATIENT HAS ORDER TODAY ", "DUPLICATE ORDER ", MessageBoxButtons.OK, MessageBoxIcon.Stop);

                    this.Close();

            }

why its not closing what's the wrong please your help ?

A: I can see no reason in
if (dialogResult == DialogResult.OK)

check, since the dialog has the only OK button:
if (order
    .GetPatientNumber(int.Parse(textPatientID.Text), Program.branch_id)
    .HasValue) {
  MessageBox.Show(
    "PATIENT HAS ORDER TODAY",
    "DUPLICATE ORDER",
     MessageBoxButtons.OK,
     MessageBoxIcon.Stop);

  Close();
}


Q: Fly command won't work after installing flight plan So I was working through a tutorial to deploy my node app to a server. They had me npm install flightplan -g so I can use the 'fly' command. This all worked but for the fly command to work I needed to install rsync. I finally got rsync to work after changing my PATH. But now when I use to fly command I get "'fly' is not recognized as an internal or external command,
operable program or batch file."
I've tried changing the PATH hundreds of times to different things and I can't for the life of my get the fly command to work again. I've tried reinstalling flightplan globally a bunch of times. NOTHING IS WORKING.

A: Node JS NPM modules installed but command not recognized
This was the answer I was looking for.. I had the end of my path set to npm/fly and not just npm....


Q: How to prove the Lipschitz property and convergence of infimal convolution functions? Here is my problem.
Suppose $f:\mathbb{R}^n\rightarrow \mathbb{R}\cup\{+\infty\}$ is a positive function. Define
$f_n(x)=\inf \{f(y)+nd(x,y):y\in \mathbb{R}^n\}$. Prove that $f_n(x)$ is Lipschitz continuous and $f_n(x)\rightarrow f(x)$.
I find $f_n(x)$ are increasing, $f_n(x)\leq f(x)$ and for each $n$, $f_n(x)$ is upper semi-continuous  without using the condition $f\geq 0$. I wonder how this condition make sense. Thanks~

A: The condition $f \ge 0$ guarantees that $f_n(x)$ is finite for all $x$, and it would suffice to require that $f$ is bounded below.
The example $f(x) = - \Vert x \Vert^2$ shows that without a lower bound, $f_n(x)$ can be identically $-\infty$.
The Lipschitz continuity follows from the triangle inequality: For fixed $x_1, x_2 \in \Bbb R$ and all $y \in \Bbb R$ we have
$$
 f(y) + nd(x_1, y) \le f(y) + nd(x_2, y) + nd(x_1, x_2)
$$
which implies $f_n(x_1) \le f_n(x_2) + nd(x_1, x_2)$. Now exchange $x_1$ and $x_2$ and conclude that
$$
|f_n(x_1) - f_n(x_2) | \le n d(x_1, x_2) \, .
$$
$f_n(x) \to f(x)$ holds if $f$ is lower semi-continuous at $x$, see for example Lower semicontinuous function as the limit of an increasing sequence of continuous functions.
Without lower semi-continuity it can be wrong. A counter example would the function defined by $f(0) = 1$ and $f(x) = 0$ otherwise, where $0 = f_n(0) \not \to f(0) = 1$.


Q: Worklight 6.1 and iOS 8 I have some Apps developed with WL 6.1 and now, I updated my device to iOS 8 and none of the App is working. All of then are stucked in the Splash Screen.
I can't update WL because my server is in the "old" version.
Any suggestion?

A: Update:
Please see the following tech note for iOS 8 support: http://www-01.ibm.com/support/docview.wss?uid=swg21684538
The link includes download links for patched versions of Worklight 5.0.6, 6.0, 6.1 and 6.2 as well as a list of fixed issues and other instructions.

*

*The relevant iFix is that from September 18th at the least.

*The fix is Studio-only.

*Users of Worklight 6.1.0.x should use the iFix from September 19th containing an App Store submission bug fix.

*Users of Worklight 6.0.0.x should also delete the wlBuildResources folder from the tmp directory prior to generating the fixed version (close Eclipse > Delete > Open Eclipse).

*Due to the nature of the defect (in native code, before the Worklight framework initializes), there are no alternatives other than the below...
Scenarios:

*

*If a user has already upgraded to iOS8 and the application got stuck on the splash screen, AFAIK the way to handle it is to either:

*

*Uninstall/re-install the application from the App Store.

*Install a newer app version (see below) from the App Store.

*If a user did not yet upgrade to iOS8, it is best to use the fixed Worklight Studio to generate an updated app, increment its version and re-publish it. Then, Remote Disable the existing version and direct users to install the fixed version from the App Store; the fixed version should then continue to work after upgrading to iOS8.

Old:
Worklight in general does support iOS 8, but this is a specific scenario that requires further investigation. Thanks for the report, We're going to look into it.


Q: Find the complex number $p+qi$. $a, b, c$ are different complex numbers and they satisfy the following:
$$\frac{a}{1-b}=\frac{b}{1-c}=\frac{c}{1-a}=p+qi.$$
Find the values for $p$ and $ q$.
I have found out that $(a-b)^2+(b-c)^2+(c-a)^2=0$

A: Hint: Let $p+qi = z$, then $ z =  a + zb = b + z c = c + za $.
By taking the difference of these equations, show that $ z^3 =-1$, .
If $ z = -1$, then prove that there are no solutions.
If $ z = \frac{1}{2} + \frac{\sqrt{3}}{2} i$, then find solutions.
If $ z = \frac{1}{2} - \frac{\sqrt{3}}{2} i$, then find solutions.


Q: Undefined behaviours in C Recently I came across a number of undefined features in C, one of them being the following:
https://stackoverflow.com/questions/8698048/behaviour-of-non-const-int-pointer-on-a-const-int
Could someone tell me what should I answer when such a question is asked during online exams ( and None of These / Undefined option is not available ) ?
Also, could you point me to a document specifying the most commonly encountered undefined behaviours in C ?
Thanks.

A: I presume you are referring to an online exam in which there is no professor to speak to, and no margin to handwrite an objection.
So, what I would do in your shoes is that I would pick the answer that most closely matches "undefined" (something like "prohibited" or "crash") and if none of these are available then I would just pick a guess.  Then, I would wait until my exam gets graded, and if my answer to this question is flagged as wrong, I would take it to the dean.
Start looking for the dean's email from now.
EDIT
The most famous instance of undefined behavior in C is this:
int somefunction( int x, int y );
...
int a = 5;
int result = somefunction( a, a++ );

The question is "what is wrong with the above call?"
I came across this one in an interview once, but it was just for bonus points, they did not really expect the candidate to know. The answer is undefined behavior because C does not guarantee to you that 'a++' will be evaluated after 'a'. So, somefunction may be called with x=5, y=6 or it may be called with x=5, y=5 or x=6, y=6. (or a whale and a bowl of petunias might fall from the sky <-- EDIT: no, this is not a possibility.)

A: You can do either of the following:

*

*Check the "right" answer (the one that your experience with the professor tells you that he wants to see). Sometimes the professors think they know better when they don't. You can argue (and get a hit with the grade) or just let them hear what they want to hear.

*Approach the professor and raise the issue. Ask a question during the office hours or even in the class. That's what I would do. You don't want to know my GPA.

*Write (if possible) an additional answer "This is undefined behavior per standard, but I believe most compilers would do ..." and proceed with #1.
Generally if professors put you in this position it means a lot about their own knowledge and qualifications. But, I don't think you want to put yourself into a position of that annoying student that puts the professor to shame. I did it twice, in one class I ended up with A+, in another with barely a B (after scoring 100% in the final exam). You never know how they'll take it. Some are ready to admit a mistake, some will be very vicious.


Q: GDB: Seeing the source code lines? Does any program compiled with the -g command have its source code available for gbd to list even if the source code files are unavailable?? Also when you set the breakpoints at a line in a program with a complicated multi source file structure do you need the names of the source code files??

A: OP's 1st Question:

Does any program compiled with the -g command have its source code available for gbd to list even if the source code files are unavailable??

No.  If there is no path to the sources, then you will not see the source.
OP's 2nd Question:

[...] when you set the breakpoints at a line in a program with a complicated multi source file structure do you need the names of the source code files??

Not always.  There are a few ways of setting breakpoints.  The only two I remember are breaking on a line or breaking on a function.  If you wanted to break on the first line of a function, use
break functionname

If the function lives in a module
break __modulename_MOD_functionname

The modulename and functionname should be lowercase, no matter how you've declared them in the code.   Note the two underscores before the module name.  If you are not sure, use nm on the executable to find out what the symbol is.
If you have the source code available and you are using a graphical environment, try ddd.  It stops me swearing and takes a lot of guesswork out of gdb.  If the source is available, it will show up straight away.


Q: Pymongo, Motor memory leak Background: I use tornado + motor, and found the mem_usage increase.
Then I code the test.py. The db.tasks "size" : 12192854 (10+M). After one minute, MEM USAGE / LIMIT is  1.219GiB / 8GiB
env:

*

*python 3.7.5

*motor 2.5.0 (2.1.0 before upgrade)

*multidict 4.7.5

*pymongo 3.12.0

Here are my code
import os
import gc
import time
import logging
import asyncio
import uvloop
import pdb
import pymongo
import base64
from tornado.platform.asyncio import AsyncIOMainLoop
from guppy import hpy
from motor import motor_asyncio

mongo_auth = 'xxxxx='
runtime_mongos = arch_mongos = {
    "host": f"mongodb://{base64.b64decode(mongo_auth).decode()}@" + ','.join(
        [
            "1xxx:27024",
            "2xxx:27024",
            "3xxx:27024",
        ]),
    "readPreference": "secondaryPreferred"
}
table = motor_asyncio.AsyncIOMotorClient(**runtime_mongos)["db"]["tasks"]

async def get_data():
    return await table.find().sort([
            ("priority", pymongo.ASCENDING),
            ("start_uts", pymongo.ASCENDING),
        ]).to_list(None)

async def test():
    while True:
        a = await get_data()
        print(len(a))
        await asyncio.sleep(1)
        gc.collect() # no use!

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test())

A: Finally, I found the python process has a lot of threads, then I get a clue about the motor 'ThreadPoolExecutor'.
code in motor 2.1:
if 'MOTOR_MAX_WORKERS' in os.environ:
    max_workers = int(os.environ['MOTOR_MAX_WORKERS'])
else:
    max_workers = tornado.process.cpu_count() * 5

_EXECUTOR = ThreadPoolExecutor(max_workers=max_workers)

I set MOTOR_MAX_WORKERS=1 and the mem_usage keeps in low level.
I deploy my project in docker.But, the cpu of the container is not exclusive.I guess this is the reason of 'max_workers' is irrational.
My fault...


Q: Find formula for $\sum_{k = 1}^{n}(k^2 \cdot x^{k - 1})$. It is almost obvious that we have to use derivative in order to find the answer. However, I couldn't see this one to be derivative of something.
It would be amazing if you share your thoughts on this problem. Also, I would be thankful if you would explain what was intuition behind your solution. Thanks!

A: Let $$f(x)=\sum_{k=0}^nx^k,$$ so that $$
\begin{align}
f'(x)&=\sum_{k=1}^n kx^{k-1}\\
xf'(x)&=\sum_{k=1}^n kx^k\\
f'(x)+xf''(x)&=\sum_{k=1}^n k^2x^k\\
\end{align}$$
Now just evaluate $f(x)$ and fill in the details.

A: An old trick !
$$S=\sum_{k = 1}^{n}k^2 \, x^{k - 1}=\sum_{k = 1}^{n}\big[k(k-1)+k \big]\, x^{k - 1}$$ that is to say
$$S=\sum_{k = 1}^{n}k(k-1) \, x^{k - 1}+\sum_{k = 1}^{n}k \, x^{k - 1}$$
$$S=x\sum_{k = 1}^{n}k(k-1) \, x^{k - 2}+\sum_{k = 1}^{n}k \, x^{k - 1}$$
$$S=x \left(\sum_{k = 1}^{n}x^k \right)''+\left(\sum_{k = 1}^{n}x^k \right)'$$


Q: Pgfplots: rotate arrow marks by a third arbitrary data In the following mwe, my goal is to have the arrows point in the arbitrary direction given by the third column of the data.

After reading some answers (for example from Dr. Feursänger there or this other question), I started to define my marker, with the hope to rotate it. I couldn't go any further. Is there a simple solution ?
The image is generated with:
\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}

\pgfplotstableread{
  5.30E-001 5.30E-001   -7.85E-001
  5.96E-001 5.89E-001   -7.85E-001
  6.69E-001 6.39E-001   -7.85E-001
  7.47E-001 6.81E-001   -7.85E-001
  8.29E-001 7.13E-001   -7.85E-001
  9.14E-001 7.36E-001   -7.84E-001
  1.00E+000 7.48E-001   -7.81E-001
  1.09E+000 7.49E-001   -7.72E-001
  1.18E+000 7.41E-001   -7.55E-001
  1.26E+000 7.22E-001   -7.28E-001
  1.35E+000 6.93E-001   -6.91E-001
  1.43E+000 6.54E-001   -6.43E-001
  1.50E+000 6.07E-001   -5.88E-001
  1.57E+000 5.51E-001   -5.25E-001
  1.63E+000 4.87E-001   -4.57E-001
  1.68E+000 4.17E-001   -3.85E-001
  1.73E+000 3.40E-001   -3.11E-001
  1.76E+000 2.60E-001   -2.34E-001
  1.79E+000 1.75E-001   -1.57E-001
  1.81E+000 8.82E-002   -7.85E-002
}\datatable

\begin{tikzpicture}[trim axis left, trim axis right]
  \pgfdeclareplotmark{yawarrow}{%
    \draw[->] (0,0)--(0,100);
  }
  \begin{axis}
    [
      xlabel={$x$},
      ylabel={$y$},
    ]
    \addplot[%
      mark=yawarrow,
 %     mark options={rotate=\thisrowno{2}}, % This won't work
    black] table[x index={0},y index={1}] {\datatable};

  \end{axis}
\end{tikzpicture}

\end{document}

Edit
Based on the answer to this question, I've tried to update my code as follows. This fails with Undefined control sequence \yaw. Am I missing something on the use of the option and on of the \yaw ?
\pgfplotstablegetrowsof{\datatable}
\pgfmathsetmacro{\rows}{\pgfplotsretval-2}

\begin{tikzpicture}[trim axis left, trim axis right]
  \pgfdeclareplotmark{yawarrow}{%
    \draw[->] (0,0)--(0,100);
  }
  \begin{axis}
    [
      xlabel={$x$},
      ylabel={$y$},
    ]
      \foreach \k in {0,...,\rows}
      {
    \pgfplotstablegetelem{\k}{[index]0}\of\datatable
      \let\x\pgfplotsretval
      \pgfplotstablegetelem{\k}{[index]1}\of\datatable
      \let\y\pgfplotsretval
      \pgfplotstablegetelem{\k}{[index]2}\of\datatable
      \let\yaw\pgfplotsretval
      \pgfmathsetmacro{\K}{\k+1}
      \pgfplotstablegetelem{\K}{[index]0}\of\datatable
      \let\X\pgfplotsretval
      \pgfplotstablegetelem{\K}{[index]1}\of\datatable
      \let\Y\pgfplotsretval
      \addplot [
        mark=yawarrow,
        mark options={rotate=\yaw}, %Won't work either
      ] coordinates {(\x,\y) (\X,\Y)};
    }
    \end{axis}
  \end{tikzpicture}

A: I would do this using a quiver plot instead of rotating markers:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}

\begin{document}

\begin{filecontents}{data.dat}
  5.30E-001 5.30E-001   -7.85E-001
  5.96E-001 5.89E-001   -7.85E-001
  6.69E-001 6.39E-001   -7.85E-001
  7.47E-001 6.81E-001   -7.85E-001
  8.29E-001 7.13E-001   -7.85E-001
  9.14E-001 7.36E-001   -7.84E-001
  1.00E+000 7.48E-001   -7.81E-001
  1.09E+000 7.49E-001   -7.72E-001
  1.18E+000 7.41E-001   -7.55E-001
  1.26E+000 7.22E-001   -7.28E-001
  1.35E+000 6.93E-001   -6.91E-001
  1.43E+000 6.54E-001   -6.43E-001
  1.50E+000 6.07E-001   -5.88E-001
  1.57E+000 5.51E-001   -5.25E-001
  1.63E+000 4.87E-001   -4.57E-001
  1.68E+000 4.17E-001   -3.85E-001
  1.73E+000 3.40E-001   -3.11E-001
  1.76E+000 2.60E-001   -2.34E-001
  1.79E+000 1.75E-001   -1.57E-001
  1.81E+000 8.82E-002   -7.85E-002
\end{filecontents}

\begin{tikzpicture}
  \begin{axis}
    [
      xlabel={$x$},
      ylabel={$y$},
    ]
    \addplot[quiver={
        u={sin(\thisrowno{2} r + 90)},
        v={cos(\thisrowno{2} r + 90)},
        scale arrows=0.1
    }, -latex] table[x index={0},y index={1}] {data.dat};
    \addplot [thick] table {data.dat};
  \end{axis}
\end{tikzpicture}

\end{document}


Q: Datatype-generic programming libraries for Scala I'm looking for a Scala library allowing for datatype-generic programming (like Scrap Your Boilerplate, for example). A list of libraries with appropriate links and short descriptions for each one would be a perfect answer.

A: Well,

*

*Adrian Moors has reimplemented Jeremy Gibbons' Origami programming : The paper. The source.

*Bruno Oliveira and Jeremy Gibbons have re-implemented Hinze's Generics for the masses,   Lämmel & Peyton-Jones' Scrap your Boilerplate with Class, and Origami Programming, and written a detailed comparison about it.
Source here.

*Naturally, the Scala Collections library itself can easily be seen as an instance of generic programming, as Martin Odersky explains, if only because of its reliance on implicits, Scala's flavor of Type Classes.

A: Christian Hofer, Klaus Ostermann, Tillmann Rendel and Adriaan Moors's Polymorphic Embedding of DSLs has some  accompanying code which is 'very generic'.  They cite Finally Tagless, Partially Evaluated as an 'important influence', which endears this paper to me for some reason...


Q: Scrolling through selected records in attribute table I am working with data from GPS tags to determine departure/return times so am I am currently going through the attribute table for each tag and clicking each consecutive record to highlight the point on the map. Is there a way to continuously "scroll" through selected records in the attribute table? I tried with a mouse wheel and arrow keys but they just select one cell of the attribute table and it doesn't highlight the whole record so the point is not highlighted on the map.

A: You can select-scroll (scroll-select?) through records of an attribute table with Ctrl + Enter, which will also highlight the feature on the map. If you only want to scroll through a selection of features, you can create a layer from your selection first, and then scroll through that attribute table.
I was looking for this today, so I found your question and this one, which had the solution.


Q: Problems with MySQL replication. Why binlogs grows so fast? I have 2 MySQL servers:
Master server: mysql version 5.7.14
Slave server: mysql version 5.7.14 in Docker container (from official docker hub).
GTID-replication.
I have two problems:

*

*Binlogs growth very fast. I set 2 days limit rotation, but this not help - every day binlog folder increases at least twice (first day 25Gb, second 50, third 80 etc).

*Slave server "seconds behind master" increases.

Servers in local network (100 mbit/s), SSD disks, Database size near 40Gb.
I clone db for slave with Percona Xtrabackup.
Maybe configuration of servers is not correct & I need to fix something?
This is Master my.cnf file:
[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

[mysqld_safe]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
explicit_defaults_for_timestamp

max_allowed_packet = 256M

log-error       = /var/log/mysql/error.log

symbolic-links=0

!includedir /etc/mysql/conf.d/

innodb_buffer_pool_size=15000M
innodb_buffer_pool_instances=1
sql_mode = ''

slow_query_log = 1
slow_query_log_file     = '/var/log/mysql/slow.log'
long_query_time = 1
log_queries_not_using_indexes = 0

#skip-grant-tables

default_week_format = 1

skip-name-resolve
sort_buffer_size=4M
join_buffer_size=4M
innodb_sort_buffer_size=4M
tmp_table_size=5000M
max_heap_table_size=5000M

[mysqld]
server-id = 1
binlog-format = row
gtid_mode=ON
enforce-gtid-consistency=ON
log-slave-updates
log_bin = /var/log/mysql/mysql-bin.log
performance_schema_max_digest_length = 8192
max_digest_length = 8192
max_binlog_size= 1G
expire_logs_days = 2
binlog-ignore-db=check_passport
replicate-ignore-db=check_passport

sync_binlog = 1
innodb_flush_log_at_trx_commit = 1

key_buffer_size             = 16M
innodb_flush_method         = O_DIRECT
max_connections             = 200

#innodb_temp_data_file_path=ibtmp1:12M:autoextend:max:5G

This is my.cnf of slave server
[client]
port                        = 3306
socket                      = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket                      = /var/run/mysqld/mysqld.sock
nice                        = 0

[mysqld]
sql_mode                    = ""
character_set_server        = utf8
collation_server            = utf8_general_ci
user                        = mysql
pid-file                    = /var/run/mysqld/mysqld.pid
socket                      = /var/run/mysqld/mysqld.sock
port                        = 3306
basedir                     = /usr
datadir                     = /var/lib/mysql
tmpdir                      = /tmp
language                    = /usr/share/mysql/english
old_passwords               = 0
bind-address                = 127.0.0.1
skip-host-cache
skip-name-resolve

skip-external-locking

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

max_allowed_packet          = 256M
#key_buffer_size             = 16M
innodb_buffer_pool_size     = 2048M
innodb_log_file_size        = 256M
innodb_file_per_table       = 1
innodb_flush_method         = O_DIRECT
innodb_flush_log_at_trx_commit  = 1

max_connections             = 136

query_cache_size            = 0

slow_query_log              = /var/log/mysql/mysql-slow.log
long_query_time             = 1

expire_logs_days            = 2
max_binlog_size             = 1G

[mysqldump]
quick
quote-names
max_allowed_packet          = 16M

[mysqld]
server-id = 2
binlog-format = row
gtid_mode=ON
enforce-gtid-consistency=ON

relay-log = /var/log/mysql/mysql-relay-bin.log

log_bin = /var/log/mysql/mysql-bin.log

skip_slave_start

log_slave_updates = 0
read_only = ON

innodb_file_per_table = ON
#innodb_buffer_pool_size = 3G
innodb_flush_method         = O_DIRECT
innodb_flush_log_at_trx_commit  = 1

max_binlog_size = 1G

#max_relay_log_size = 1G
#relay_log_space_limit = 20G
relay_log_recovery = ON

expire_logs_days = 2

#slave-parallel-workers = 0

binlog-ignore-db=check_passport
replicate-ignore-db=check_passport

replicate-ignore-table=gfk.application_insurance
replicate-ignore-table=gfk.archive_client_building
replicate-ignore-table=gfk.comments_passwords
replicate-ignore-table=gfk.date_interval

Output of SHOW SLAVE STATUS\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.0.4
                  Master_User: slave_user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.004720
          Read_Master_Log_Pos: 518759418
               Relay_Log_File: mysql-relay-bin.000188
                Relay_Log_Pos: 213202356
        Relay_Master_Log_File: mysql-bin.004703
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB: check_passport
           Replicate_Do_Table:
       Replicate_Ignore_Table: gfk.application_insurance,gfk.date_interval,gfk.archive_client_building,gfk.comments_passwords
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 213202143
              Relay_Log_Space: 18773097825
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: Yes
           Master_SSL_CA_File: /var/lib/master_cert/ca.pem
           Master_SSL_CA_Path:
              Master_SSL_Cert: /var/lib/master_cert/client-cert.pem
            Master_SSL_Cipher:
               Master_SSL_Key: /var/lib/master_cert/client-key.pem
        Seconds_Behind_Master: 14488
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
                  Master_UUID: 8ab33cfb-bb00-11e6-84cd-fa163eb352dd
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: System lock
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set: 8ab33cfb-bb00-11e6-84cd-fa163eb352dd:62276836-70424802
            Executed_Gtid_Set: 8ab33cfb-bb00-11e6-84cd-fa163eb352dd:1-67413143
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:

A: Is it practical for the Primary to have binlog_ignore = check_passport?  If so, and if there is a lot of traffic about that db, then that would  shrink the binlogs "a lot".
Big DELETEs or UPDATEs take a lot of binlog space, hence making the binlog huge.  (Example:  updating every row of a million-row table.)  Provide specifics; the may be significant work-arounds.
How many replica threads are running on the Replica?  This impacts Seconds_behind_master.  (More threads, up to some limit, is likely to decrease "behind".)
innodb_flush_log_at_trx_commit  = 1 --> change to 2.  This sacrifices some robustness (across a crash), but improves throughput.
How much RAM in each?  I see a bigger buffer_pool in the Primary.  Usually the Replica should be the beefier machine.
100Mbs seems low; can you check to see whether it is saturated.
Fresh data daily
Here is an efficient way to replace all the data in a table:

*

*CREATE TABLE new LIKE real;

*LOAD DATA INFILE INTO new ...  -- or whatever it takes

*`RENAME TABLE real TO old, new TO REAL;

*DROP TABLE old;
Step #2 is the slowest part.
Step #3 is very fast; it is the only time that your table is not available.
No binlog-intensive UPDATE or DELETE.

A: I found solution for my case
First of all, I search what databases and tables generates so big binlogs (what tables don't have primary or unique keys):
SELECT t.table_schema,t.table_name,engine
FROM information_schema.tables t
INNER JOIN information_schema .columns c
on t.table_schema=c.table_schema
and t.table_name=c.table_name
and t.table_schema not in ('performance_schema','information_schema','mysql')
GROUP BY t.table_schema,t.table_name
HAVING sum(if(column_key in ('PRI','UNI'), 1,0)) =0;

Then:

*

*My network speed already been 1Gbit/s, there is all ok.

*I exclude from replication and logging database which recreated every day.

*I increase on slave RAM to 23Gb (as on master)

*I move binlogs on slave from SSD to HDD - it's ok - speed of HDD is enough.

*I set log_slave_updates = 1, because my replication scheme is master>slave>slave.

And this steps solve my problems! For now my binlogs not increase more than 10Gb.


Q: Fast search on encrypted data? I've got a requirement to encrypt Personally identifiable information (PII) data in an application DB. The application uses  smart searches in the system that use sound like, name roots and part words searches to find name and address quickly.
If we put in encryption on those fields (the PII data encrypted at the application tier), the searches will be impacted by the volume of records because we cant rely on SQL in the normal way and the search engine (in the application) would switch to reading all values, decrypt them and do the searches.
Is there any easy way of solving this so we can always encrypt the PII data and also give our user base the fast search functionality?
We are using a PHP Web/App Tier (Zend Server and a SQL Server DB). The application does not currently use technology like Lucene etc.
Thanks
Cheers

A: Encrypting the data also makes it look a great deal like randomized bit strings. This precludes any operations the shortcut searching via an index.
For some encrypted data, e.g. Social security number, you can store a hash of the number in a separate column, then index this hash field and search for the hash. This has limited utility obviously, and is of no value in searches name like 'ROB%'
If your database is secured properly may sound nice, but it is very difficult to achieve if the bad guys can break in and steal your servers or backups. And if it is truly as requirement (not just a negotiable marketing driven item), you are forced to comply.
You may be able to negotiate storing partial data in unencrypted, e.g., first 3 character of last name or such like so that you can still have useful (if not perfect) indexing.
ADDED
I should have added that you might be allowed to hash part of a name field, and search on that hash -- assuming you are not allowed to store partial name unencrypted -- you lose usefulness again, but it may still be better than no index at all.
For this hashing to be useful, it cannot be seeded -- i.e., all records must hash based on the same seed (or no seed), or you will be stuck performing a table scan.
You could also create a covering index, still encrypted of course, but a table scan could be considerable quicker due to the reduced I/O & memory required.

A: I'll try to write about this simply because often the crypto community can be tough to understand (I resisted the urge to insert a pun here).
A specific solution I have used which works nicely for names is to create index tables for things you wish to index and search quickly like last names, and then encrypt these index column(s) only.
For example, you could create a table where the key column contains one entry for every possible combination of characters A-Z in a 3-letter string (and include spaces for all but the first character). Like this:
A__
AA_
AAA
AAB
AAC
AAD
..
..
..
ZZY
ZZZ

Then when you add a person to your database, you add their index to a second column which is just a list of person ID's.
Example: In your patients table, you would have an entry for smith like this:
231    Smith    John    A     1/1/2016   .... etc

and this entry would be encrypted, perhaps all columns but the ID 231. You would then add this person to the index table:
SMH    [342, 2342, 562, 12]
SMI    [123, 175, 11, 231]

Now you encrypt this second column (the list of ID's). So when you search for a last name, you can type in 'smi' and quickly retrieve all of the last names that start with this letter combination. If you don't have the key, you will just see a cyphertext. You can actually create two columns in such a table, one for first name and one for last name.
This method is just as quick as a plaintext index and uses some of the same underlying principles. You can do the same thing with a soundex ('sounds like') by constructing a table with all possible soundex patterns as your left column, and person (patient?) Id's as another column. By creating multiple such indices you can develop a nice way to hone in on the name you are looking for.
You can also extend to more characters if you like but obviously this lengthens your table by more than an order of magnitude for each letter. It does have the advantage of making your index more specific (not always what you want). Truthfully any type of histogram where you can bin the persons using their names will work. I have seen this done with date of birth as well. anything you need to search on.
A table like this suffers from some vulnerabilities, particularly that because the number of entries for certain buckets may be very short, it would be possible for an attacker to determine which names have no entries in the system. However, using a sort of random 'salt' in your index list can help with this. Other problems include the need to constantly update all of your indices every time values get updated.
But even so, this method creates a nicely encrypted system that goes beyond data-at-rest. Data-at-rest only protects you from attackers who cannot gain authorization to your systems, but this system provides a layer of protection against DBA's and other personnel who may need to work in the database but do not need (or want) to see the personal data contained within. They will just see ciphertext. So, an additional key is needed by the users or systems that actually need/want to access this information. Ashley Madison would have been wise to employ such a tactic.
Hope this helps.

A: Sometimes, "encrypt the data" really means "encrypt the data at rest". Which is to say that you can use Transparent Data Encryption to protect your database files, backups, and the like but the data is plainly viewable through querying. Find out if this would be sufficient to meet whatever regulations you're trying to satisfy and that will make your job a whole lot easier.


Q: Connect to postgres database on local linux install I'm trying to figure out how to connect via my ruby app using PGConn in order to connect to my postgres database on the aws ec2 linux server.
db_connection = PGconn.connect("ip-172-31-90.9.us-west-2.compute.internal", 5432, '', '', "testdb", "username", "password")

I keep getting an error
app.rb:21:in `initialize': could not translate host name "ip-172-31-90-9.us-west-2.compute.internal." to address: nodename nor servname provided, or not known (PG::ConnectionBad)

I ran /sbin/ifconfig -a on the linux server to get the IP address, but it still can't connect.  I also edited the files per the instructions from the site http://www.cyberciti.biz/tips/postgres-allow-remote-access-tcp-connection.html

A: IP of "ip-172-31-90-9" seems private IP address.
So what you need do:

*

*assign public IP or Elastic IP to that ec2 instance.

*set inbound rule in its security group and open the port 5432 to 0.0.0.0/0 or any IP ranges in your case

*test the port from your local
telnet NEW_Public_IP 5432
If can, then you should be fine to connect the database.


Q: Proof that equality of derivative of section is coordinate independent Lemma 4.1.1 in D.J Saunders 's book (The geometry of jet bundles) says:
Let $(E,\pi,M)$ be a bundle, and let $p$ $\in M$. Suppose that
$\phi$ and $\psi$ are section that satisfy $\phi(p)=\psi(p)$. Let $(x^i,u^\alpha)$ and $(y^i,v^\beta)$ be two adapted
coordinate systems around $\phi(p)$, and suppose also that $$\frac{\partial(
 u^\alpha \circ \phi)}{\partial x^i}\bigg|_{p}=\frac{\partial(
 u^\alpha \circ \psi)}{\partial x^i}\bigg|_{p}$$
for $1 \leq i\leq m$ and $1 \leq \alpha \leq n$ then
$$\frac{\partial(
 v^\beta \circ \phi)}{\partial y^i}\bigg|_{p}=\frac{\partial(
 v^\beta \circ \psi)}{\partial y^i}\bigg|_{p}$$
for $1 \leq j\leq m$ and $1 \leq \beta \leq n$
To proof this he uses the relation
$$\frac{\partial(
 v^\beta \circ \phi)}{\partial y^j}\bigg|_{p}=\frac{\partial(
 v^\beta \circ \phi)}{\partial x^i}\bigg|_{p} \frac{\partial
 x^i }{\partial y^j}\bigg|_{p}=\left (\frac{\partial
 v^\beta }{\partial x^i}\bigg|_{\phi(p)}+\frac{\partial
 v^\beta }{\partial u^{\alpha}}\bigg|_{\phi(p)} \frac{\partial(
 u^\alpha \circ \phi)}{\partial x^i}\bigg|_{p} \right)\frac{\partial
 x^i }{\partial y^j}\bigg|_{p} \tag 1$$
What I am not seeing is why from $(1)$ we obtain
$$\frac{\partial(
 v^\beta \circ \phi)}{\partial y^i}\bigg|_{p}=\frac{\partial(
 v^\beta \circ \psi)}{\partial y^i}\bigg|_{p}$$
for $1 \leq j\leq m$ and $1 \leq \beta \leq n$


Q: Fql returning array.. but i need an object I'm using this code to get list of friends.
    $params = array(
    'method' => 'fql.query',
    'query' => "SELECT uid FROM user WHERE uid = me()
    OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())",
);

$result = $facebook->api($params);

now i'm displaying the picture of user as
 echo "";

but it is still returning the result as an array like this:
http://graph.facebook.com/array/picture
I need the uid at that place where it is showing array. Help please. its really important
print_r ($result[0]); gives the following output----
 Array ( [uid] => XXXXXXXX )

A: This is 2-D array no need to convert it into object you can still access it
To access uid you have to do something like this
echo $result[0]['uid'];

Hence you code will become
echo "";

If you still want object instead of array you can do type cast.
$result_obj= (object) $result[0];
echo $result_obj->uid;


Q: Negating expression in bash double bracket How can I negate the expression as the following matches a numeric check.
  elif [[ $pn =~ ^[[:digit:]]+$ ]]; then
    pfm -w "pn failed numeric inspection"

A: You may negate the test using
[[ ! $pn =~ ^[[:digit:]]+$ ]]

or, in this case,
[ -z "$pn" ] || [[ $pn =~ [^[:digit:]] ]]

i.e., "is $pn empty or does it contain a non-digit?"
Or, with a globbing test,
[ -z "$pn" ] || [[ $pn == *[![:digit:]]* ]]

or, using an extended globbing pattern,
[[ $pn != +([[:digit:]]) ]]


Q: How to get text inside tag using python and BeautifulSoup I'm trying to get text (example text) inside tags using beautiful soup
The html structure looks like this:
...

Description

example text

...

What i tried:
r = requests.get(url)
soup = bs(r.content, 'html.parser')
desc = soup.find('div.div.span.div.span')
print(str(desc))

A: You cannot use .find() with multiple tag names in it stacked like this. You need to repeatedly call .find() to get desired result. Check out docs for more information. Below code will give you desired output:
soup.find('div').find('span').get_text()

A: r = requests.get(url)
soup = bs(r.content, 'html.parser')
desc = soup.find('div').find('span')
print(desc.getText())

A: Your selector is wrong.
>>> from bs4 import BeautifulSoup
>>> data = '''\
...

...
Description

...
...
example text

...
...
'''
>>> soup = BeautifulSoup(data, 'html.parser')
>>> desc = soup.select_one('div span div span')
>>> desc.text
'example text'
>>>

A: Check this out -
soup = BeautifulSoup('''

Description

example text

''',"html.parser")

text = soup.span.get_text()
print(text)


Q: Red Hat Directory Server and 389 Directory Server, differences Red Hat Directory Server and 389 Directory Server are the same product? Or what is the difference between them?

A: The 389 Directory Server is absolutely identical to the Red Hat Directory Server. It's the same product.
It's just rebranded with Red Hat logos.


Q: Too many internal channel errors while using Channel API We use Channel API in our Google App Engine application to send updates to our users. The code to send updates is something like this
for(String clientID: listOfClientID)
    channelService.sendMessage(new ChannelMessage(clientID, stringMessage));

Over the past few weeks, we've been getting too many exceptions in this method. We get around around 150 exceptions for a 8-hour peak usage period.
com.google.appengine.api.channel.ChannelFailureException: An internal channel error occured.

The loop can have 500-3000 iterations. Is it a problem when ChannelService tries to send a message to a channel that has been closed? If I remove closed channels from the list, will it completely solve the problem? Please note that this large number of exceptions have been a trend only in the past few weeks and we've been using Channel API for several months.

A: Turns out that the problem was the server trying to send messages to channels that have expired. The error rate has gone down considerably when I made sure that doesn't happen anymore.


Q: How to call Java method which returns String from C using JNI? Is there a way to call a java method, which returns a String in C?
For Integer it works like that:
JNIEXPORT jint JNICALL Java_Client_getAgeC(JNIEnv *env, jobject callingObject, jobject employeeObject) {
jclass employeeClass = (*env)->GetObjectClass(env, employeeObject);
jmethodID midGetAge = (*env)->GetMethodID(env, employeeClass, "getAge", "()I");
int age =  (*env)->CallIntMethod(env, employeeObject, midGetAge);
return age;
}

I've searched for a long time but nothing works for String.
Finally, I want to get a char*
Thanks in advance!

A: Below is an example of JNI code calling a method returning a string. Hope this helps.
int EXT_REF Java_JNITest_CallJava(
    JNIEnv* i_pjenv,
    jobject i_jobject
)
{
    jclass      jcSystem;
    jmethodID   jmidGetProperty;
    LPWSTR      wszPropName = L"java.version";

    jcSystem = i_pjenv->FindClass("java/lang/System");
    if(NULL == jcSystem)
    {
        return -1;
    }
    jmidGetProperty = i_pjenv->GetStaticMethodID(jcSystem,
                      "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    if(NULL == jmidGetProperty)
    {
        return -1;
    }

    jstring joStringPropName = i_pjenv->NewString((const jchar*)wszPropName, wcslen(wszPropName));
    jstring joStringPropVal  = (jstring)i_pjenv->CallStaticObjectMethod(jcSystem,
                               jmidGetProperty, (jstring)joStringPropName);
    const jchar* jcVal = i_pjenv->GetStringChars(joStringPropVal, JNI_FALSE);
    printf("%ws = %ws\n", wszPropName, jcVal);
    i_pjenv->ReleaseStringChars(joStringPropVal, jcVal);
    return 0;
}