text:
Q: Webview is blank without any error in Android 6.0, working fine in lower version. 1.In Android 6.0 it is not working.  Whenever i open the webview, it is blank without any error.  Webview is working fine in lower version.
 2. Inside LinearLayout i added the webview.
 3. Here i will share my part of the code.
 4.Normally with static lat , long it loading. Whenever i try to get current location , problem occurs.
In assets:
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
    x.innerHTML = "Geolocation is not supported by this browser.";
}

In onCreate:
if (Build.VERSION.SDK_INT >= 23) {
                // Marshmallow+ Permission APIs
                fuckMarshMallow();
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
                    WebView.setWebContentsDebuggingEnabled(true);
                }
            }
            webview.addJavascriptInterface(new MyJS(this), "Android");
            webview.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
            webview.getSettings().setSavePassword(true);
            webview.getSettings().setSaveFormData(true);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setSupportZoom(false);

           webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            webview.getSettings().setGeolocationEnabled(true);
            webview.setInitialScale(1);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            webview.setScrollbarFadingEnabled(false);
            webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            webview.getSettings().setBuiltInZoomControls(true);
            webview.setWebViewClient(new Materialformfilling.GeoWebViewClient());
            // Below required for geolocation
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setGeolocationEnabled(true);
            webview.setWebChromeClient(new Materialformfilling.GeoWebChromeClient());

            webview.getSettings().setAppCacheEnabled(true);
            webview.getSettings().setDatabaseEnabled(true);
            webview.getSettings().setDomStorageEnabled(true);
            String url = "file:///android_asset/index.html";
            webview.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int progress) {
                    // Activities and WebViews measure progress with different scales.
                    // The progress meter will automatically disappear when we reach 100%
                    Materialformfilling.this.setProgress(progress * 100);
                }

                @Override
                public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                    callback.invoke(origin, true, false);
                }
            });
           webview.loadUrl(url);

      public class GeoWebChromeClient extends android.webkit.WebChromeClient {
            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                                                           final GeolocationPermissions.Callback callback) {
                // Always grant permission since the app itself requires location
                // permission and the user has therefore already granted it
                callback.invoke(origin, true, false);
            }
        }

        /**
         * WebViewClient subclass loads all hyperlinks in the existing WebView
         */
        public class GeoWebViewClient extends WebViewClient {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // When user clicks a hyperlink, load in the existing WebView
                view.loadUrl(url);
                return true;
            }

            Dialog loadingDialog = new Dialog(Materialformfilling.this);

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                webViewPreviousState = PAGE_STARTED;

                if (loadingDialog == null || !loadingDialog.isShowing())
                    loadingDialog = ProgressDialog.show(Materialformfilling.this, "",
                            "Loading Please Wait", true, true,
                            new DialogInterface.OnCancelListener() {

                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    // do something

                                }
                            });

                loadingDialog.setCancelable(false);
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request,
                                        WebResourceError error) {

                if (isConnected()) {
                    final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE);
                    snackBar.setAction("Reload", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            webview.loadUrl("file:///android_asset/index.html");
                        }
                    });
                    snackBar.show();
                } else {
                    final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
                    snackBar.setAction("Enable Data", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
                            webview.loadUrl("file:///android_asset/index.html");
                            snackBar.dismiss();
                        }
                    });
                    snackBar.show();
                }

                super.onReceivedError(view, request, error);

            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view,
                                            WebResourceRequest request, WebResourceResponse errorResponse) {

                if (isConnected()) {
                    final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase() + +errorResponse.getStatusCode(), Snackbar.LENGTH_INDEFINITE);

                    snackBar.setAction("Reload", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            webview.loadUrl("file:///android_asset/index.html");
                        }
                    });
                    snackBar.show();
                } else {
                    final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
                    snackBar.setAction("Enable Data", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
                            webview.loadUrl("file:///android_asset/index.html");
                            snackBar.dismiss();
                        }
                    });
                    snackBar.show();
                }
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                if (webViewPreviousState == PAGE_STARTED) {

                    if (null != loadingDialog) {
                        loadingDialog.dismiss();
                        loadingDialog = null;
                        Constant.print("check 1111111111111111");
                    }
                }
            }
        }

        /**
         * Check if there is any connectivity
         *
         * @return is Device Connected
         */
        public boolean isConnected() {

            ConnectivityManager cm = (ConnectivityManager)
                    this.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (null != cm) {
                NetworkInfo info = cm.getActiveNetworkInfo();
                return (info != null && info.isConnected());
            }

            return false;

        }

        @TargetApi(Build.VERSION_CODES.M)
        private void fuckMarshMallow() {
            List<String> permissionsNeeded = new ArrayList<String>();

            final List<String> permissionsList = new ArrayList<String>();
            if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
                permissionsNeeded.add("Show Location");
            if (permissionsList.size() > 0) {
                if (permissionsNeeded.size() > 0) {

                    // Need Rationale
                    String message = "App need access to " + permissionsNeeded.get(0);

                    for (int i = 1; i < permissionsNeeded.size(); i++)
                        message = message + ", " + permissionsNeeded.get(i);

                    showMessageOKCancel(message,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                                }
                            });
                    return;
                }
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                return;
            }
            Toast.makeText(Materialformfilling.this, "No new Permission Required- Launching App .You are Awesome!!", Toast.LENGTH_SHORT)
                    .show();
        }

        private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
            new AlertDialog.Builder(Materialformfilling.this)
                    .setMessage(message)
                    .setPositiveButton("OK", okListener)
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        }

        @TargetApi(Build.VERSION_CODES.M)
        private boolean addPermission(List<String> permissionsList, String permission) {

            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
                // Check for Rationale Option
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
            return true;
        }

Please help me


text:
Q: Volley error-UnsupportedOperationException when making json request When I use Volley Library on
Android 5.1 all works fine.  But
when I run on 6.0 I got unsupported operation exception.
What can be the reason?
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,

        url, null,

        new Response.Listener<JSONObject>() {

        @Override

        public void onResponse(JSONObject response) {

        Log.e(TAG, response.toString());

        try {

        String apiNum = response.getString("apiNum");

        switch (apiNum){

        case "1":

        Log.e(TAG, "CASE 1");

        break;

        case "2":

        Log.e(TAG, "CASE 2");

        prefs.edit().putString("id", id.getText().toString())

        .putString("secret", password.getText().toString()).commit();

        listener.onRegister("success");

        break;

        case "-1":

        Log.e(TAG, "CASE -1");

        listener.onRegister("not_exists");

        break;

        default:

        listener.onRegister("error");

        Log.e(TAG, "DEFAULT");

        break;

        }

        } catch (JSONException e) {

        showAlert(getActivity(),

        "JSONException,"+"MEggase="+e.getMessage()+"Cause:"+e.getCause());

        e.printStackTrace();

        }

        pDialog.hide();

        }

        }, new Response.ErrorListener() {

        @Override

        public void onErrorResponse(VolleyError error) {

        Log.e(TAG, "Error: " + error.getMessage());

        showAlert(getActivity(), "VolleyError,

        "+"MEggase="+error.getMessage()+"Cause:"+error.getCause());

        pDialog.hide();

        }

        } );

        // Adding request to request queue

        try{

            AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_arry);

        } catch (Exception e){

            showAlert(getActivity(), "AddToRequestQueue Error");

        }

A: Solved
The problem was in permissions. When I've added request for permissions app become to work without errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook login callback hash documentation I'm using Omniauth with Devise to authenticate users via Facebook for a web app I'm writing using Rails 3.0.4
I modeled it after Ryan Bates' Railscasts:
http://railscasts.com/episodes/235-omniauth-part-1
http://railscasts.com/episodes/236-omniauth-part-2
At this point, I can log into my site with my Facebook account and pull my email out of the callback hash, which looks like this for me:
request.env["omniauth.auth"]

{"user_info"=>
  {"name"=>"Eric Hu",
   "urls"=>
    {"Facebook"=>"http://www.facebook.com/...", "Website"=>nil},
   "nickname"=>"...",
   "last_name"=>"Hu",
   "first_name"=>"Eric"},
 "uid"=>"...",
 "credentials"=>
  {"token"=> "..."},
 "extra"=>
  {"user_hash"=>
    {"name"=>"Eric Hu",
     "timezone"=>-8,
     "gender"=>"male",
     "id"=>"...",
     "last_name"=>"Hu",
     "updated_time"=>"2011-02-21T17:46:19+0000",
     "verified"=>true,
     "locale"=>"en_US",
     "link"=>"http://www.facebook.com/...",
     "email"=>"...",
     "first_name"=>"Eric"}},
 "provider"=>"facebook"}

(replaced some fields with "..." for my own privacy)

Right now, I use this field to get the user's email address
 request.env["omniauth.auth"]["user_info"]["extra"]["email"]

I don't know if the callback hash varies with the user's settings--I've actually restricted my email display settings on Facebook and it still shows up.  To make sure my code handles any possible variations with this hash, I'd like to find some reference on how this Facebook login callback hash looks and how it can vary.  So far I haven't found anything on SO or the Facebook developer documentation.
The question: is there an official reference for the Facebook login callback hash?  I don't want to assume that all the same hash elements are there for all users.  I included as much info as I could here for other people who want to authenticate their rails apps using Facebook and Omniauth.

A: Take a look at the Facebook permissions reference, this is a list of the permissions that you can request from the user.  This allows you to request specific things and if the user grants permission then you can guarantee that the field is present.  I would also recommend you read through their authentication docs so you understand the users experience.
Once you know what permissions you want you can update your devise config (config/initializers/devise.rb) so that devise is requesting the permissions you need:
config.omniauth :facebook, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, {:scope => 'offline_access,email,user_birthday'}


text:
Q: Plan already exists - stripe/php I would like to conclude a monthly plan created by myself with the customer's ID and complete the fixed amount payment.
However, when creating a "Subscription" after creating the original plan, "Plan already exists" is output.
I can not truly understand the above error. For example, if I create and run "Subscription" without creating original plan, the code will work correctly.
The log at that time is below. However, with this, it is impossible to judge what kind of plan contents are adapted to customers. How can you associate your plan with "Subscription"?
Implement Subscription without creating a plan
// echo $customer->id;
// $my_original_plan =  \Stripe\Plan::create(array(
// "id"  => "basic-monthly",
// "interval"  =>  "month",
// "currency"  => "jpy",
// "product" => array("name" => "aaaaaa"),
// "amount"  => 9800
// ));
// echo $my_original_plan;

$subscription =  \Stripe\Subscription::create(array(
"customer" => "$customer->id",
"items" => array(
  array(
    "plan" => "basic-monthly",
  ),
)
));

echo $subscription;

The above log
Stripe\Subscription JSON: {
    "id": "sub_CXKozer939U80A",
    "object": "subscription",
    "application_fee_percent": null,
    "billing": "charge_automatically",
    "billing_cycle_anchor": 1521674075,
    "cancel_at_period_end": false,
    "canceled_at": null,
    "created": 1521674075,
    "current_period_end": 1524352475,
    "current_period_start": 1521674075,
    "customer": "cus_CXKovj687dz1Po",
    "days_until_due": null,
    "discount": null,
    "ended_at": null,
    "items": {
        "object": "list",
        "data": [
            {
                "id": "si_CXKoBTbLbBICEL",
                "object": "subscription_item",
                "created": 1521674075,
                "metadata": [],
                "plan": {
...

Plan already exists
// echo $customer->id;

$my_original_plan =  \Stripe\Plan::create(array(
"id"  => "basic-monthly",
"interval"  =>  "month",
"currency"  => "jpy",
"product" => array("name" => "aaaaaa"),
"amount"  => 9800
));

// echo $my_original_plan;

$subscription =  \Stripe\Subscription::create(array(
"customer" => "$customer->id",
"items" => array(
array(
"plan" => "basic-monthly",
),
)
));

echo $subscription;

All source code
<?php

header("Content-type: text/plain; charset=UTF-8");

if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
if (isset($_POST['request']))
{

//make token from ajax js
$token_from_js = $_POST['request'];

//stripe from composer
require_once 'vendor/autoload.php';

//set api key
\Stripe\Stripe::setApiKey("sk_test_");

//make customer info
$customer =  \Stripe\Customer::create(array(
"description" => "taylor@example.com",
"source" => "$token_from_js",
));

// echo $customer->id;

$my_original_plan =  \Stripe\Plan::create(array(
"id"  => "basic-monthly",
"interval"  =>  "month",
"currency"  => "jpy",
"product" => array("name" => "aaaaaa"),
"amount"  => 9800
));

// echo $my_original_plan;

$subscription =  \Stripe\Subscription::create(array(
"customer" => "$customer->id",
"items" => array(
array(
"plan" => "basic-monthly",
),
)
));

echo $subscription;
};
};

?>

A: \Stripe\Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

$product = \Stripe\Product::create([
    'name' => 'My SaaS Platform',
    'type' => 'service',
]);

$plan = \Stripe\Plan::create([
    'currency' => 'usd',
    'interval' => 'month',
    'product' => $product->id,
    'nickname' => 'Pro Plan',
    'amount' => 3000,
]);

You should try to use product_id instead of an array.


text:
Q: Does a "gesundheit" for coughing exist? To wish someone good health (or just to be polite) after they sneeze we say "gesundheit".
Is there any word or phrase to say after someone coughs?

A: There is no word or phrase that is commonly said after someone coughs.


text:
Q: Python unexpected EOF in for loop [repl.it]
Note: This question is about a problem with repl.it, not a general problem.

Note: You might consider this as a duplicate, but in fact it isn't.
  These do not suit my problem:

*

*Python unexpected EOF while parsing : syntax error

*Python unexpected EOF while parsing

*Unexpected EOF while parsing in python

*Python unexpected EOF while parsing (python2.7)
(Taken from alerady answered questions list, duplicates excluded for compactness)

I've got a problem with for loops in Python (repl.it Python 2 and Python 3 interpreters) in that one-line for loops without a trailing newline raise SyntaxError.
for i in (1,2,3,4,): print i+i+i

Traceback (most recent call last):
  File "python", line 1
    for i in (1,2,3,4,): print i+i+i
                                   ^
SyntaxError: unexpected EOF while parsing
for i in (1,2,3,4,): print i+i+i
# Trailing newline

3
6
9
12
Another question: How to display a trailing newline , trailing space or unprintable character in SE (without using <pre>)?

A: It doesn't seem to be a Python problem.
I tried your exact script without a newline on python 2.7 on OS X. It runs successfully. I also tried it on Python 3.5, after adding parens around the argument to print. Still no error.
Looks like a bug specific to repl.it.


text:
Q: How can I include FirstOrDefault child of parent in Entity Framework linq ".Include" I want to select Evaluation with all his Component and only the first Answers of each component.
QueryFutureEnumerable<Evaluation> deferredEvaluations = db.Evaluations
    .Include(e => e.Components)
    .Include(e => e.Components.Select(c => c.Answers).FirstOrDefault())
    .Where(e => e.Deprecated == false)
    .OrderByDescending(e => e.LastModified)
    .Future();

I need help figuring how to Include only first Answer child.
Here is what I already tried which does not works:
 .Include(e => e.Components.Select(c => new List<Answer>(){ c.Answers.FirstOrDefault()} ))
 .Include(e => e.Components.Select(c => new { Answer = c.Answers.FirstOrDefault()}))
 .Include(e => e.Components.Select(c => c.Answers.Take(1)))

Note: I'm using Z.EntityFramework.Plus; but I don't think the part of the query that I want to accomplish has anything to do with that.
When it's not workin, "I get the error: The Include path expression must refer to a navigation property defined on the type..."


text:
Q: Arraylist is adding objects twice I have a strange problem with arraylist. I add objects to arraylist in for loop, everything is working fine except arraylist add method. It seems like my list is adding each object twice but I can't find a reason of this.
Here is my code
private void generateCitizens()
{
    int counter = Constants.CITIZENS_NUMBER;
    Random r = new Random(Calendar.getInstance().getTimeInMillis());
    while(counter > 0)
    {
        int x = r.nextInt(Constants.TILES_IN_WIDTH) + 1;
        int y = r.nextInt(Constants.TILES_IN_HEIGHT) + 1;

        if(map.collisionTable[y][x] == 2)
        {
            Citizen c = new Citizen(x, y, citizenTexture.deepCopy(), map);
            citizensList.add(c);
            Log.i("Citizens count", String.valueOf(citizensList.size()));
            scene.attachChild(c);
            counter--;
        }
    }

    for(int i = 0; i<citizensList.size(); i++)
    {
        Log.i("Citizen - ", citizensList.get(i).toString());
    }
}

Constants.CITIZENS_NUMBER is 15 in this case and this is what I got in logs

05-10 15:13:36.801: I/Citizens count(3237): 2
  05-10 15:13:36.801: I/Citizens count(3237): 4
  05-10 15:13:36.801: I/Citizens count(3237): 6
  05-10 15:13:36.801: I/Citizens count(3237): 8
  05-10 15:13:36.801: I/Citizens count(3237): 10
  05-10 15:13:36.811: I/Citizens count(3237): 12
  05-10 15:13:36.811: I/Citizens count(3237): 14
  05-10 15:13:36.811: I/Citizens count(3237): 16
  05-10 15:13:36.811: I/Citizens count(3237): 18
  05-10 15:13:36.821: I/Citizens count(3237): 20
  05-10 15:13:36.821: I/Citizens count(3237): 22
  05-10 15:13:36.821: I/Citizens count(3237): 24
  05-10 15:13:36.821: I/Citizens count(3237): 26
  05-10 15:13:36.831: I/Citizens count(3237): 28
  05-10 15:13:36.831: I/Citizens count(3237): 30
  05-10 15:13:36.831: I/Citizen -(3237): com.lpp.towndefence.Citizen@40535d40
  05-10 15:13:36.831: I/Citizen -(3237): com.lpp.towndefence.Citizen@40535d40
  05-10 15:13:36.831: I/Citizen -(3237): com.lpp.towndefence.Citizen@40537318
  05-10 15:13:36.831: I/Citizen -(3237): com.lpp.towndefence.Citizen@40537318
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@40514688
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@40514688
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@40799fe8
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@40799fe8
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079c308
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079c308
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079abd8
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079abd8
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079b4a0
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@4079b4a0
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba160
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba160
  05-10 15:13:36.841: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba230
  05-10 15:13:36.851: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba230
  05-10 15:13:36.851: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba300
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba300
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba3d0
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba3d0
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba4a0
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407ba4a0
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bac18
  05-10 15:13:36.861: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bac18
  05-10 15:13:36.871: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bb3f0
  05-10 15:13:36.871: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bb3f0
  05-10 15:13:36.871: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bbc80
  05-10 15:13:36.871: I/Citizen -(3237): com.lpp.towndefence.Citizen@407bbc80

A: Did you subclass the List class ?
May new Citizen add itself to the list ? Or the attachChild method on scene ?


text:
Q: Divergence in meaning of "just about" between UK and North American English Does anyone know anything about how the meaning of "just about" came to have opposite meanings in the UK and North America.
For example, in the UK, The team just about won. means that the team won, but it was close (ie The team barely won.). However, in North America, it means that the team almost won.

A: I am Scottish and we always use "just about" to mean "nearly, but not quite".
E.g. "I just about passed my exam" means "I got close to the pass mark, but didn't quite make it."
A straw poll of some of my friends indicates that Australians, New Zealanders, the Irish (both Northern Ireland and the Republic of Ireland) and those from North America (Canada and that USA) also share the same meaning as we Scots. Amongst my English and Welsh friends, I have found that only those from the north of England (Northumberland and Cumbria) share our meaning.
An interesting fact  I've noticed that is that everyone says "just about to", to mean "nearly, but not quite", e.g. "I was just about to leave when the telephone rang", meaning "I had not left, but was about to, when the telephone rang".

A: When I was young, a long time ago (!), I was only aware of just about to mean very nearly, as in Just about everyone was there (a few people were missing) and I just about died when I heard the news. (I didn't actually die!)
About 20 years ago, I noticed that some sports journalists were using just about to mean only just as in The goalkeeper just about kept the ball out. (Meaning he saved the ball!).  Interestingly, I recently noticed a football commentator use just about with one meaning in one sentence and then two minutes later used it with the other and completely different meaning. I have now noticed it being used by people other than sports commentators. This wouldn't be the first time that words have come to take on another often contradictory meaning. Like all evolutionary change, what starts off as a mistake, sometimes gets accepted and repeated, but it annoys me so much, I'll resist its lure.

A: British football announcers often use "just about" to mean that the objective was accomplished but by the smallest of margins whereas in the US, that phrase would imply that the objective was not accomplished narrowly. So if a Brit said, the defender just about arrived in time to block the shot, he did block it but barely.  In the US that would mean that he nearly got back in time but didn't block it. I see from the comment above that I'm not the first to notice this.  Maybe it's a British sport announcer thing.

A: On the Separated by a Common Language blog (Observations on British and American English by an American linguist in the UK) we can read the following explanation:

The translation problem in just about isn't just about just. Let's think about about. The (UK) Collins English Dictionary gives us this sense-definition, which is not to be found in the American Heritage Dictionary or Merriam-Webster:

about
13. used in informal phrases to indicate understatement : I've had just about enough of your insults it's about time you stopped

Aha, the famous British understatement. Rather than saying I've had enough, you put an about in to soften the blow. And then a just to soften it more.

For more details, see the site I mentioned, which seems quite well done.


text:
Q: How to cast a type when referencing the assembly Given
An extension method to convert a type via casting.
    public static dynamic SwitchType(this dynamic ppo,
        string classname, Action<dynamic> callback)
    {
        Type obj= Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(p => p.Name == classname)
            .First();
        var converted =(obj)ppo; <-- Error Here
        callback(converted);
    }

Problem
Compiler tells me it cannot find obj, so cast won't work.
Maybe I'm making this too complicated, but the ppo being passed in is a runtime object that I want to convert to a specific type of that same runtime object that  was created earlier and contains specific static field text I need.
I've already validated the return of obj in other code so that part is working.
Further Information
We are parsing approximately 11 different tables in a web page all using the same class name. I want to write all the assertions in one place one time for all 11 rows.  Each row has different content in it thus I have to have the instance of the saved class from when we created it, but all I have at runtime is the class name.  Each time we call TestEditorFields we have a different page object with the same structure just different property values.
 private void TestEditorFields(dynamic ppo)
        {
            Assert.IsTrue(ppo.ActualHeaderText == ppo.ExpectedHeaderText, "UTSC1160-The actual header text was not as expected");
            Assert.IsTrue(ppo.ActualInputText == ppo.ExpectedInputText, "UTSC1170-The actual inputs text was not as expected");
            Assert.IsTrue(ppo.ActualLabelText == ppo.ExpectedLabelText, "UTSC1180-The actual labels text was not as expected");
            Assert.IsTrue(ppo.ActualRowHTML == ppo.ExpectedRowHTML, "UTSC1190-The HTML of the content rows was not as expected");
            Assert.IsTrue(ppo.ActualSelectedText == ppo.ExpectedSelectedText, "UTSC1200-The Selected Options are not as expected");
            Assert.IsTrue(ppo.ActualWarningText == ppo.ExpectedWarningText, "UTSC1210-The actual warning text is not as expected");
        }

A: It seems like one of most powerful features of .NET is missed in a lot of questions: expression trees.
With expression trees you can generate an expression which can get compiled into a delegate to perform the desired conversion (bye bye reflection).
For example:
var paramExpr = Expression.Parameter(typeof(object));
var convertExpr = Expression.Convert(paramExpr, obj);
var lambdaExpr = Expression.Lambda(convertExpr, paramExpr);
var compiledExprDelegate = lambdaExpr.Compile();

Now you can call the delegate using Delegate.DynamicInvoke:
object conversionResult = compiledExprDelegate.DynamicInvoke(ppo);

Since you're working with DLR using dynamic, the above code should work in your scenario...

A: You can't cast an object instance to a Type that you don't know at compile time.
You need A base class or interface that the target type implement.
Or find a specific method by reflection on this object.
MethodInfo methodInfo = type.GetMethod(methodName);
methodInfo.Invoke(methodInfo, parametersArray);


text:
Q: How do I use a directive to toggle a slide animation on an element from my controller? I am confused on the following scenario.  Let's say I have a table with rows.  When a user clicks a button in the table I want a user form to slide down with jQuery and display the form with the selected row values.  Here is what I am currently doing that doesn't quite make sense:
View

...
<form>
   <input type="test" ng-model={{itemToEdit.Property1}} >
   <button ng-click=saveEditedItem(item)" slide-up-form>
<form>

Control
$scope.itemToEdit = {};

$scope.setItemToEdit = function(item) {
    $scope.itemToEdit = item;
});

$scope.saveEditedItem = function(item) {
   myService.add(item);
   $scope.itemToEdit = {};
}

Directive - Slide-Up / Slide-Down
var linker = function(scope, element, attrs) {
    $(form).slideUp(); //or slide down
}

It seems the my directive and my control logic are too disconnected.  For example, what happens if there is a save error?  The form is already hidden because the slideUp event is complete.  I'd most likely want to prevent the slideUp operation in that case.
I've only used AngularJS for about a week so I'm sure there is something I'm missing.

A: Sure, it's a common problem... here's one way to solve this: Basically use a boolean with a $watch in a directive to trigger the toggling of your form. Outside of that you'd just set a variable on your form to the object you want to edit.
Here's the general idea in some psuedo-code:
//create a directive to toggle an element with a slide effect.
app.directive('showSlide', function() {
   return {
     //restrict it's use to attribute only.
     restrict: 'A',

     //set up the directive.
     link: function(scope, elem, attr) {

        //get the field to watch from the directive attribute.
        var watchField = attr.showSlide;

        //set up the watch to toggle the element.
        scope.$watch(attr.showSlide, function(v) {
           if(v && !elem.is(':visible')) {
              elem.slideDown();
           }else {
              elem.slideUp();
           }
        });
     }
   }
});

app.controller('MainCtrl', function($scope) {
   $scope.showForm = false;
   $scope.itemToEdit = null;

   $scope.editItem = function(item) {
       $scope.itemToEdit = item;
       $scope.showForm = true;
   };
});

markup
<form show-slide="showForm" name="myForm" ng-submit="saveItem()">
    <input type="text" ng-model="itemToEdit.name" />
    <input type="submit"/>
</form>

         {{item.name}}
        edit


text:
Q: WPF WebBrowser won't show Google Maps This is a follow up question to this question:
Load local HTML file in a C# WebBrowser
I've created an html file by simply copying the example from this link:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
When I run it by double clicking the file which opens the regular web browser (i.e Firefox), it works. I then added the HTML to my sln, and change the file's property to always be copied to the output directory. I then tried running it like this:
string curDir = Directory.GetCurrentDirectory();
webBrowser.Navigate(new Uri(String.Format("file:\\{0}\\mymap.html", curDir)));

The browser is opened with the yellow warning on top:

"to help protect your security, your browser has restricted this file from showing active content .."

I'm clicking it, allowing the blocked content, and then I get a message saying there's an error in the script in the page. I'm allowing it to continue, and the browser remains blank.. why is that?

A: After searching for an answer, I came across this blog entry:
https://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version
First of all for the yellow warning, just add this comment line under the html tag of the page:
<!-- saved from url=(0016)http://localhost -->

You can read more about it here:
https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/ms537628(v=vs.85)
Regarding the map and the script error:
It seems like you need to set the WebBrowser's IE version to edge, in order to be able to render HTML5.
set this line as the first one inside the head tag:
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

After these 2 changes, it will work


text:
Q: Trying to print list of object names, just get memory address instead Here's the code in question for the Person class:
class Person:
    def __init__(self, firstName, lastName, email, yearRounder, symptomatic, tested):
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.yearRounder = yearRounder
        self.symptomatic = symptomatic
        self.tested = tested
    def __repr__(self):
        return str(self)

I'm assigning these objects to variable names generated on the fly through exec() commands. I'm trying to make it print so that I see a list of the assigned names and not the memory addresses. Can anyone lend a hand?
EDIT: To clarify: Trying to make the objects assign to PatientXXXX variable names instead of the names themselves. For instance, the first person in the database would be assigned as Patient0001 = Person(John, Smith, johnsmith@gmail.com, False, False, False) and then print a list that's like [Patient0001, Patient0002] etc


text:
Q: C# Starting threads from a Loop throws IndexOutOfBoundsException It's very weird because It's very apparent that the loop condition will never cause an Exception
Thread [] threads = new Thread[threadData.Length];
for (int i = 0; i < threadData.Length; i++)
{
   threads[i]= new System.Threading.Thread(() => threadWork(threadData[i]));
   threads[i].Start();
}

It just causes IndexOutOfBoundsException for threadData[i]

A: It's the normal problem of loop capturing - you've captured the loop variable, so by the time the thread actually starts, i is the final value, which is an invalid index into the array. The solution is to create a new variable inside the loop, and capture that instead:
Thread[] threads = new Thread[threadData.Length];
for (int i = 0; i < threadData.Length; i++)
{
    int copy = i;
    threads[i]= new System.Threading.Thread(() => threadWork(threadData[copy]));
    threads[i].Start();
}

You can read more about this on Eric Lippert's blog: part 1; part 2.
Personally I would consider using List<T> more though, and using foreach where possible - or even LINQ. foreach wouldn't have solved this problem, admittedly, but it would be generally cleaner IMO.
Here's an example of how you might have done it in LINQ:
List<Thread> threads = threadData.Select(x => new Thread(() => ThreadWork(x)))
                                 .ToList();
foreach (Thread thread in threads)
{
    thread.Start();
}

Or with a straight foreach loop, starting each thread as you go:
List<Thread> threads = new List<Thread>();
foreach (var data in threadData)
{
    var dataCopy = data;
    Thread thread = new Thread(() => ThreadWork(dataCopy));
    thread.Start();
    threads.Add(thread);
}

A: You have captured over the loop variable i which may cause the last value of 'i' to be used when each thread eventually executes and retrieves data from threadData. Assign i to a variable in the loop and use that instead, e.g.:
Thread [] threads = new Thread[threadData.Length];

for (int i = 0; i < threadData.Length; i++)
{
    int index = i;
    threads[i]= new System.Threading.Thread(() => threadWork(threadData[index]));
    threads[i].Start();
}

Eric Lippert has a very nice article on the phenomenon here:
http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx
http://blogs.msdn.com/b/ericlippert/archive/2009/11/16/closing-over-the-loop-variable-part-two.aspx
For an insight into why this happens, consider that the threads will execute at some undetermined point in the future, perhaps after the loop has finished. Start signals that the thread should start, it actually starts asynchronously though i.e. not immediately. Given this, we can see that the lambda passed to the Thread may execute well past the loop finishing. So how can it have a reference to i?
In short the compiler will create a helper class that can encapsulate i, then replace references to i with this helper class. This allows the lambda to have a reference to i outside of the scope of the loop. A nice example of compiler magic, but in this case has a non-obvious side-effect i.e. it captures over the loop variable:
    private class LambdaHelper
    {
        public int VarI { get; set; }
    }

    private static void SomeMethod()
    {
        LambdaHelper helper = new LambdaHelper();

        Thread[] threads = new Thread[threadData.Length];

        for (helper.VarI = 0; helper.VarI < data.Length; helper.VarI++)
        {
          threads[helper.VarI] = new Thread(() => ThreadWork(data[helper.VarI]));
          threads[helper.VarI].Start();
        }
    }

Here we can see that VarI is used in place of i. The non-obvious side-effect is that when the threads execute they all see a shared value i.e. VarI. If the threads start after the loop has finished, they will all see the maximum value of i.
The fix is to assign i to a temporary variable inside the loop as detailed in the first code example.


text:
Q: Produce a dataframe from comparison process As input dataframe having a data structure like this:
dframe <- data.frame(id = c(1,2), col1 = c(4.2, 1.2), su = c(1.2,2.4))

How is it possible to compare the number in every row for the two columns and according to the greatest produce a new column which will have the col name of the greatest value and a second column with this value?
dcom <- data.frame(id = c(1,2), col1 = c(4.2, 1.2), su = c(1.2,2.4), com = c("col1", "su"), com_num = c(4.2, 2.4))
dcom
  id col1  su  com com_num
1  1  4.2 1.2 col1     4.2
2  2  1.2 2.4   su     2.4

A: A vectorized solution can be the following.
com_num <- with(dframe, pmax(col1, su))
i <- which(dframe[-1] == com_num, arr.ind = TRUE)
dframe$com <- names(dframe[-1])[i[, 2]]
dframe$com_num <- com_num

dframe
#  id col1  su  com com_num
#1  1  4.2 1.2 col1     4.2
#2  2  1.2 2.4   su     2.4


text:
Q: can I avoid displaying ^C while writing in the standard input? I'm trying to read from the standard input and I'd like to avoid displaying expressions such as ^C or ^D when pressing ctrl+C ....
I'm only allowed to use tcsetattr and tcgetattr functions.
int main() {
    while(1) {};
}


text:
Q: How do I create a list of ggplots? I have these three data frames and this function
set.seed(1)
df1 <-
  data.frame(
    x = c("cat", "dog"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )

df2 <-
  data.frame(
    x = c("red", "green"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )

df3 <-
  data.frame(
    x = c("up", "down"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )

dataframes <-
  c("df1", "df2", "df3")

exploreDataFrames <- function(dataframes, sequence = seq_along(dataframes)){

  for (i in seq_along(sequence)){
    print(get(dataframes[i]))

    gg <-
      get(dataframes[i]) %>%
      ggplot(aes(z, y, group = 1)) +
      geom_line() +
      facet_wrap(~get(names(get(dataframes[i]))[1]))

    return(gg)
  }
}

exploreDataFrames(dataframes[3])

I'd like for my function to return a list with three entries:
list[1][1] <- name_of_the_dataframe
list[1][2] <- copy_of_the_complete_dataframe
list[1][3] <- ggplot_object

My goal is to be able to have a single list and iterate through the ggplot charts, quickly be able to slice it by the name of a particular data frame and pull up the complete dataframe.
What do I need to change about my function to make this possible?

A: You can use
l = sapply(dataframes, function (dfname) {
      ggplot(get(dfname) , aes(z, y, group = 1)) +
      geom_line() +
      facet_wrap(~get(names(get(dfname))[1]))
    }, simplify = FALSE, USE.NAMES = TRUE)

the data.frame names are then in names(l)
names(l[1])
# [1] "df1"

and the data are in
l[[1]]$data

#     x  y          z
#1  cat 68 2020-01-01
#2  dog 39 2020-01-02
#3  cat  1 2020-01-03
#4  dog 34 2020-01-04
#5  cat 87 2020-01-05
#6  dog 43 2020-01-06
#7  cat 14 2020-01-07
#8  dog 82 2020-01-08
#9  cat 59 2020-01-09
#10 dog 51 2020-01-10
#11 cat 85 2020-01-11
#12 dog 21 2020-01-12
#13 cat 54 2020-01-13
#14 dog 74 2020-01-14
#15 cat  7 2020-01-15
#16 dog 73 2020-01-16
#17 cat 79 2020-01-17
#18 dog 37 2020-01-18
#19 cat 83 2020-01-19
#20 dog 97 2020-01-20

A: You need to initiate the whole list before starting to populate it. Since you have a nested level in the list, you need to initiate that "inner" list too:
set.seed(1)
df1 <-
  data.frame(
    x = c("cat", "dog"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )
df2 <-
  data.frame(
    x = c("red", "green"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )

df3 <-
  data.frame(
    x = c("up", "down"),
    y = sample(1:100, 20),
    z = seq(ymd("2020-01-01"), ymd("2020-01-20"), by = "1 day")
  )

dataframes <-
  c("df1", "df2", "df3")

exploreDataFrames <- function(dataframes, sequence = seq_along(dataframes)){

  ll <- list()

  for (i in seq_along(sequence)){
    ll[[i]] <- list()
    ll[[i]][[1]] <- dataframes[i]
    # print(get(dataframes[i]))
    ll[[i]][[2]] <- get(dataframes[i])
    ll[[i]][[3]] <-
      get(dataframes[i]) %>%
      ggplot(aes(z, y, group = 1)) +
      geom_line() +
      facet_wrap(~get(names(get(dataframes[i]))[1]))

  }
  return(ll)
}

out <- exploreDataFrames(dataframes)

A: To return the list the question asks for, create a list to hold the objects before the for loop, with the length set to length(sequence) and assign the values in the loop.
exploreDataFrames <- function(dataframes, sequence = seq_along(dataframes)){

  out_list <- vector("list", length = length(sequence))
  for (i in seq_along(sequence)){
    dftmp <- get(dataframes[i])
    print(dftmp)

    gg <-
      dftmp %>%
      ggplot(aes(z, y, group = 1)) +
      geom_line() +
      facet_wrap(~get(names(dftmp)[1]))

    out_list[[i]]$data.name <- dataframes[i]
    out_list[[i]]$data <- dftmp
    out_list[[i]]$gg.plot <- gg
  }
  out_list
}

exploreDataFrames(dataframes[3])

This will plot the out_list[[1]]$gg.plot object, since the function's return value is not assigned to anything, it's returned to the .GlobalEnv.


text:
Q: Angular 5: adding types to external JS file I'm loading a JS file through a <script src="http://.../script.js">
In the JS, there is a namespace "foo", and a method "bar".
I would like to call foo.bar() from my component.
I'd like to add type definitions so that I know what I'm doing while I'm coding. I have the file script.d.ts with type definitions. It looks like this:
export as namespace foo;

export namespace Baz {
    interface Qux {
    // ...
    }
}

export function bar(): Baz.Qux;

I can't figure out how to include this file in the Angular build (using CLI), so that I get type checks during build, but at runtime the namespace and function in the external JS file will be called from my component. Help?

A: You don't need the export modifier, since these are not exported from a module you can use declare and reference them with a /// or include the definitions in tsconfig:
// script.d.ts
declare namespace foo {
    namespace Baz {
        interface Qux {
        // ...
        }
    }

    declare function bar(): Baz.Qux;
}

// Other file
/// <reference path="./script.d.ts" />
foo.bar() // works and calls method from remote JS file


text:
Q: Is there a name for string "chunk" justification? I was recently implementing the following algorithm (written for clarity; there are many ways to write it more compactly):
tmp = str.length % blocksize
if (tmp == 0)
  tmp = blocksize
tmp = blocksize - tmp
str.append(padchar * tmp)

It ensues the string str is a multiple of blocksize, padding with padchar as necessary. I've found myself implementing this often enough, that today I implemented it yet again, and realized that it must be common enough to have a proper name or be in some common libraries, yet I've never seen or heard of it. This example is left-justified, but I could imagine a similar right-variant. My attempts at googling "chunk justification" or "block justification" turned up nothing. It isn't standard left or right justification, as all api's for those that I've seen are fixed length, whereas this is semi-variable length.
So, my two questions:

*

*Does this have a more formal name?

*Is this algorithm implemented in any language standard library or common utilities?

(note that although I've used strings in this question, the algorithm works just as well for, and I'm just as interested in answers for generic lists/arrays)
Example output:
> thisalgo(str="hey!", blocksize=5, padchar='0')
"hey!0"
> thisalgo(str="hello", blocksize=5, padchar='0')
"hello"
> thisalgo(str="hello!", blocksize=5, padchar='0')
"hello!0000"

A: Not sure about a single name, but there are two operations involved:

*

*Padding (leftpad, rightpad, etc. - see How can I pad a String in Java?)

*Round up length to next multiple
I would call the combined operation "Pad string to next multiple", which is quite intuitive, but not a 'proper' name.
BTW, this combined operation is used extensively in cryptography, where it is simply called 'padding'.


text:
Q: Server doesn't work (Jboss and aerogear war files) hello everyone i was following this tutorial (https://github.com/aerogear/aerogear-unifiedpush-server) to have an UnifiedPush server of aerogear so i have download the two .war files and put them in deployments, but when i tried to lunch the server there is n error that i don't understand (sorry if my english is bad).
18:10:47,857 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-16) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./ag-push: org.jboss.msc.service.Start
Exception in service jboss.undertow.deployment.default-server.default-host./ag-push: Failed to start service
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_40]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_40]
        at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_40]
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
        at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:219)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
        at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
        ... 3 more
Caused by: java.lang.NullPointerException
        at org.jboss.aerogear.unifiedpush.keycloak.BootstrapListener.contextInitialized(BootstrapListener.java:40)
        at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173)
        at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:190)
        ... 7 more

18:10:47,863 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "unifiedpush-server-0.11.0.war")
]) - failure description: {"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./ag-push" => "org.jboss.msc.service.StartException in service jboss.undertow.deploym
ent.default-server.default-host./ag-push: Failed to start service
    Caused by: java.lang.RuntimeException: java.lang.NullPointerException
    Caused by: java.lang.NullPointerException"}}
18:10:47,884 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "unifiedpush-server-0.11.0.war" (runtime-name : "unifiedpush-server-0.11.0.war")
18:10:47,885 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 1) JBAS014774: Service status report
JBAS014777:   Services which failed to start:      service jboss.undertow.deployment.default-server.default-host./ag-push: org.jboss.msc.service.StartException in service jboss.undertow.deployment.def
ault-server.default-host./ag-push: Failed to start service.

can anyone help please.
thank you very much.

A: You could build it yourself, using the -Pwildfly maven profile.
Another option is using the docker image:
https://github.com/abstractj/docker/tree/master/aerogear-unifiedpush-dev
Or use the offering for Openshift (you need an OS account, but that is free):
https://github.com/aerogear/openshift-origin-cartridge-aerogear-push


text:
Q: Split sentences in python with citations I'm trying to split sentences from academic papers. Traditionally splitting sentences would simply be:
sentence = 'This is a sentence. This is another sentence'
separate = sentence.split('.')

#  [ This is a sentence, This is another sentence ]

However, this logic does not work if you have sentences such as:
This is a sentence is a paper with a citation (author et al., 2020a) and it contains more
information. This is similar to the examples I have (author et al., 2020a).

How could I split sentences (like the sample above) so the output would look something like this:
['This is a sentence is a paper with a citation (author et al., 2020a) and it contains more information' , 'This is similar to the examples I have (author et al., 2020a)' ]

What is an easy solution to this problem? Appreciate the suggestions.

A: A simple solution would be to split on "\. (?>[A-Z])" (dot space uppercase) :
sentences = values.split(r"\. (?>[A-Z])") # split nicely in the 2 sentences
sentences = values.split(r"\. ") # more basic and generic

A more powerful one is to use a dedicated lib like nltk : Python split text on sentences


text:
Q: Dynamic Reactive Form using Angular I have created a dynamic reactive form which is working fine except for the first item of the FormArray which is displayed as null.
Current Output

Expected Output

Subsequent items of the array are generated fine. And if I delete the first item after generating other items, the data is saved correctly.
I see the following error on the console and have tried looking for a solution but according to various answers on the web I have done it correctly.

ERROR Error: Cannot find control with path: 'contentBoxes -> 0 -> contentType'

Unable to display error. Open your browser's console to view.

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

ERROR Error: Cannot find control with path: 'contentBoxes -> 0 -> revenueShare'

Unable to display error. Open your browser's console to view.

Code can be viewed and run here: https://stackblitz.com/edit/angular-ui5n8c
Thanks a lot for the help.

A: You put a reference of the function at index 0: this.buildGroup; that should of course be: this.buildGroup(). That way the function will be invoked and the actual object will be returned. So your problem is, the function is not being executed.
So to summarize:
```
  buildArray(): FormArray {
    this.contentBoxes = this._fb.array([
      this.buildGroup() // <---- notice the () I added, these are needed!
      //this._fb.control('')
    ]);
    return this.contentBoxes;
  }

```


text:
Q: Transfer data from 1 column to another from different table with middle table as link I have 3 tables with table C.Bid referencing to B.id and B.Aid referencing to A.id. I want to transfer data from columns in table A to table C but having issues with the sql.

Heres what i did
UPDATE contact_address,
(SELECT contact_master.id , contact_master.address,
contact_branch.contact_master_id, contact_branch.id
FROM contact_master
INNER JOIN contact_branch ON contact_master.id =
contact_branch.contact_master_id)
SET contact_address.address = contact_master.address
WHERE contact_address.contact_branch_id = contact_branch.id;

My understanding from the UPDATE Statement, is the comma can be used to separate different column we want to add in the select statement.
How do i transfer these data column using referenced attribute in the middle table? error im getting is

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET contact_address.address = contact_master.address
where contact_address.cont' at line 5

I already have the rows of data on table C where i insert them using these query.
INSERT INTO `contact_branch` (contact_master_id)
SELECT `id` FROM `contact_master`;

INSERT INTO `contact_address` (contact_branch_id)
SELECT `id` FROM `contact_branch`;

A: Solved it, giving AS to subquery, and AS for middle table (conatct_branch) id so it won't confuse the program.
UPDATE contact_address,
(SELECT contact_master.*, contact_branch.id AS cId
FROM contact_master
INNER JOIN contact_branch ON contact_master.id = contact_branch.contact_master_id) AS subque
SET contact_address.address = subque.address
WHERE contact_address.contact_branch_id = subque.cId;


text:
Q: PDF creation function crashes after deployment I have method, which creates a pdf file from the view, based on information retrieved from the model. It works without any problem on my pc in debug mode, however after deployment on IIS server (different machine) it started crashing.
I have granted full access to all user on a map with assembly but it didn't help.
Error message is useless it only says that "something went wrong"

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

My Code:
    [HttpPost]
    public ActionResult EmployeesForExamination(List<EmployeeListForHealthExamination> model)
    {
        List<EmployeeListForHealthExamination> listForPrint = new List<EmployeeListForHealthExamination>();
        foreach (var item in model)
        {
            if (item.printDoc)
            {
                return CreatePDF(item);
            }
        }
        return View(model);
    }
    [AllowAnonymous]
    public ActionResult ReportForHE(EmployeeListForHealthExamination model)
    {
        using (var db = new HRMEntities())
        {
            model.harmingFactorList = db.EmployeeHarmingFactors.Where(e => e.EmployeeId == model.EmployeeId).ToList();
            return PartialView("Partial/_ReportHE", model);
        }
    }

    [AllowAnonymous]
    public ActionResult CreatePDF(EmployeeListForHealthExamination model)
    {
        return new ActionAsPdf("ReportForHE", model)
        {
            FileName = model.FirstName + model.LastName + "HealthExamination.pdf"
        };
    }

A: This issue could be because of lack of visual c++ of an old version of your visual c++ on server, try to upgrade it.


text:
Q: Plotting a graph row by row from a table using matlab (Instead of column) I have a data set that looks like as below and i want to plot them into a graph. I have seen a couple of examples online for graphs , however they are plotting column by column and the data source are from different matrix file.
What i am trying to achieve is to plot multiple graphs on the same figure using the data set as below.

My final product that i am trying to achieve is the image below. Can someone be kind enough to guide or point me in the right direction ?

The C1990 stands for carbon emission yr 1990.
So far i was able to plot the following but with much changes to the data source, rearranging and performing transpose operation.

A: Here is a starting point.
data = rand(5, 20); // random data for five countries
countries = {'Afghanistan', 'Argentina', 'Australia', 'Austria', 'Belgium'}; // cell array containing the names of the countries

H = zeros(size(countries));

hold on

H = plot(data', 'Marker', '.', 'LineWidth', 1.0, 'MarkerSize', 16);

legend(H, countries)

Output:

This answers the question how to plot multiple graphs (by row). To polish the plot you just have to play with different properties of the graphs and the axes.


text:
Q: Angular 4 Filteration on Button Click I am new in Angular 4 currently there is a list of data without filtration and on the left side, I have given category list. So, when any user will click on any of Category the list should be filtered. Please let me know how can I do this?
xyz.component.html

{{ category.name }}

      {{post.blogger.name}}

xyz.component.ts
  export class BlogComponent implements OnInit {
        filteredPosts=[];
        originalPosts=[];

        constructor(private blogService: BlogService) {
          this.blogService.getBlogPosts().then(res=>this.originalPosts=res);
        }
        public filter(bgr, cat){
          if(cat != null){
            let category = this.categories[cat]
            this.filteredPosts = this.originalPosts.filter(d => d.category.id == cat);
          }
        }
    }

Current Output which displays all category
Current Output
Expected Output which should display only the selected category eg. Author
Expected Output
Unable To Filter?

A: Do this

{{ category.name }}

component
originalPosts = []; // add all posts
filteredPosts = [];

public filter(categoryId){
    this.filteredPosts = this.originalPosts.filter(post => post.category.id === categoryId;
}


text:
Q: Wondering why this formula works in one cell and not another and if there is any alternative this is the formula in question,
=INDEX(C:C,COUNTA(C:C),1)

in this form it works perfectly and displays the latest result from that row and column.
=INDEX(AA:AA,COUNTA(AA:AA),1)

However, the above does not work and just displays blank. Why does the double column identifier ruin it? is there an alternative I can use for these columns?.

A: most likely you got there an empty cell in that AA column that will offset the result
try this instead:
=INDEX(INDIRECT("AA"&MAX((AA:AA<>"")*(ROW(A:A)))))


text:
Q: How to sort null value at the end while in Ascending MongoDB I have multiple documents and some of the document does not contain that key which I want to sort so it is treated as null and when I sort then null data came first but I need to take preference other one and null placed at the end.
sample data:
[
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":"A",
      "description":"Mens Upper Shirt"
   },
   {
      "cat_id":2,
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":"A",
      "rank":5,
      "description":"Shirt"
   },
   {
      "cat_id":3,
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat_type":"Women Top wear",
      "description":"cloths"
   },
   {
      "cat_id":4,
      "categoryCode":"categoryCode4",
      "categoryName":"categoryName4",
      "cat_type":"A",
      "rank":8,
      "description":"Women"
   }
]

in above example cat_id- 1 and 3 does not contains rank field and it output response it came at last.
expected output:
[
   {
      "cat_id":2,
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":"A",
      "rank":5,
      "description":"Shirt"
   },
   {
      "cat_id":4,
      "categoryCode":"categoryCode4",
      "categoryName":"categoryName4",
      "cat_type":"A",
      "rank":8,
      "description":"Women"
   },
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":"A",
      "description":"Mens Upper Shirt"
   },
   {
      "cat_id":3,
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat_type":"Women Top wear",
      "description":"cloths"
   }
]

I am using this query-
db.collection.aggregate([
  {
    $addFields: {
      sortrank: {
        $cond: {
          if: {
            $eq: [
              "$rank",
              null
            ]
          },
          then: 2,
          else: 1
        }
      }
    }
  },
  {
    "$sort": {
      "sortrank": 1
    }
  }
])

A: I think your direction of using an auxiliary field to sort is correct. You can use $ifNull to assign a dense index(e.g. 999) as your sort rank.
db.collection.aggregate([
  {
    "$addFields": {
      "sortrank": {
        "$ifNull": [
          "$rank",
          999
        ]
      }
    }
  },
  {
    $sort: {
      sortrank: 1
    }
  },
  {
    $project: {
      sortrank: false
    }
  }
])

Here is the Mongo playground for your reference.


text:
Q: carousel bootstrap slider firefox I'd be grateful if you could help me. I use a CSS3 bootstrap carousel slideshow. Slideshow appears in the following link.
It works fine in google chrome but unfortunately it doesn't work in mozilla firefox or internet explorer. I use -moz and -webkit css3 tricks but not working..


text:
Q: Same content (language) for multiple countries (store views) I'm trying to implement an e-commerce site (using Magento 2) that has the following requirements:

*

*be available in N countries (eg http://example.com/country_code/ )

*with X languages

*share the same price

*Currency changes depending on the selected country

The initial idea is to create 1x website with 1x store with N store-views
However, I wanted to reuse the content in countries that share the same language base (eg: English in the US and UK)
It becomes impracticable to add or change the same content to several different store-views.
Do you know the best Magento practice to handle this issue, or if there is a module from a Magento partner to manage a multi-locale and multi-language store?
Thank you


text:
Q: Can you only construct proofs for tautologies? I'm studying Logic and Discrete Structures and we are covering natural deduction. We're using Jape to construct proofs and I'd like to know if we can only construct proofs for a formula if it is a tautology?
If so would the proofs for these tautologies be in the classical conjecture pane as opposed to the invalid conjecture pane? It seems like the truth tables for the formulas in the invalid conjecture pane are not tautologies.

A: The first thing to point out is that in Jape you don't so much prove statements to be tautologies, as that you demonstrate that some statement can be derived from other statements.
This is what the $\vdash$ symbol is for that you see in all of the panes: it is used to claim that some statement can be derived from others. For example:
$$P \to Q, P \vdash Q$$
is the claim that $Q$ can be derived from $P \to Q$ and $P$.
Here, the statement that is being derived is typically called the conclusion, while the statements from which you derive the conclusion are called the premises or givens.
Note that this claim is a claim about some relationship between logic expressions. As such, this is a 'meta-logical' statement, rather than a logic statement/expression in and of itself. But, like any claim, this meta-logical claim is true or false, which is why it is called a Conjecture.
All of the Conjectures in the Invalid conjectures window are false conjectures, e.g. $$E \to (F \to G) \vdash (E \to F) \to G$$ claims (conjectures) that $$(E \to F) \to G$$ can be derived from $$E \to (F \to G)$$
but that is false: As it turns out, $(E \to F) \to G$ can not be derived from $E \to (F \to G)$.
On the other hand, all conjectures in the Classical conjectures and the Conjectures windows are true. (the difference between 'Classical conjectures' and 'Conjectures' seems to be that the conjectures in the 'Classical conjectures' window are more 'elementary'.
OK, so with that out of the way, let's see how all of this applies to tautologies.
First, you'll note that some conjectures do not contain the $\vdash$ symbol. For example, the Classical Conjectures window contains $$E \lor \neg E$$ as a conjecture. OK ... so then exactly what is the Conjecture here then? Well, you should treat this as the conjecture $$\vdash E \lor \neg E$$, i.e. that $E \lor \neg E$ can be derived using no premises at all.
[I must say that I am not happy with the fact that the authors of Jape leave out the $\vdash$ in these cases: As I said, something like $$\neg \neg E \vdash E$$ is a meta-logical claim, but $$E \lor \neg E$$ is, by itself, a logical expression, and so we really have two quite different kinds of claims in the conjecture windows.  I really would have preferred it had the authors had used $$\vdash E \lor \neg E$$
since that is, undoubtedly, the actual conjecture that is being made here about $$E \lor \neg E$$]
Now, any statement can can be derived from no premises at all is a tautology. Indeed, $E \lor \neg E$ is a tautology. So, that should answer your question that you pose in the body of your post:

would the proofs for these tautologies be in the classical conjecture pane as opposed to the invalid conjecture pane?

The answer is (slightly nuanced) Yes: you will never see a tautology appear in the Invalid conjectures window. Instead, it may appear in the Classical conjectures window ... though (and here's the nuance) a more complicated (less 'elementary') tautology could appear in the Conjectures window. In fact, we see a number of tautologies in the latter window. That very first one:
$$A \to (B \to (A \to B))$$
is a tautology, and so, as a conjecture:
$$\vdash A \to (B \to (A \to B))$$
it is a true conjecture.
OK, so what if a statement is not a tautology?  You ask:

I'd like to know if we can only construct proofs for a formula if it is a tautology?

Again, the answer is a (nuanced) Yes:  If we have a statement that is not a tautology, e.g.:
$$P \to (P \land Q)$$
then we cannot derive that statement from no premises. That is, the conjecture:
$$\vdash P \to (P \land Q)$$
is False. So, this is something you could find in the Invalid conjectures window (although the authors of Jape would probably drop the $\vdash$ symbol and put
$$P \to (P \land Q)$$
in the Invalid conjectures window.  Interestingly, there are no such examples (of a single statement that is not a tautology) in the Invalid conjectures window.
So yes, if a statement is not a tautology, then there is no proof for it ... if (here's the nuance) there are no premises.  OK, so what if you do have premises? Well, let's go back to:
$$\neg \neg E \vdash E$$
Here, the conclusion $E$ can be derived from premise $\neg \neg E$. As such, we often say that we 'prove $E$' ... though what we really should say is that we 'prove $E$ from $\neg \neg E$'.
The point is: the way we talk about 'proving statements' is often such that the statement we prove is in fact not a logical tautology. For example, the statement
$$1 + 1 = 2$$
is not a tautology, and accordingly the conjecture:
$$\vdash 1 + 1 = 2$$
is False.
However, we can still prove the statement to be true given a bunch of premises: premises that define the numbers $1$ and $2$, and that define how addition is supposed to work. Thus, we what we do have is that:
$$PA \vdash 1 + 1 = 2$$
where $PA$ ('Peano Arithmetic') is a standard set of axioms that mathematicians and logicians like to work with to prove mathematical theorems.
So, long story short: when in the title of your post you ask:

Can you only construct proofs for tautologies?

one could also say 'No': you can prove statements from other statements, and the proven statements need not be tautologies.
OK, that's a lot to throw at you at once, but read it over a few times, see if it makes sense, and let me know if you have any further questions.


text:
Q: Regex: match single equal sign with negative lookahead = I am building something that requires the user to input conditions and then I will parse it with PHP. I want to build a preg_replace that replaces = with == but == remains untouched.
Examples
a=b => a==b
a==b => a==b
a = b => a == b
a == b => a == b

So basically if a user forgets that the condition needs == instead of =, the system will allow that too.

A: You can use this regex,
(?<![=!])=(?![=!])

Which ensures a = will only be selected if it is not preceded or followed by a = and replace it by ==
Demo
Sample PHP codes,
$arr = array("a=b", "a==b", "a = b", "a == b", "a!=b");
foreach($arr as $s) {
    echo $s, ' --> ', preg_replace('/(?<![=!])=(?![=!])/', '==', $s) , "\n";
}

Prints,
a=b --> a==b
a==b --> a==b
a = b --> a == b
a == b --> a == b
a!=b --> a!=b

A: You could get the desired result by doing the following :
$string = "a == b" ;
$string = str_replace('==', '=', $string);
$string = str_replace('=', '==', $string);

var_dump($string);

By replacing all == to = and then replacing all = to ==

A: Another option is to use positive lookbehind to assert what is on the left is either a word character \w or a whitespace character \s
(?<=[\w\s])=+

Regex demo | Php demo
For example:
$result = preg_replace('/(?<=[\w ])=+/', '==', $str)


text:
Q: Angular 4.1.3 routing could not resolve child module from parent module Thank you ahead of time for any help!!!!
Hello, As the title says. I'm getting the following error.... I'm trying to do a bunch of research and figure it out, but nothing I do seems to work. Here are some important files, does anyone have experience with this issue or see the problem? (Also the error is coming from ng serve and ng build but with ng serve it fails first then automatically rebuilds and works perfectly. So it does work with ng serve but since the first is a fail I can't build it (which obviously is the main problem)
ERROR in Could not resolve "patient.module" from "d:/Downloads/AngularApp/AngularApp/src/app/app.module.ts".

app.routing.ts
const patientRoutes: Routes = [
    {
        path: 'patient',
        loadChildren: 'app/patient/patient.module.ts#PatientModule',
    }
];

const nurseRoutes: Routes = [
    {
        path: 'nurse',
        loadChildren: 'app/nurse/nurse.module.ts#NurseModule',
    }
];

const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'auth',
        pathMatch: 'full'
    },
    {
        path: 'auth',
        component: AutenticationComponent
    },
    ...patientRoutes,
    ...nurseRoutes
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});

patient.module.ts
import { NgModule }                     from '@angular/core';
import { CommonModule }                 from '@angular/common';
import { patientRouting }               from './patient.routing';

import { PatientDashboardComponent }    from './dashboard/patient-dashboard.component';

@NgModule({
              imports:      [
                  CommonModule,
                  patientRouting
              ],
              declarations: [
                  PatientDashboardComponent
              ]
          })
export class PatientModule { }

patient.routing.ts
import { ModuleWithProviders }          from '@angular/core';
import { Routes, RouterModule }         from '@angular/router';

import { PatientComponent }             from './patient.component';
import { PatientDashboardComponent }    from './dashboard/patient-dashboard.component';
import { PatientVideoComponent }             from './video/video-chat.component';

const patientRoutes: Routes = [
    {
        path: 'patient',
        component: PatientComponent,
        children: [
            {
                path: '',
                component: PatientVideoComponent,
                children: [
                    {
                        path: '',
                        component: PatientDashboardComponent,
                    }
                ]
            }
        ]
    }
];

export const patientRouting: ModuleWithProviders = RouterModule.forChild(patientRoutes);

angularcli.json
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": ["assets"],
      "index": "index.html",
      "main": "main.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "mobile": false,

A: I finally found something on this and this seems to work. They changed their routing structure so instead of saying app/patient just go directly to using ./patient for example.
https://github.com/angular/angular-cli/issues/3623

A: app/dir1/dir2/...
(assuming the routes module is configured inside app directory) to
./dir1/dir2/...
Can solve this problem:
const routes: Routes = [
  {
    path:'customers',
    loadChildren: './customers/customers.module#CustomersModule'

  },
  {
    path: 'orders',
    loadChildren: './orders/orders.module#OrdersModule'
  },
  {
    path:'contacts',
    loadChildren:'./contacts/contacts.module#ContactsModule'
  },
  {
    path:'',
    redirectTo:'',
    pathMatch:'full'
  }
];


text:
Q: How to upload file from javascript to php server? How to upload image or other file from javascript to php server ???
i am working on php api how to send and receive
please help me
i am getting josn data using
$login = file_get_contents('php://input');

i want to upload image using js and receive using php and upload to server disk
Here is my login.php file
  <?php
session_start();
//server accpet response in forllowing format
//{"username":"administrator","password":"administrator","remind":"on"}
// iuncluding function file
require_once "../includes/system.php";
    if(isset($_COOKIE['COOKIE_KEEP_ME_NAME1shpingcart'])){
            $_SESSION['login_usershoping'] =  $_COOKIE['COOKIE_KEEP_ME_NAME1shpingcart'];
        }
   if(isset($_SESSION['login_usershoping'])){
    $success['alreadylogin'] = "true";
    echo $successlogin = malik_encode($success );
    die();
}
// get value
$login = file_get_contents('php://input');
    if(empty($login)){
        $error['error'] = "Username & password never be empty";
        echo $errorlogin = malik_encode($error );
        die();
    }
//decode and convert into assos array by using custom function
$login_decode = malik_decode($login,true);
    $username =  $login_decode['username'];
    $password =  $login_decode['password'];
    $remind = $login_decode['remind'];

    $db = malik_database_connection();
    $connected = null;
    $username = $db->quote($username);
        $select = $db->query("SELECT * FROM users WHERE username=$username");
        if($select->rowCount() > 0){
            $user = $select->fetch();
            $ban = $user['ban'];
              if($ban === 'yes'){
                 $error['error'] = "Your account is banned by our admistrator";
                 echo $banerror = malik_encode($error );
              }
            if (password_verify($password, $user["password"])){
                if(isset($remind) && $remind === 'on'){
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME1shpingcart',$user['salts'] ,time() + (86400 * 30 * 12), '/',false,true);
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME2',malik_ramdomstring_generator(60) ,time() + (86400 * 30 * 12), '/',false,true);
                //generate for storing cookies
                setcookie('COOKIE_KEEP_ME_NAME3',malik_ramdomstring_generator(50) ,time() + (86400 * 30 * 12), '/',false,true);
                }
                $se= $_SESSION['login_usershoping'] =  $user['salts'];
                 $success['success'] = "true";
                 echo $loginsuccess = malik_encode($success );
                exit();

            }else {
                $connected = false;
            }
            }else{
            $connected = false;
        }
           if ($connected === false):
           $error['error'] = "Username and password wrong";
            echo $loginerror = malik_encode($error );
         $connected = null;
       endif;

A: upload.html:
    <!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    </head>
    <body>
        <form id="uploadform">
            <input type="file" name="file"/><br/>
            <button type="submit">
                Upload!
            </button>
        </form>
    </body>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
    <script>

        $("form#uploadform").submit(function () {
            var formData = new FormData(this);

            $.ajax({
                url: '/upload_file.php',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                    alert(data)
                },
                error:function(data){
                    alert(data);
                },
                cache: false,
                contentType: false,
                processData: false
            });

            return false;
        });
    </script>
</html>

upload_file.php:
/*
 * Do your authentication logic here, log in user, etc.
 */

//Fist, check if we have any file sent to the script:
$file = isset($_FILES['file']) ? $_FILES['file'] : NULL;

//It seems we have a file?
$tmpfile = $file['tmp_name'];
//Find the file extension:
$fileparts = explode('.', $file['name']);

//Apply the extension, usually the last item in the parts array:
$fileExtension = $fileparts[count($fileparts) - 1];

//Make a filename:
$filename = md5($file['name']);

//add file extension to the filename:
$filename .= '.' . $fileExtension;

//Save to current directory:
$saveto = __DIR__ . DIRECTORY_SEPARATOR . $filename;

//Move file:
move_uploaded_file($tmpfile, $saveto);

///If we ever get here, the file has been uploaded, saved and moved to the permanent location
print 'File saved to: ' . $saveto;


text:
Q: 24AWG Ribbon Cable Connectors I have some Amphenol 24AwG Spectra-Strip 10 conductor ribbon cable that I want to use in an aquarium LED project.
Unfortunately, its dimensions don't match those of a traditional 2x5 crimp connector. The spacing between the individual conductors is such that only half of the ribbon fits within the connector.
Does anyone know of a source for ribbon cable crimp connectors that work with larger size ribbons? If not, what other approaches could I try?
Additional Info
From what I can gather, for 2xN ribbon cable crimp connectors, the spacing between wires has to be 0.05 inches, even though the connectors themselves present the pins on a 0.1 inch interval. My 10 conductor ribbon cable has the individual conductors at 0.1 inch intervals, so a typical 2x5 connector only connects 5 of its pins when it's crimped on (the other five slots "connect" to the ribbon material between each conductor).
It occurred to me I could work around the problem of using this particular ribbon cable by using a standard 2x10 connector. Only half of the pins will be connected to a wire, but that would least let me use standard parts.
I've ordered some 2x10s and will report back on what I learn.

A: The standard method of using this type of cable with dual-row 2xN connectors is to use crimp pins on the individual conductors, then insert the pins into an appropriate housing.
These housings go by several different names.  On eBay, people refer to them as "Dupont" connectors.  The housings and pins (in cut-tape form) are really quite inexpensive.
However, I need to be able to order from reputable suppliers.  One such is Harwin.  These are readily available from Digikey: Harwin 2x5 housing.  The matching contacts are also available from Digikey: Female Contacts 22-30 AWG.
The Asian suppliers sell these things for almost nothing.  I purchase the eBay versions for my own projects but use parts from Digikey for my customer's projects.

A: I've used a lot of 22 AWG ribbon cable but have never seen a IDC for that gauge.  If anyone has seen them, let us know.

A: Using a standard 2x10 ribbon connector intended for use with 28 AWG ribbon cable is a bad idea for several reasons.
1) You will need to remove one row of pins from the connector.  If you don't do that, all of the conductors in the cable will most likely be shorted together.
2) The gap in the pins is too small for the conductor diameter.  You will wind up cutting many of the strands in each conductor.  Because each conductor has only 7 strands, you have reduced both the current-carrying capability of the wire PLUS reduced the physical strength significantly.
In addition to both of the above problems, the wire outside diameter is too large to allow the top of the ribbon connector to lock into place.


text:
Q: How to define macro for UIAlertViewController? There are 400 Alertview object added as we need in old project so here I want to define macro for UIAlertViewController in objective-c which is introduced in iOS 8.0
Please help me defining it in Constant file.

A: Only For Alertview
#define SHOW_ALERT(title,msg,del,cancel,other) \
do { \
UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:del cancelButtonTitle:cancel otherButtonTitles:other,nil]; \
[_alert show]; \
} while(0);

Only For AlertViewController
#define SHOW_ALERT2(title,msg,ButtonTitle)\
do { \
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];\
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:ButtonTitle\
                                                       style:UIAlertActionStyleDefault\
                                                     handler:nil]; \
    [alertController addAction:actionOk];\
    [self presentViewController:alertController animated:YES completion:nil];\
}while(0);

For Both AlertView and AlertViewController
#define SHOW_ALERT3(title,msg,delegate,ButtonTitle) \
    do { \
        if ([UIAlertController class]) {\
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];\
            UIAlertAction *actionOk = [UIAlertAction actionWithTitle:ButtonTitle\
            style:UIAlertActionStyleDefault\
            handler:nil]; \
            [alertController addAction:actionOk];\
            [self presentViewController:alertController animated:YES completion:nil];\
        }\
        else {\
            UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:delegate cancelButtonTitle:ButtonTitle otherButtonTitles:nil]; \
            [_alert show]; \
        }\
    }while(0);


text:
Q: PDF of Y=sin^2(X) Suppose X ∼ Exponential(λ). Find the PDF of $$Y = sin^2(X)$$
Note: While the solution involves an infinite sum, it is an example of a geometric series and so can be evaluated.
My answer so far:
I was able to go as far as finding the bounds, and now I am stuck on the integral itself. As in the directions, we are told to use a geometric series, but I don't know how to proceed from here.
The integral which will give me the CDF
I also have the piece $$P(0 <= x <= arcsin(\sqrt t))$$ I know this does not included in the integral, but I don't know how to incorporate it into my CDF.
$$\int_a^b \lambda\ e^-\lambda x\ \,dx,$$
$$ a = k \pi\ - arcsin(\sqrt t)$$
$$ b = k \pi\ + arcsin(\sqrt t)$$

A: This is the problem of finding derived distribution, so
$$CDF_Y(y)=P(Y\leq y)=P(\sin^2(X)\leq y)$$
Now it is time to draw the plot of $\sin^2(x)$ for $x>0$ and see how to calculate this probability; for $0\leq y \leq 1$ it is
$$P(\sin^2(X)\leq y)=\int_{0}^{\arcsin{\sqrt{y}}}{\lambda e^{-\lambda x}} dx+\sum_{k=1}^{\infty}\int_{k\pi-\arcsin{\sqrt{y}}}^{{k\pi+\arcsin{\sqrt{y}}}}{\lambda e^{-\lambda x}} dx$$
The integrals are simple, and the sum is the sum of geometric series.


text:
Q: query in two or three fields elasticsearch I have the query below that searches simultaneously in three fields (title, url and description) in my index.
{
  "from": 0,
  "size": 10,
  "sort": [
    {
      "pgrk": {
        "order": "desc"
      }
    },
    {
      "url_length": {
        "order": "asc"
      }
    }
  ],
  "query": {
    "multi_match": {
      "query": "netflix releases",
      "type": "cross_fields",
      "fields": [
        "title",
        "url",
        "description"
      ],
      "operator": "and"
    }
  }
}

Is there any way to search in just two fields and if don't find anything, search in the third field too? that is, I wanted to search only in the fields (title and url) and if I can't find anything, search the three fields (title, url and Description)
My query sorts the results by the field (pagerank) and by the field (url_length) cannot remove the ordering by the field (pagerank and url_length) because this ordering is important for my results. With this sorting that I do it does not generate (_score), if it generated score I would put (boost) in the fields (title and url) to give relevance to these two fields,  but as there is no score, I need a way to search in two relevant fields and if don't find anything, search the three fields


text:
Q: How can retrieve values from a RedisResult if the result is a MultiBulk I can retrieve all keys in a Redis database by executing a command like:
RedisResult allRedisKeys = redisDatabase.Execute("KEYS", new List<object>
{
   "*"
})

But I can not make use of the variable allRedisKeys since its _value field is private. How can I extract the value from a RedisResult? In my case, _value holds a RedisResult[] and allRedisKeys has a RedisType of RedisType.MultiBulk.

A: First of all, per the documentation, don't use the KEYS command in a production environment. However, you can use the .Keys method per server, but this requires querying each server individually (and it's O(N) so also not the best).
For a faster (but more complex) solution, take a look at this answer by Marc Gravell. Basically, you store all your keys in a SET so you have O(1) response time.
This is my implementation of his suggestion:
/// <summary>
/// Class that keeps track of cache keys and the expiration of said keys.
/// Uses a LIST to store the keys because it's faster than using SCAN on the entire Redis database.
/// Expirations are stored as ticks.
/// </summary>
public static class KeyAndExpirationTracker
{
    private const string ALL_KEYS = "ALL_KEYS";
    private const string EXPIRATION_SUFFIX = "|EXPIRATION";

    public static void StoreKeyAndExpiration(IDatabase db, string key, TimeSpan? timeToLive, ITransaction transaction)
    {
        string expiryKey = $"{key}{EXPIRATION_SUFFIX}";
        // although Redis will automatically replace an existing key,
        // we still have to remove this in case this we went from having an expiration to not expiring
        db.KeyDelete(expiryKey);

        // add the item key to the list of keys
        transaction.SetAddAsync(key);
        // add the separate cache item for expiration (if necessary)
        if (timeToLive.HasValue)
        {
            DateTime expiry;
            try
            {
                expiry = DateTime.UtcNow.Add(timeToLive.Value);
                transaction.StringSetAsync(expiryKey, expiry.Ticks.ToString());
            }
            catch (ArgumentOutOfRangeException)
            {
                // no expiration then
            }
        }
    }

    public static void StoreKeyAndExpiration(IDatabase db, string key, DateTime? expiration, ITransaction transaction)
    {
        string expiryKey = $"{key}{EXPIRATION_SUFFIX}";
        // although Redis will automatically replace an existing key, we still have to remove this in case this we went from having an expiration to not expiring
        db.KeyDelete(expiryKey);

        // add the item key to the list of keys for this client type
        transaction.SetAddAsync(cacheKey, key);
        // add the separate cache item for expiration (if necessary)
        if (expiration.HasValue)
        {
            transaction.StringSetAsync(expiryKey, expiration.Value.Ticks.ToString());
        }
    }

    public static IEnumerable<string> GetKeys(IDatabase db)
    {
        RedisValue[] keys = db.SetMembers(ALL_KEYS));
        if (keys.Length == 0)
            return new string[0];

        List<string> expiredKeys = new List<string>(keys.Count());
        List<string> ret = new List<string>(keys.Count());

        // get expiration values using SORT with GET: https://redis.io/commands/sort
        RedisValue[] results = db.Sort(
            ALL_KEYS,
            sortType: SortType.Alphabetic,
            by: "notarealkey", // a (hopefully) non-existent key which causes the list to actually not be sorted
            get: new RedisValue[] { $"*{EXPIRATION_SUFFIX}", "#" } // # = "get the list item itself" which means the key in our case
        ));

        // SORT results will be in the same order as the GET parameters:
        // result[0] = expiration (= null if no matching expiration item found)
        // result[1] = key
        // (repeat)
        for (int i = 0; i < results.Length; i += 2)
        {
            string key = results[i + 1].Replace(EXPIRATION_SUFFIX, string.Empty);

            RedisValue expiryRedis = results[i];
            long ticks;
            if (long.TryParse(expiryRedis, out ticks))
            {
                DateTime expiry = new DateTime(ticks, DateTimeKind.Utc);
                if (expiry <= DateTime.UtcNow)
                    expiredKeys.Add(key); // expired: add to list for removal
                else
                    ret.Add(key);
            }
            else
                ret.Add(key);
        }

        // remove any expired keys from list
        if (expiredKeys.Count > 0)
        {
            IBatch batch = db.CreateBatch();
            batch.SetRemoveAsync(cacheKey, expiredKeys.ConvertAll(x => (RedisValue)x).ToArray());
            foreach (string expiredKey in expiredKeys)
            {
                batch.KeyDeleteAsync(expiredKey);
            }
            batch.Execute();
        }

        return ret;
   }

    public static void RemoveKeyAndExpiration(IDatabase db, string key, ITransaction transaction)
    {
        // remove the key from the list and its corresponding expiration value
        string expiryKey = $"{key}{EXPIRATION_SUFFIX}";
        transaction.SetRemoveAsync(ALL_KEYS, key);
        transaction.KeyDeleteAsync(expiryKey);
    }

}

NOTE: The StoreKeyAndExpiration and RemoveKeyAndExpiration methods both take an ITransaction because I'm doing these operations in conjunction with adding or removing items to cache, so I want to wrap them all up into a single transaction. The transaction doesn't get executed here in case the calling method wants to add more operations to it.


text:
Q: why the output displays 3 and not a char in java i would understand why the output is 3 and not a char ('5' unicode character)
char c='5';
c = (char) (c - 2);
System.out.println(c);

and could you please explain what's the difference beetween code ASCII and unicode character ?
thank you in advance :)

A: It is a character. It's a character representing the numeral 3, just as '3' is a character on your keyboard.
When you subtract one from a character, you get the character immediately before that. For example, 'B' - 1 = A.
You start with the character '5' and subtract two, giving the character '3'. If you subtracted 6, you would not get -1, you'd get a random character ('/' I think).
Basically this subtraction works because the characters 0 - 9 are stored contiguously.

A: The output is the char '3', not the number 3.
When you subtract 2 from the char '5' and cast the result to char, you get the char '3'.
The char type is a numeric primitive type. Each character has a corresponding integer value between 0 and 2^16-1. The integer value of the character '3' is smaller by 2 than the value of the character '5'.


text:
Q: Is it possible to access Slim symbols from code with FitSharp? According to FitSharp issue 123 it wasn't possible to in July 2014.  I was wondering if this has changed in the years since.

A: There's no way defined in the Slim protocol to do this.  We'd have to inspect the parameter types to see if a method wants the Slim symbols passed to it, e.g.
using fitSharp.Machine.Engine;
...
public void GetTheSymbols(Symbols symbols) { ...}


text:
Q: Safe to Delete Keynote Cache under /Library/Container/com.apple.iWork.Keynote/Data/Library/Caches While the question "is it safe to delete /Library/Caches" is commonly seen, OSX also has another path for storing caches (not sym link). Keynote has another cache stored at /Library/Container/com.apple.iWork.Keynote/Data/Library/Caches. In particular, a subfolder named DocumentCaches store a some of my slides created in keynotes.
Is it safe to delete this folder?

A: Cache is cache. Deleting it is safe. It's recommended to have all applications involved closed tho. Tools like Onyx are mostly the best way to just do a periodic cleansing every now and then.
If you just intend to delete that cache; no worries. Just close Keynote and remove the caches. You might want to remove the app states for that app too if this is a matter of something behaving weird in while working in it.


text:
Q: How to upgrade from 12.04.1 LTS to 12.04.4 LTS from USB? I want to upgrade from 12.04.1 LTS to 12.04.4 LTS and there is no GUI. Which is the best way to upgrade to Ubuntu?

A: You don't need USB for that because it is not upgrade it is Update !
Open a tty Terminal (Ctrl+Alt+F1) and:
sudo apt-get update
sudo apt-get upgrade

Note:

*

*the first command updates packages list

*the second command downloads and updates software installed on your PC