text:
Q: android.content.ActivityNotFoundException: Unable to find explicit activity class - how to fix it? I have a very basic and yet annoying issue. I created new activities and pass the intent to move to them. Yet when I communicate the two:
MainMenu and EventCreationActivity, I get the following error:
android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.mysampleapp.EventCreationActivity}; have you declared this activity in your AndroidManifest.xml?
When I run the activities separately they work perfectly.
Here is the code of MainMenu
   package com.mysampleapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

//import com.amazon.mysampleapp.R;

public class MainMenu extends AppCompatActivity {
    //public final static String EXTRA_MESSAGE = "com.mysampleapp.MESSAGE";
    final Intent intent = new Intent(this, EventCreationActivity.class);
    Button newEvent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_menu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        newEvent = (Button) findViewById(R.id.new_event_button);

        newEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(intent);
            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}

And manifest:
   <application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" />
        <activity
            android:name=".LogInActivity"
            android:label="@string/title_activity_log_in"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainMenu"
            android:label="@string/title_activity_main_menu"

            android:theme="@style/AppTheme">
            <!--android:parentActivityName=".LogInActivity"-->
            <!--<meta-data-->
                <!--android:name="android.support.PARENT_ACTIVITY"-->
                <!--android:value="com.mysampleapp.LogInActivity" />-->
        </activity>
        <activity
            android:name=".MainDrawerActivity"
            android:label="@string/title_activity_main_drawer"
            android:theme="@style/AppTheme">
            <!--<meta-data-->
                <!--android:name="android.support.PARENT_ACTIVITY"-->
                <!--android:value="com.mysampleapp.MainMenu" />-->
        </activity>
        <activity
            android:name=".EventCreationActivity"
            android:label="@string/title_activity_event_creation"

            android:theme="@style/AppTheme">
            <!--android:parentActivityName=".MainMenu"-->
            <!--<intent-filter>-->
                <!--<action android:name="android.intent.action.MAIN" />-->
                <!--<category android:name="android.intent.category.DEFAULT" />-->
            <!--</intent-filter>-->
            <!--<meta-data-->
                <!--android:name="android.support.PARENT_ACTIVITY"-->
                <!--android:value="com.mysampleapp.MainMenu" />-->
        </activity>

As you see, I commented some stuff in the Manifest file, but it did not help. I also looked other, similar questions and they did not help.
Thanks in advance,
John

A: Solution is in your question
have you declared this activity in your AndroidManifest.xml?

use full package name with class like this in your Manifest
android:name="com.mysampleapp.MainMenu"

A: You're instantiating the intent before the activity has gone through its life cycle methods. This means that the Context that you pass in to the Intent constructor is not valid.
Typically, the intent is created right before you use it:
newEvent.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainMenu.this, EventCreationActivity.class);
        startActivity(intent);
    }
});

A: John, have you tried the full Activity name com.mysampleapp.MainMenu? Do this for all activities: your.package.ActivityName.
<activity
        android:name="com.mysampleapp.MainMenu"
        android:label="@string/title_activity_main_menu"

        android:theme="@style/AppTheme">
        <!--android:parentActivityName=".LogInActivity"-->
        <!--<meta-data-->
            <!--android:name="android.support.PARENT_ACTIVITY"-->
            <!--android:value="com.mysampleapp.LogInActivity" />-->
    </activity>

A: Just follow these steps, you will definitely solve this problem:
1) Go To File.
2) Click on Invalidate Cache/Restart
3) Now go to AndroidManifest.xml and most probably you are not shown
RED sign on your activity. If you see the RED on your activity then remove it and again type the name of the activity with packagename.

A: Newbie here. I added the name of my 2nd java class to my AndroidManifest.xml, just above the  and right below the . Now I can run my application on the emulator instead of having the "apps keep closing" error. Im not quite sure why it worked though. Got the idea from above ^ @ikkarion.
<activity
android:name=".MainActivity2"
android:exported="true"/>


text:
Q: jQuery mobile 1.4.5 and custom button image I need to use custom png instead of default search icon of jQuery mobile.
The code I have for default button is following
Search

I try to redefine the CSS like this
.ui-icon-search {
  background:
    url('images/search.png')
    50% 50% no-repeat!important;
}

I see the image but cannot get rid of the theme CSS design.

UPDATE #1
I used CSS of the user deblocker and it looks like

A: JQM is using the ::after pseudo-selector for button icons.
First example:
I'm not able to understand the size of your icon, so i'm using in this example a bigger one, 32x32px icon to show how to change also the appearance of the container button.

.ui-icon-search {
  height: 48px !important;
}
.ui-icon-search:hover:after {
  background-color: transparent !important;
  border-radius: 0 !important;
}
.ui-icon-search:after {
  width: 32px !important;
  height: 32px !important;
  background-size: 32px !important;
  background: 50% 50% no-repeat !important;
  border-radius: 0 !important;
  margin-left: -16px!important;
  margin-top: -16px!important;
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAB3RJTUUH4QMBECUe4AoxxgAAAAlwSFlzAABOIAAATiABFn2Z3gAAAARnQU1BAACxjwv8YQUAAAZKSURBVHjaxZZbbBRVGMe/OXPZmdmZne3eui0tlLbQFlIQTEXBpGIg0XqNWnkwPBqTqjHxwfBgYmpiqDGoIUh4EYwYH4wPqDHiJYV6QQ1gwUpbamFpN9DdbtttZ3dmb3Pxm+420Qi4i6An+facOXP2/H/n+75zzgD8z4W61os9ez4SeJ7uZlnm8VDI1yHLQg3DMFAoGPOapg/iXz8XRe697ds3zd50gL6+w08Gg9631qxZWYsAMKMadipHcgxNQBJotj7I0U5/LDanJZPpvpMns329vVuNfw3Q3d1Nt7d37V23rrmHFwUYnaG0+rYmY2W9Yocl4AQCkCuAEZnO2Vcm43S9xxL9Hhe5ePHyQKFgPtzVdadaKQD580NLy/a9t922qic6k8+Pcw0zd3RthOYmhXULwOVtgKyFxAwwdTUudn3HcrLgqZ0/E9EybW0NnRxHHz106Bh/wwAvvbTvyebmup7RS2reWLVpvqnFLxoWUAUUzptoKK6jaVYRxOkLBDne3dqY/e7cQrq5uf6umhrh9RsC6O7egwnHvWXaFFyp2hALhNxSNociGNUsAuTQMmbJnD6j2OcYLxCXFlqRikzp+epq33NffXW6rWKA6mrorqurrv123I4vawwrGGfI5lEsizW2M6XVL3lAt4ttBySD47wKo/wcExI+n4cYRv6FigFM03wctxfkg+1pwwRWR+EMekDDWsugGIpkSx7Ilrzg9Dnv0jq2cazKB3LxuYwly+JjcJ3tfVUAUeQ74smc3X9B+Xkkal7ACW0tVxLJFkUcW2w7VhJOZYriTr/AE2lo0pxTFCn4ySc/NZQLwCz+MHRNIgXaTMpOf3RM+3HtCubc5rWu5vpqOuyVwFMwgdgW6OiVhJ610hgBWnSBz8WREIaIOKGyLCJems5N390qByiqsAynjZQNYGC6523DxrMFAjIBFFR/ixi/RBMWyCIFKAYulgBFA9gYghyOz6KoaZtC2EdaJZFencZE4W2wivPZdEUe0PXMvOAWZK8IxCcTK6DQEFAI+GUKAfD0Q+NYAGQA00m+AgH0BCykITM5bQ6i+LDAUQ33eqkWHRPIssx4RQCqqg3WK/LWBnYuxHqqY370whJElQQIgTHm0O842nQyH3dGSi9CUcU0ziVV88Kq1dSWRCKpDw0dH68IIJ83P0Pnbg1rgy1GfVfMK1FQhACscZt5ACQ84+iSB5xEdMLiPIPlhMyCBnamKVzFMWfOzB3p7e0t+15YBMAt+P70dPLVZZK5aoHMD3nE4JyCK69C8WAVQmBbxNXSlBP3Igzr5IPl/BdzIk/YdnbqdlV14WIKB8oVd8qiA48c6ZtV1fTrPGsTbvjTbQJrukS+6HoFTUb3Y0SgCnG9WCsIsxQaNw/Ucv3sPW3LFen336MLoZB8tmIApyQSJ/qi0djxAF/wzvZ/8BBdSMkCCjnG4yiMCHhxnESKzy7ayQuLpSOntrWHycrz5ydgw4bViMV03BDAwMCAoarsIxMTUz94SNY3+vHhJ4aPfX+7kc2JpDTQMbpYM7GRi63Rb/q7VyqO+CR4PG6IRqf1S5emZn97BbjIG/57ygH425F5333Puzwez278Cnre71cYvJ9syaskPTKvMjSDUbfduM/8HklknON7bGxiEE+/dfiBom7c2Fo1OjxeaEruzbTWRORcItWz4sXZAxUBLJUdO15uwxPyWZz8sUDAW6MobnC5ONS2IJ3W0wsL2lFCmH27dz8zsGvX/kZdz4s+L//rVn8/tfHB7SBJcZg9ftDWLi9cF6KsS2Pnzr7lPA91NE3RHAexs2f1yMDAX7daT2en1NKopXbcL0Ko4xGgau8AmB/4RwimHIDDh3dNYjV5vTEN4un1jaxhulM8bUTkxYmp2k7ATKDg+MH9E28CXA2i7DP7n8rX4/no+pA4bmczj4aFGCGANxjDAhXcAmLYRxlzIw88u5nE3/4yc+qWADjlm/Hc0JqA+yoQm68JcVMBrg3BXRPipgNUCnFLAK4OYZQgtgAtEGpmfKJp39G5d8raBTdadn2hfth3P16loL+/CU4sLjY/n4TRkxFIr3kXb5jO8rbhzYJYmzlBn4qnQNzyGoyMTY85729ZCP5clsIxcplfe4Z5Kj08Fv9pair29OnT/an/Qv+65Q9wv/+DycxdGwAAAABJRU5ErkJggg==) !important;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

      Search

Second example:
From your edit it seems you need a standard 22x22px button inside a Toolbar or Navbar, so the CSS is even simpler.
Moreover i added some JQM no-frills rules (Some credits codaniel from this answer: JQuery Mobile: how to not display the button focus halo when a button is clicked?, see also this great post from Omar: How to remove the blue halo glow from jQuery Mobile input elements that receive focus.
Feel free to check it out, IMHO it will be a somewhat cleaner, mobile-friendly look.

.ui-btn-inline.ui-icon-search {
  background-color: transparent !important;
  border-style: none !important;
}
.ui-icon-search:after {
  border-radius: 0 !important;
  background-color: transparent !important;
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAB3RJTUUH4QMCCBQRtmh2wwAAAAlwSFlzAABOIAAATiABFn2Z3gAAAARnQU1BAACxjwv8YQUAAAQgSURBVHjatZRbaBxVGMe/c+Y+mb1PNpfdbjepSW3TKNJYk4K1BSF50EihyYO1hIjkrQ9F30NeFAXBB1/6GN+aShGJio+lUCtBiwqJTbfZJE2y2exm7zv3mePZQGsKuVCLH3znMHPO95s//+/MAfifAu1+mJi4zvX2qr3t7ZFLGDMXBVlOchyLMbjrAs/+6DjkRjpdmBsfv2AcBmZ2f+Ty5Q/GY/HmL10xOBTuSPrD0QgJq0FPDIQUy8WnZYEZapJZfmDgtXuzs7PeoYobShMJYSyeTHxmhuNC8tQRFPXzyMdhkDCAQwDKukM21yskgjRPKxW+KhbtL4aH+7T9wLgxqKrVGwj6PtmAZtbX2QGsKGIbMNJdQFUHkEZnQi2RYkG0ZMpEVpQJv58/f5DiHbAgyJc2Nb4Nt3YS22WZGtVRcwAq7r9ZpWm4GHuKH6/VJVkUmQ8PBWu6dTHrteWKpmBUNCBlCi7VKIy2qGLRNKkVdYBihb6zMN6wJNMhzODMzF1pPzDbGBwPJR9kyK8lw8qf7eESXTEc9whWdBMcy/K2LRdsFpOghxh/XcOoUiPIkTlGECBGy1P7gk3bRY5re5rmbs+nYbtQZu+rAQ9k2jmOaax7QO1BgOxIk4S72brnIx5pMk2dOVCxrdc3oj5DgRBGbSpLjqgMtIQBFBkDT3cYNqY2eCRb8PKPt7xit+z2OEa9hTq5fiDYddwfws7qCKu88ndMFfUELYlHMYQUAJ5q0myAXJGqp7sRsfHLTdWoadTvjI5eqB3YPF23ZkQzb4Yqf3VH/ICaQxhiVHE8AHDEB5AIAbRHAKJBDC+JuYSKSzHLMG8deirW1pbmKuXqdSm/cMxc/KVH8GpCgPY7RNWqdEeAzjJjc3J19dhRNvs69hw2EPApZBJwI/cC75i/svKHw/PH7/kVLECl8Lae20oS3WC1Ulkq50v+rUy+JZtafdXcWO8q5Qsiz/NutVIrm86fcTeIW4f7aqnp2/DML/7MJTQyck2SpMh5RRHGfX55SFVDrCyLxLYt5NjeHQDyjWnaSJK4wQSfev/cGd3ji3c364sLH8Wu5n7eF7w7xsYmRYzFdp7HTKGgZW7enNpp1CS1r+VK18dv9omfn3znCkLhVqj+Pr1VS81fK25kvj01BdbTU7FXTE9PNa7Gpb3WBGt9QcuQFWvhuyR/4j1QekebwbvxKSKE1mzeeurx88Rt6odw0n7EZoX7gpUd9ENG4UOdiE++EUBu/tzVAS09frr26LnBjZifB/LTA3u5v51NYyPfF+IKIS7YgfhEnwJWtp9xjMx/Aj+JFtFJsYR/yFn5twJM3scFEghFewLlreLxFwL/lgHv+3n74ZkWdhHr2X7R3gwtZ/wojd+tvBD4SbRK9jKPuNXHWTgxVz5bz+nBr/8BY6vJZPw2PtcAAAAASUVORK5CYII=) !important;
}
.ui-icon-search:hover:after {
  background-color: transparent !important;
  border-radius: 0 !important;
}

/* jQM no frills */
.ui-btn,
.ui-btn:hover,
.ui-btn:focus,
.ui-btn:active,
.ui-btn:visited  {
    text-shadow: none !important;
}
.ui-focus,
.ui-btn:focus {
    -moz-box-shadow: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
}
/* speed-up some android  ans iOS devices */
* {
    -webkit-tap-highlight-color:rgba(0,0,0,0) !important;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Header

<button data-icon="home">One</button>

<button data-icon="grid" data-theme="b">Two</button>

<button data-icon="search">Three</button>

Third and last example:
I'm using here a custom rule, alternate styles (black & white icons), 22x22px svg icons & png as fallback, tested also in older IE versions with body class="ui-nosvg".

.ui-icon-search-custom {
  border-width: 0 !important;
  border-style: none !important;
  background-color: transparent !important;
}
.ui-icon-search-custom:after {
  margin-top: -9px !important;
  border-radius: 0 !important;
  background-color: transparent !important;
}
/* white svg */
.ui-icon-search-custom:after {
  background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyB3aWR0aD0iMjJweCIgaGVpZ2h0PSIyMnB4IiB2aWV3Qm94PSIwIDAgMjIgMjIiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+ICAgIDxnIGlkPSJzZWFyY2giIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPiAgICAgICAgPGcgaWQ9InNlYXJjaCIgZmlsbD0iI2ZmZmZmZiI+ICAgICAgICAgICAgPGcgaWQ9InNlYXJjaCI+ICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNS4yMzY0NDgsMTMuNDM5NTAyOCBMMTQuMjkwMDU2OSwxMy40Mzk1MDI4IEwxMy45NTQ2MjcxLDEzLjExNjA1MjcgQzE1LjEyODYzMTMsMTEuNzUwMzc0NCAxNS44MzU0Mjk4LDkuOTc3Mzg4NDQgMTUuODM1NDI5OCw4LjA0ODY2NzI3IEMxNS44MzU0Mjk4LDMuNzQ3OTc4NDQgMTIuMzQ5MzU2MSwwLjI2MTkwNDc2MiA4LjA0ODY2NzI3LDAuMjYxOTA0NzYyIEMzLjc0Nzk3ODQ0LDAuMjYxOTA0NzYyIDAuMjYxOTA0NzYyLDMuNzQ3OTc4NDQgMC4yNjE5MDQ3NjIsOC4wNDg2NjcyNyBDMC4yNjE5MDQ3NjIsMTIuMzQ5MzU2MSAzLjc0Nzk3ODQ0LDE1LjgzNTQyOTggOC4wNDg2NjcyNywxNS44MzU0Mjk4IEM5Ljk3NzM4ODQ0LDE1LjgzNTQyOTggMTEuNzUwMzc0NCwxNS4xMjg2MzEzIDEzLjExNjA1MjcsMTMuOTU0NjI3MSBMMTMuNDM5NTAyOCwxNC4yOTAwNTY5IEwxMy40Mzk1MDI4LDE1LjIzNjQ0OCBMMTkuNDI5MzIwMiwyMS4yMTQyODU3IEwyMS4yMTQyODU3LDE5LjQyOTMyMDIgTDE1LjIzNjQ0OCwxMy40Mzk1MDI4IEwxNS4yMzY0NDgsMTMuNDM5NTAyOCBaIE04LjA0ODY2NzI3LDEzLjQzOTUwMjggQzUuMDY1NzM4MjQsMTMuNDM5NTAyOCAyLjY1NzgzMTY5LDExLjAzMTU5NjMgMi42NTc4MzE2OSw4LjA0ODY2NzI3IEMyLjY1NzgzMTY5LDUuMDY1NzM4MjQgNS4wNjU3MzgyNCwyLjY1NzgzMTY5IDguMDQ4NjY3MjcsMi42NTc4MzE2OSBDMTEuMDMxNTk2MywyLjY1NzgzMTY5IDEzLjQzOTUwMjgsNS4wNjU3MzgyNCAxMy40Mzk1MDI4LDguMDQ4NjY3MjcgQzEzLjQzOTUwMjgsMTEuMDMxNTk2MyAxMS4wMzE1OTYzLDEzLjQzOTUwMjggOC4wNDg2NjcyNywxMy40Mzk1MDI4IEw4LjA0ODY2NzI3LDEzLjQzOTUwMjggWiIgaWQ9IlNoYXBlIi8+ICAgICAgICAgICAgPC9nPiAgICAgICAgPC9nPiAgICA8L2c+PC9zdmc+) !important;
}
/* black svg */
.ui-alt-icon.ui-icon-search-custom:after {
  background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyB3aWR0aD0iMjJweCIgaGVpZ2h0PSIyMnB4IiB2aWV3Qm94PSIwIDAgMjIgMjIiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+ICAgIDxnIGlkPSJzZWFyY2giIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPiAgICAgICAgPGcgaWQ9InNlYXJjaCIgZmlsbD0iIzAwMDAwMCI+ICAgICAgICAgICAgPGcgaWQ9InNlYXJjaCI+ICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNS4yMzY0NDgsMTMuNDM5NTAyOCBMMTQuMjkwMDU2OSwxMy40Mzk1MDI4IEwxMy45NTQ2MjcxLDEzLjExNjA1MjcgQzE1LjEyODYzMTMsMTEuNzUwMzc0NCAxNS44MzU0Mjk4LDkuOTc3Mzg4NDQgMTUuODM1NDI5OCw4LjA0ODY2NzI3IEMxNS44MzU0Mjk4LDMuNzQ3OTc4NDQgMTIuMzQ5MzU2MSwwLjI2MTkwNDc2MiA4LjA0ODY2NzI3LDAuMjYxOTA0NzYyIEMzLjc0Nzk3ODQ0LDAuMjYxOTA0NzYyIDAuMjYxOTA0NzYyLDMuNzQ3OTc4NDQgMC4yNjE5MDQ3NjIsOC4wNDg2NjcyNyBDMC4yNjE5MDQ3NjIsMTIuMzQ5MzU2MSAzLjc0Nzk3ODQ0LDE1LjgzNTQyOTggOC4wNDg2NjcyNywxNS44MzU0Mjk4IEM5Ljk3NzM4ODQ0LDE1LjgzNTQyOTggMTEuNzUwMzc0NCwxNS4xMjg2MzEzIDEzLjExNjA1MjcsMTMuOTU0NjI3MSBMMTMuNDM5NTAyOCwxNC4yOTAwNTY5IEwxMy40Mzk1MDI4LDE1LjIzNjQ0OCBMMTkuNDI5MzIwMiwyMS4yMTQyODU3IEwyMS4yMTQyODU3LDE5LjQyOTMyMDIgTDE1LjIzNjQ0OCwxMy40Mzk1MDI4IEwxNS4yMzY0NDgsMTMuNDM5NTAyOCBaIE04LjA0ODY2NzI3LDEzLjQzOTUwMjggQzUuMDY1NzM4MjQsMTMuNDM5NTAyOCAyLjY1NzgzMTY5LDExLjAzMTU5NjMgMi42NTc4MzE2OSw4LjA0ODY2NzI3IEMyLjY1NzgzMTY5LDUuMDY1NzM4MjQgNS4wNjU3MzgyNCwyLjY1NzgzMTY5IDguMDQ4NjY3MjcsMi42NTc4MzE2OSBDMTEuMDMxNTk2MywyLjY1NzgzMTY5IDEzLjQzOTUwMjgsNS4wNjU3MzgyNCAxMy40Mzk1MDI4LDguMDQ4NjY3MjcgQzEzLjQzOTUwMjgsMTEuMDMxNTk2MyAxMS4wMzE1OTYzLDEzLjQzOTUwMjggOC4wNDg2NjcyNywxMy40Mzk1MDI4IEw4LjA0ODY2NzI3LDEzLjQzOTUwMjggWiIgaWQ9IlNoYXBlIi8+ICAgICAgICAgICAgPC9nPiAgICAgICAgPC9nPiAgICA8L2c+PC9zdmc+) !important;
}
/* white png */
.ui-nosvg .ui-icon-search-custom:after {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAB3RJTUUH4QMDFxQEdHMRAAAAAAlwSFlzAABOIAAATiABFn2Z3gAAAARnQU1BAACxjwv8YQUAAAGCSURBVHjarZQ9S8RAEIY3EkQ7sRP8AYJXCIqcqK16YGFxhYoI4imCjYXgj7C0FGwUGwWL622vUFC5E7GSOz+ukhNEBBXiO2RWpths5iQDD9kkkye7m5kExhFRFOVwGALDIAQ34BLUgiD4Me0GhGPgIEqOM1BoVzoHWkLyDa7ABfgU12m8oZX2C+k72AZd4n4I5kFTvDSvEZeFdMCT1wMeOPdOvtyVPCqWuaOYxCL44PzlpLwOkOPxKzhME6Mqjk1cJUY86xVTKb2oPooxVY24k8dfSqnM7faJb+3bsWe9SvEgH+994gqP+8BUmpGrZtJuny8x5EageKSSSsmtcG7Tl2sfKIAGP3BOJeXImQYnojQ3VZuGxC3uKBtVsA/2uK3lPYpdMKOV57mjkoKWv8RS29pFlytwyKlNZ8E4GAF0fm3ipjhCrb/xTMsm/qXSb3QB109Vs1esbgXUxUcvZSJm+SpLKZ7AWpbyEkspnsF6lvKiqJpWan3/Q07SicykQv4301/GcuwCIWGRcwAAAABJRU5ErkJggg==") !important;
}
/* black png */
.ui-nosvg .ui-alt-icon.ui-icon-search-custom:after {
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAMAAADzapwJAAAA5FBMVEUAAABAQEAgICAgICArKysnJyckJCQmJiYjIyMlJSUmJiYkJCQoKCgmJiYoKCgnJycmJiYmJiYkJCQmJiYlJSUnJycmJiYlJSUnJycnJycmJiYmJiYmJiYlJSUnJycmJiYmJiYnJyclJSUnJycnJycnJycmJiYlJSUmJiYmJiYnJycmJiYmJiYlJSUlJSUmJiYmJiYmJiYmJiYmJiYnJycnJycmJiYlJSUmJiYmJiYmJiYlJSUmJiYmJiYnJycmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYnJycmJiYmJiYmJiYCMz21AAAAS3RSTlMABAgQEhocKCwwNjg5PEdISVBUWFpcXmFiY2RlZmhpa2xwdHeKi46Pk5SYmZueq6+ztrq+v8DDxsfLz9PX3+Hi4+Tl5ufs7/P19/sf9UMeAAAA0klEQVR42m3IazcCURhA4XfmIAllKpdxi0qDXHObhIkx6ez//38svM1krbM/7fXIb8vNXhSWPfnX6gUAXNXmdSMDO4ynMN0vdCljcuyLePUUW8n5mknp78wLI191BdqiNb7Y1N3mc1FmPdLRO+Fe8s650TvltuCIO70DPhZyHnCmV4b6TEuWlq43JDG6T6RGtNobg8bPrF/CoeQdWXjuR7EFutXCKyMASJtdbFC4H/Qe4n7LSNUWPt/WK0no8J2E8a7DwzHvew4PLJlxebYmrozIN8tDIYS624DnAAAAAElFTkSuQmCC) !important;
}
/* Show me the tap */
.ui-icon-search-custom:active:after {
  filter: invert(100%);
  -webkit-filter: invert(100%);
}
/* jQM no frills */
.ui-btn,
.ui-btn:hover,
.ui-btn:focus,
.ui-btn:active,
.ui-btn:visited {
  text-shadow: none !important;
}
.ui-focus,
.ui-btn:focus {
  -moz-box-shadow: none !important;
  -webkit-box-shadow: none !important;
  box-shadow: none !important;
}
/* speed-up some android  ans iOS devices */
* {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0) !important;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Header

A: Try this
.ui-icon-search {
  background:
    transparent
    url('images/search.png')
    50% 50% no-repeat!important;
    border: none;
}

A: Try this:

No additional CSS needed, but make sure, that you have right icon size.

A: Since you are using jQuery UI Mobile, you'll need to remove the search icon from ui-icon-search:after using background-image. You'll also want to remove the border, border-radius, and :hover that JQM uses.
CSS
body .ui-icon-search {
  background: url('images/search.png') 50% 50% no-repeat; /* Set Your Image */
  padding: 0; /* Remove Padding */
  border: none; /* Remove Border */
  border-radius: 0; /* Remove Border Radius */
  background-size: contain; /* Contain Background Image */
}
body .ui-page-theme-a .ui-btn:hover {
  background-color: inherit; /* Remove Hover Color */
}
body .ui-icon-search:after {
  display: none; /* Remove Default Search Icon */
}

You'll notice I don't use !important because I'm using specificity to target the CSS using the body tag.
Here is a working example that's using jQuery UI Mobile 1.4.5, and the CSS code above to get the results you wanted.
Old Result

New Result

Obviously the example I provided is not using the exact image you would end up using, but it should work just fine. You can always change the height and width of ui-icon-search to fit your icon better.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does a dictionary of numpy arrays really use less memory than an ndarray? I am trying to find a memory efficient way to store data in python variables for quick access and analysis. I initialize an 2d array in numpy and then find its memory usage (using sys so I can compare to other variable types later) via the following:
a = np.zeros((1000,1000), dtype=np.float32)
print('The size of the numpy array is {} bytes'.format(sys.getsizeof(a)))

Which returns: The size of the numpy array is 4000112 bytes
I can move this into a dictionary of 1d numpy arrays using the following for-loop:
b = {}
for ii in range(1000):
    b[f'{ii}']=a[:,ii]

print('The size of the dictionary is {} bytes'.format(sys.getsizeof(b)))

Which returns: The size of the dictionary is 36968 bytes. The dictionary size persists even if I delete a and run garbage collection, so b can't just be a container pointing to a.
Why would a dictionary of 1d arrays take up less memory than those same arrays in an ndarray?

A: There are two fundamental mistakes in your observation.

*

*you cannot delete an object, only references. If you delete a you delete the pointer. When you delete all pointers then only the object might get deleted at some point by the garbage collector

*sys.getsizeof only gives the size of the container. To get the total size you need to loop over the elements and sum.
Demonstration that the size is roughly the same:
b = {}
for ii in range(1000):
    b[f'{ii}']=a[:,ii].copy()
sum(sys.getsizeof(e) for e in b.values())
# 4096000


text:
Q: EditText Values Get Written To Database Values On Cancel I have a dialog box that allowing the user to enter in values,  each value gets validated to ensure the correct value has been entered.  However on an invalid entry the values of the EditText are getting written to the SQLite database when the user clicks Cancel.
This is my code for the Dialog Box:
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton( AlertDialog.BUTTON_POSITIVE).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Show Toast Message When No Text Is Entered
                //Validation Being Done Here
                if (TextUtils.isEmpty(inputScore.getText().toString())) {
                    inputScore.setText( "0" );
                    //return;
                }
                if (TextUtils.isEmpty(inputStrikes.getText().toString())) {
                    inputStrikes.setText( "0" );
                    //return;
                }
                if (TextUtils.isEmpty(inputSpares.getText().toString())) {
                    inputSpares.setText( "0" );
                    //return;
                }
                if (TextUtils.isEmpty(inputSplits.getText().toString())) {
                    inputSplits.setText( "0" );
                    //return;
                }
                if (TextUtils.isEmpty(inputSplitConversions.getText().toString())) {
                    inputSplitConversions.setText( "0" );
                    //return;
                }
                if (TextUtils.isEmpty(inputOpenFrames.getText().toString())) {
                    inputOpenFrames.setText( "0" );
                    //return;
                }

                final int valueScore = Integer.valueOf(inputScore.getText().toString());
                final int valueStrikes = Integer.valueOf(inputStrikes.getText().toString());
                final int valueSpares = Integer.valueOf(inputSpares.getText().toString());
                final int valueSplits = Integer.valueOf(inputSplits.getText().toString());
                final int valueSplitConversions = Integer.valueOf(inputSplitConversions.getText().toString());
                final int valueOpenFrame = Integer.valueOf(inputOpenFrames.getText().toString());
                if (valueScore > 300) {
                    inputScore.setError("Maximum value allowed is 300");
                    //return;
                } else
                if (valueStrikes > 12) {
                    inputStrikes.setError("Maximum value allowed is 12");
                    //return;
                } else
                if (valueSpares > 10) {
                    inputSpares.setError("Maximum value allowed is 10");
                    //return;
                } else
                if (valueSplits > 10) {
                    inputSplits.setError("Maximum value allowed is 10");
                    //return;
                } else
                if (valueSplitConversions > 10) {
                    inputSplitConversions.setError("Maximum value allowed is 10");
                    //return;
                } else
                if (valueOpenFrame > 10) {
                    inputOpenFrames.setError("Maximum value allowed is 10");
                    //return;
                } else {

                        alertDialog.dismiss();
                    }

                //Check If User Is Updating Game
                //Create New Game
                if (shouldUpdate && game != null) {
                    //Update Game By It's Id
                    updateGame(inputScore.getText().toString(), inputStrikes.getText().toString(), inputSpares.getText().toString(), inputSplits.getText().toString(), inputSplitConversions.getText().toString(), inputOpenFrames.getText().toString(), position);
                } else {
                    createGame(leagueId.getText().toString(), bowlerId.getText().toString(), seriesId.getText().toString(), inputScore.getText().toString(), inputStrikes.getText().toString(), inputSpares.getText().toString(), inputSplits.getText().toString(), inputSplitConversions.getText().toString(), inputOpenFrames.getText().toString());
                }
                seriesAverage = db.getSeriesAverage(savedLeagueId, savedBowlerId, savedSeriesId);
                bowlerAverage = db.getBowlerAverage(savedLeagueId, savedBowlerId);
                leagueAverage = db.getLeagueAverage(savedLeagueId);
            }
        });

    }

I would like it to display all the fields that are incorrect at once and not save the values on a cancel.  Can't seem to get this to happen though.  Below is a image of what is currently happening.

A: Try this code, with a boolean flag that indicates if all values are valid.
I include code for the cancel button just to close the dialog (I hope there are no typos).
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Show Toast Message When No Text Is Entered
        //Validation Being Done Here
        Boolean allValid = true;

        if (TextUtils.isEmpty(inputScore.getText().toString())) {
            allValid = false;
            inputScore.setText( "0" );
        }
        if (TextUtils.isEmpty(inputStrikes.getText().toString())) {
            allValid = false;
            inputStrikes.setText( "0" );
        }
        if (TextUtils.isEmpty(inputSpares.getText().toString())) {
            allValid = false;
            inputSpares.setText( "0" );
        }
        if (TextUtils.isEmpty(inputSplits.getText().toString())) {
            allValid = false;
            inputSplits.setText( "0" );
        }
        if (TextUtils.isEmpty(inputSplitConversions.getText().toString())) {
            allValid = false;
            inputSplitConversions.setText( "0" );
        }
        if (TextUtils.isEmpty(inputOpenFrames.getText().toString())) {
            allValid = false;
            inputOpenFrames.setText( "0" );
        }

        final int valueScore = Integer.valueOf(inputScore.getText().toString());
        final int valueStrikes = Integer.valueOf(inputStrikes.getText().toString());
        final int valueSpares = Integer.valueOf(inputSpares.getText().toString());
        final int valueSplits = Integer.valueOf(inputSplits.getText().toString());
        final int valueSplitConversions = Integer.valueOf(inputSplitConversions.getText().toString());
        final int valueOpenFrame = Integer.valueOf(inputOpenFrames.getText().toString());
        if (valueScore > 300) {
            allValid = false;
            inputScore.setError("Maximum value allowed is 300");
        }
        if (valueStrikes > 12) {
            allValid = false;
            inputStrikes.setError("Maximum value allowed is 12");
        }
        if (valueSpares > 10) {
            allValid = false;
            inputSpares.setError("Maximum value allowed is 10");
        }
        if (valueSplits > 10) {
            allValid = false;
            inputSplits.setError("Maximum value allowed is 10");
        }
        if (valueSplitConversions > 10) {
            allValid = false;
            inputSplitConversions.setError("Maximum value allowed is 10");
        }
        if (valueOpenFrame > 10) {
            allValid = false;
            inputOpenFrames.setError("Maximum value allowed is 10");
        }

        if (!allValid) {
            return;
        }

        alertDialog.dismiss();

        //Check If User Is Updating Game
        //Create New Game
        if (shouldUpdate && game != null) {
            //Update Game By It's Id
            updateGame(inputScore.getText().toString(), inputStrikes.getText().toString(), inputSpares.getText().toString(), inputSplits.getText().toString(), inputSplitConversions.getText().toString(), inputOpenFrames.getText().toString(), position);
        } else {
            createGame(leagueId.getText().toString(), bowlerId.getText().toString(), seriesId.getText().toString(), inputScore.getText().toString(), inputStrikes.getText().toString(), inputSpares.getText().toString(), inputSplits.getText().toString(), inputSplitConversions.getText().toString(), inputOpenFrames.getText().toString());
        }
        seriesAverage = db.getSeriesAverage(savedLeagueId, savedBowlerId, savedSeriesId);
        bowlerAverage = db.getBowlerAverage(savedLeagueId, savedBowlerId);
        leagueAverage = db.getLeagueAverage(savedLeagueId);
    }
});

alertDialog.getButton( AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        alertDialog.dismiss();
    }
});


text:
Q: Convergence test of $S=\frac{1}{\ln 2} \sum_{k=1}^\infty \ln (1+\frac{1}{k(k+2)}) \ln k$ Does S converge? (The answer says it converges)

$S=\frac{1}{\ln 2} \sum_{k=1}^\infty \ln (1+\frac{1}{k(k+2)}) \ln k$

My attempt:

Comparison test: $\ln (1+\frac{1}{k(k+2)}) \ln k \lt \ln 2 \ln k$ --- not work;
Cauchy's test: $\lim_{k \to \infty} |\ln (1+\frac{1}{k(k+2)}) \ln k|^{1/k} \lt 1$? --- hard to tell
Ratio test: $\lim_{k \to \infty} |\frac{\ln (1+\frac{1}{(k+1)(k+3)})\ln (k+1)}{\ln (1+\frac{1}{k(k+2)})\ln k} | \lt 1$? --- hard to tell
Integral test: is the series decreasing and founded?

Thanks,

A: $\ln(1+x)\lt x$ for $x\to 0$ so the sum is, term by term, smaller than
$$\dots \lt \frac{1}{\ln 2} \sum_{k=1}^{\infty} \frac{\ln k}{k(k+2)} $$
but this is clearly convergent because the logarithm is just a small correction relatively to the power laws, and $\sum 1/k^2$ safely converges. Alternatively, we may use e.g. $\ln k < \sqrt{k+100}$ for $k\geq 1$ so the latest sum is smaller than
$$\dots \lt\frac{1}{\ln 2} \sum_{k=1}^\infty \frac{\sqrt{k+100}}{k(k+2)}  $$
but this is already seen to be as convergent as $\sum 1/k^{3/2}$ i.e. as $\int 1/k^{3/2}$ whose indefinite integral is $\sim k^{-1/2}\to 0$ for $k\to\infty$.

A: You should use the equivalence
$$\ln(1+x)\sim_{x\to 0} x$$
Here as $k$ goes to $\infty$, you get
$$\ln(1+\frac{1}{k(k+2)})\ln(k)\sim \frac{\ln(k)}{k(k+2)}\sim \frac{\ln(k)}{k^2}.$$
Then, either you know the criterion of convergence of the serie $\sum_k\ln^a(k)k^b$, or you reprove it in this particular case, noticing for example that
there is a constant $M$ such that
$$\forall k\in\mathbb{N}^*, \left|\frac{\ln(k)}{k^2}\right|\leq \frac{M}{k^{3/2}}.$$

A: Note that $\log(1+x)<0$ for $x\to 0$ therefore $$\frac{1}{\ln 2} \sum_{k=1}^\infty \ln (1+\frac{1}{k(k+2)}) \ln k<\frac{1}{\ln 2} \sum_{k=1}^\infty \frac{1}{k(k+2)} \ln k$$ using the Cauchy condensation test $$\frac{1}{\ln 2} \sum_{k=1}^\infty  2^k\frac{1}{2^k(2^k+2)} k\ln 2=\frac{1}{\ln 2} \sum_{k=1}^\infty  \frac{1}{(2^k+2)} k\ln 2$$ but $$\frac{1}{(2^k+2)} k\ln 2\sim_{k\to +\infty} \frac{1}{(2^k)} k\ln 2$$ and the series  $$\sum_{k=1}^\infty  \frac{1}{(2^k)} k\ln 2$$ converges. Indeed using the root test $$\lim_{k\to +\infty} \frac{1}{({2^k}^{\frac{1}{k}})} k^{\frac{1}{k}}=\frac {1}{2}<1$$


text:
Q: Why to split the tasks not running on UI thread to make WPF app more responsive? In part1 "Getting Started" of

*

*Alexandra Rusina's series. Parallel Programming in .NET Framework 4

in order to make WPF UI responsive, it is done by outsourcing the intensive computations out of  UI.  Eventually, the code was changed to:
for (int i = 2; i < 20; i++)
 {
     var t = Task.Factory.StartNew(() =>
     {
         var result = SumRootN(i);
         this.Dispatcher.BeginInvoke(new Action(() =>
             textBlock1.Text += "root " + i.ToString() + " " +
                result.ToString() + Environment.NewLine)
             ,null);
     });
 }

Update: so shifting the intensive computations out of UI thread.
Here are the quotes from Part1 article upon coming to this snippet:

*

*"To make the UI responsive, I am going to use tasks, which is a new concept introduced by the Task Parallel Library. A task represents an asynchronous operation that is often run on a separate thread"

*"Compile, run… Well, UI is responsive"
And in order to output to WPF UI from those separate task threads (or to avoid InvalidOperationException that says "The calling thread cannot access this object because a different thread owns it.") the Dispatcher.BeginInvoke() was engaged.
Part2 of the same series "Parallel Programming: Task Schedulers and Synchronization Context" tells about the same snippet of code (after small change of introducing a local iteration variable):

"This one requires more thorough refactoring. I can't run all the
  tasks on the UI thread, because they perform long-running operations
  and this will make my UI freeze. Furthermore, it will cancel all
  parallelization benefits, because there is only one UI thread.
What I can do is to split each task into..."

Does not the part1-article contradict to the part2-article?
What is the need of splitting the tasks that are not running on UI thread into parts?
What do I undermisoverstand here?

A: I think there are two different concepts here. Part 1 talks about running code in tasks  as to not block the UI thread. Part 2 talks about running several tasks in parallel. One is used to "Not block the UI thread" and the other is used to get more things done in parallel. If you have only two threads: the UI thread and the task thread, things are not happening in parallel and you are not leveraging the true power of parallel processing.

A: The statements don't contradict, they are quite adding up to a whole.
The UI-thread is responsible for refreshing the window and the controls in it, so the react when you activate them, go over them with the mouse cursor, etc.
If you would perform a long-running operation, for example a for-loop with 10000 iterations, the UI would freeze and become unresponsive (the window will blur and the little blue donut of death will come up). Once the for-loop has completed, your UI will be there again.
In order to relieve the UI-thread from additional burden, you put long-running tasks in seperate threads/tasks, so they execute concurrently. Your UI will stay responsive and accept commands (clicks, keystrokes, ...).
Maybe unrelated but grappling on the basics behind it

Users expect an app to remain responsive while it does computation,
  regardless of the type of machine.
      This means different things for different apps.
      For some this translates to providing more realistic physics,
      loading data from disk or the web faster, quickly presenting complex scenes and navigating between pages, finding directions in a
  snap, or rapidly processing data.
      Regardless of the type of computation, users want their app to act on their input and eliminate instances where it appears suspended
  while it "thinks."

Read this article here.


text:
Q: Copy file to another folder upon creation using FileSystemWatcher - C# New to C# - I need to build a console app to monitor a set of folders on a Windows 2019 Server and copy any newly-created .txt files to another folder, using the same file name.  I need assistance with the Copy method. This is what I have so far:
using System;
using System.IO;

namespace Folderwatch
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourcePath = @"C:\Users\me\Documents\SomeFolder";

            FileSystemWatcher watcher = new FileSystemWatcher(sourcePath);

            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;
            watcher.Filter = "*.log";

            // Add event handlers.
            watcher.Created += new FileSystemEventHandler(OnCreated);

            // Wait for the user to quit the program.
            Console.WriteLine("Monitoring File System Activity on {0}.", sourcePath);
            Console.WriteLine("Press \'q\' to quit.");
            while (Console.Read() != 'q') ;

        }

        // Define the event handlers.

        private static void OnCreated(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is created.
            string destPath = @"C:\Users\pdeeb\Desktop\Temp";
            string sourceFile = ??
            string destFile = Path.Combine(destPath, sourceFile);
            File.Copy(sourceFile, destFile, true);
        }

    }
}

I feel I may be overcomplicating a simple task - I just want to copy that created file to the destPath with the same file name, and allow overwrites.  How should I be defining the sourceFile variable, or am I even on the right track with this approach?


text:
Q: How to avoid half of the picture when making a live screenshot feed? I have created a Visual Basic .NET application that takes a screenshot every second and saves it to a file screenshot.jpg And I also created a server that serves the screenshot.jpg file every second. But the problem is that sometimes I see half of the picture (probably because it hasn't finished drawing yet). Is there a way around this problem? I wonder how webcams offer that smooth stream. Does it mean my screenshot capture program is too slow?

Here is my application
' Take screenshot every second
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim bmp As Bitmap = ScreenCap()

    bmp.Save(Application.StartupPath & "\screenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
    bmp.Dispose()
End Sub

You can see the full project on Github: https://git.io/Jv4TL
And here is the front end code
<html>
<body>
    <img class="screenshot" src="screenshot.jpg">

    <script>
        setInterval(() => {
            document.querySelector('.screenshot').src =
                'screenshot.jpg?id=' + Math.random(0, 1000)
        }, 1000)
    </script>
</body>
</html>


text:
Q: SwiftUI NavigationBar back button complains about icon scaling when using custom font I see tons of logs when running my app telling me that the back button icon (chevron.backward) is being scaled.
2021-10-14 13:54:32.306371+0200 MyApp[37123:18219419] [framework] CoreUI: -[CUICatalog namedVectorGlyphWithName:scaleFactor:deviceIdiom:layoutDirection:glyphSize:glyphWeight:glyphPointSize:appearanceName:] 'chevron.backward' called with scaleFactor == 2.000000 glyphPointSize == 0.000000 at '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/CoreServices/CoreGlyphs.bundle/Assets.car'
2021-10-14 13:54:32.386602+0200 MyApp[37123:18219419] [framework] CoreUI: -[CUICatalog namedVectorGlyphWithName:scaleFactor:deviceIdiom:layoutDirection:glyphSize:glyphWeight:glyphPointSize:appearanceName:] 'UINavigationBarTitleTransitionBackIndicatorMaskSymbol' called with scaleFactor == 2.000000 glyphPointSize == 0.000000 at '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/Artwork.bundle/Assets.car'

All back buttons in my app are created by the operating system, i.e. I don't manually add back buttons to the NavigationBar. I do, however, theme the NavigationBar by setting a font and foreground color to be used via a ViewModifier. Not applying the view modifier silences all logs, so I guess my usage of a custom font is causing those messages. The app is targeting iOS 15 onwards and I'm coding on XCode 13.
I call this View Modifier once in my App:
struct MyApp:App {
  var body: some Scene {
    WindowGroup {
      NavigationView {
        ContentView
      }
      .navigationBarThemed()
    }
  }
}

The ViewModifier:
// MARK: Navigation Bar
extension View {
  public func navigationBarThemed() -> some View {
    self.modifier(ThemedNavigationBar())
  }
}

private struct ThemedNavigationBar:ViewModifier {
  // MARK: Back button
  var backButtonAppearance: UIBarButtonItemAppearance {
    let backButtonAppearance = UIBarButtonItemAppearance()
    backButtonAppearance.normal.titleTextAttributes = [
      NSAttributedString.Key.font: UIFont(name: Font.myFont.weights.regular, size: Font.sizes.navigationBarButton)!,
      NSAttributedString.Key.foregroundColor: UIColor(Color.highlight)
    ]
    backButtonAppearance.focused.titleTextAttributes = [
      NSAttributedString.Key.font: UIFont(name: Font.myFont.weights.regular, size: Font.sizes.navigationBarButton)!,
      NSAttributedString.Key.foregroundColor: UIColor(Color.highlight)
    ]

    return backButtonAppearance
  }

  // MARK: Large Title
  var largeTitleTextAttributes:[NSAttributedString.Key : Any] = [
    NSAttributedString.Key.font: UIFont(name: Font.myFont.weights.regular, size: Font.sizes.navigationBarLargeTitle)!,
    NSAttributedString.Key.foregroundColor: UIColor(Color.text)
  ]

  var theme:UINavigationBarAppearance {
    let themedAppearance = UINavigationBarAppearance()
    themedAppearance.configureWithTransparentBackground()
    themedAppearance.backgroundColor = UIColor(Color.background)
    themedAppearance.backButtonAppearance = self.backButtonAppearance
    themedAppearance.largeTitleTextAttributes = self.largeTitleTextAttributes

    return themedAppearance
  }

  init() {
    UINavigationBar.appearance().standardAppearance = self.theme
    UINavigationBar.appearance().scrollEdgeAppearance = self.theme
    UINavigationBar.appearance().compactAppearance = self.theme
  }

  public func body(content: Content) -> some View {
    content
  }
}

How can I use a custom font in the NavigationBar without causing these scaling logs?

A: Not really an answer, but maybe helpful to anyone ending up here:
I was not able to solve the issue with the above themed ViewModifier. Instead I created a BackButton view and an accompanying .navigationBarBackButton() view modifier which I use when I want back functionality in the navigation bar.
The back buttton:
import SwiftUI

struct BackButton: View {
  @Environment(\.dismiss) var dismiss

  var body: some View {
    Button(action: {
      self.dismiss()
    }) {
      HStack {
        Text(Image(systemName: "chevron.backward"))
        Text("Back")
      }
      .font(myCustomFont)
      .foregroundColor(myCustomColor)
    }
  }
}

The view modifier:
// MARK: NavigationBar Back button
private struct NavigationBarBackButton:ViewModifier {
  public func body(content: Content) -> some View {
    content
      .navigationBarBackButtonHidden(true)
      .toolbar {
        ToolbarItem(id: "navigationBarBackButton", placement: .navigationBarLeading, showsByDefault: true) {
          BackButton()
        }
      }
  }
}

extension View {
  public func navigationBarBackButton() -> some View {
    self.modifier(NavigationBarBackButton())
  }
}

Example usage:
import SwiftUI

struct ContentView:View {
  var body: some View {
    NavigationView {
      ViewA()
        .navigationBarBackButton()
    }
  }
}


text:
Q: SSLContext Android Marshmallow not working So when in my manifest I speciay targetsdkversion 23 everything works normal, but when I specify targetsdkversion 23 I am unable to make api calls.I keep getting the following error.
10-28 09:09:40.462: I/System.out(13743): <title>Request Rejected</title>The requested URL was rejected. Please consult with your administrator.

Your support ID is: 12896453146718027503

So why does it work on 22, but on 23 i get that error. Here is my implementation.
public static SSLContext getSSL() {

    try {

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        AssetManager assetManager = BankNizwaApp.getAppContext()
                .getAssets();
        InputStream caInput = assetManager.open("cert.pem");
        java.security.cert.X509Certificate ca = null;
        try {
            ca = (java.security.cert.X509Certificate) cf
                    .generateCertificate(caInput);
            /*
             * System.out.println("BankNizwa: " +
             * ((java.security.cert.X509Certificate) ca) .getSubjectDN());
             */
        } catch (Exception er) {
             //System.out.println("BankNizwa: " + er.getMessage());
        } finally {
            caInput.close();
        }

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca",
                (java.security.cert.X509Certificate) ca);
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(tmfAlgorithm);
        tmf.init(keyStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e1) {
        // System.out.println("BankNizwaaaaa: "+e1.getMessage());
        return null;
    }
}

    HttpURLConnection conn = (HttpURLConnection) url2
                        .openConnection();
                conn.setReadTimeout(180000);

                    ((HttpsURLConnection) conn).setSSLSocketFactory(Common
                            .getSSL().getSocketFactory());
                conn.setConnectTimeout(180000);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // conn.setDoOutput(true);
                conn.setRequestProperty("Cache-Control", "no-cache");
                String sessionId = "JSESSIONID=" + Common.getAuthCode();
                conn.setRequestProperty("Cookie", sessionId);
                conn.setRequestProperty("User-Agent",
                        System.getProperty("http.agent"));


text:
Q: Firefox SVG graphics blurry I have a responsive web design with a SVG logo/image which is dynamic with its container. All major browsers seem to support SVG really good.
My SVG is dynamic, so if I scale up my browser window, the SVG does it too. In Chrome and IE9 it works like a charm. In Firefox the SVG is blurry at some sizes. But I can't say its all the time blurry when it's over the initial SVG size. It just seems not to rerender correctly all the time while I'm scaling up my browser window.
That's what it looks like sometimes (have a look at it in fullsize to see the difference):

Maybe I'm using the wrong way to embed it. That's what my CSS and HTML look like:

CSS:
#logo {
   background-image: url('http://dl.dropbox.com/u/569168/jess.svg');
   height: 22em;
   background-repeat: no-repeat;
   -webkit-background-size: 100%;
   -moz-background-size: 100%;
   -o-background-size: 100%;
   background-size: 100%;
}

Grab the SVG with the link in the CSS if you want to have a look at it. It's made with Adobe Illustrator.
Any idea how to fix that?

A: The problem is that when you use SVG as a background image Firefox chooses what size to render the vectors to, and then scales those image-based-pixels up as necessary. Here's a related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=600207
The simplest fix here is not to use SVG as a background image, but to embed your SVG directly, or reference it via an  tag.
If you put up a working test case showing the problem and files then we can help you with actual code and fixes.

A: To make an SVG image scale to the size of its container, make sure your svg tag has a viewBox set:
<svg viewBox="0 0 347 189">

but no width or height attributes, i e not:
<svg width="347px" height="189px" viewBox="0 0 347 189">

This, by default, will retain its aspect ratio by scaling up to the largest width or height that fits, whichever dimension hits the boundary first.
You can change preserveAspectRatio strategy in all sorts of interesting ways, if that particular behaviour isn't the one you seek.

A: Update 2013-10: Confirmed fixed in v24 which now made it into the release channel

Update 2013-07: Bug is solved! Fix will make it into Firefox 24 which will be released somewhere between September and October

I read about a somewhat simple solution to this problem somewhere that I now use in my projects (will add source when i find it again):
simply set width and height of the svg-container to the maximum values the image is likely going to have and you are fine. Works in all current browsers just fine. only restriction is, that firefox and opera (yes, the same two browsers that caused this mess) dont work well with very big images --> dont use too high values for the dimensions
original file:
<svg width="64px" height="128px">

lets say the maxium width will be 3x that big, then your SVG should contain this:
<svg width="192px" height="384px">

(yes, the svg node can have more attributes...)
The reason why this works is that Opera and FF render SVGs before resizing them instead of the other way round as it is supposed to be done with vector gfx
UPDATE: credits go to David Bushell who wrote a wonderfull article on Resolution Independence With SVG.

A: I've run into the exact same issue, myself. I was able to fix it in Firefox by editing the SVG in a text editor and changing the <svg> element's width attribute value to 100%, but leaving all other attribute values alone. In your particular example, here's the change to be made:
<svg version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
    x="0px"
    y="0px"
    width="100%"
    height="189px"
    viewBox="0 0 347 189"
    enable-background="new 0 0 347 189"
    xml:space="preserve">

That did the trick for me and should do the same for you; I can't be 100% without a test case to work with, though.
NB: Setting both the width and the height to 100% broke Safari's rendering of the SVG in my particular case. Be sure to only set the width to 100%.

A: The easiest solution is to scale up the SVG in a vector image editor like Illustrator. Scale it to the rendered resolution in the browser (or higher). Since it is a vector, scaling it up won't affect the file size.

A: Another similar "gotcha" I found was when I exported an svg from illustrator the width and heights weren't round numbers - so when I opened the SVG in an editor the width was something like "100.6789px". By carefully editing the image in illustrator first to be round numbers and then using the same width and height for firefox it solved fuzzy images for me.


text:
Q: Use Compute Shader to Process the Render Target I would like to use the Render Target as the input the Compute Shader in DirectX 11. I only need to read the Render Target in the Compute Shader, and in my case I do not have to render the Compute Shader output (although I do have to consume this in the CPU later, and may need to process it in additional Compute Shader passes.)
I have seen comments that this is possible, but I cannot seem to find any sample code that shows how to consume the render target (a Texture2D) as a Compute Shader Buffer in a Shader Resource View. I have tried a number of options, but have not been able to create the Shader Resource View that the Computer Shader needs as input.
A pointer to a fragment of sample code would be most appreciated.

A: Your resource needs to indeed have Shader resource usage mode to be readable via compute shader:
-For a standard render target : D3D11_BIND_SHADER_RESOURCE
-For a swap chain : DXGI_USAGE_SHADER_INPUT in swap chain description.
Then you just create a Shader Resource View as usual.
It is also possible (in some extents), to have your buffer also writeable directly by the compute shader. Flags is D3D11_BIND_UNORDERED_ACCESS or DXGI_USAGE_UNORDERED_ACCESS in that case (please note this doesn't work for multisampled textures tho).
Here is a very simple compute shader that reads samples from a texture from UV coords:
RWStructuredBuffer<float4> rwbuffer;

//Render target previously rendered
Texture2D tex;

//Buffer containing uvs for sampling
 StructuredBuffer<float2> uv <string uiname="UV Buffer";>;

 SamplerState mySampler : IMMUTABLE
 {
     Filter = MIN_MAG_MIP_LINEAR;
     AddressU = Clamp;
     AddressV = Clamp;
 };

 [numthreads(1, 1, 1)]
 void CS( uint3 i : SV_DispatchThreadID)
 {
//Read color and write to buffer
rwbuffer[i.x] = tex.SampleLevel(mySampler,uv[i.x],0);
 }

 technique11 Process
 {
pass P0
{
    SetComputeShader( CompileShader( cs_5_0, CS() ) );
}
 }

Hope that helps.

A: the first requirement to create a shader resource view from a texture is to create the texture with the good flags. The flag is D3D11_BIND_SHADER_RESOURCE. It has to be set in the decription binding member before calling CreateTexture2D.
If the render target is not create by you, but from the swap chain, you cannot bind it as an SRV. You will need an intermediate frame buffer and copy it to the back buffer at the end of the frame.


text:
Q: How to compile OpenCV 4.4 with FFmpeg for android? I'm trying to compile OpenCV-4.4 for android with FFmpeg support. I tried following this link. But the problem here is that the CMake scripts are entirely different. I searched on google a lot but could not find any link that resolves my issue. The problem that I'm facing is that when I run CMake script it does not find the FFmpeg libs that I have compiled. I think it is not even checking if the libs are available or not. I tried to modify the CMakeLists.txt in OpenCV but it did not resolve the issue. Is there any way to fix this?

A: Have you looked into one of these
https://jayrambhia.com/blog/ffmpeg-opencv-android
https://gist.github.com/jayrambhia/4ede34930c9a067ea3f8


text:
Q: spark executors running multiple copies of the same application In the spark documentation it says,

Each application gets its own executor processes, which stay up for the duration of the whole application and run tasks in multiple threads. This has the benefit of isolating applications from each other, on both the scheduling side (each driver schedules its own tasks) and executor side (tasks from different applications run in different JVMs). However, it also means that data cannot be shared across different Spark applications (instances of SparkContext) without writing it to an external storage system.

From the phrase

... executor side (tasks from different applications run in different
JVMs)

Does this mean that

*

*If you're running multiple copies(multiple spark-submits) of the same application in a cluster that has many executors, is it possible for an executor to run tasks that belong to different spark-submits in parallel?

*If the above is possible, using singleton objects that are shared between tasks of an executor, can cause data collisions between different copies(different spark-submits) of the same application?

A: Each executor is separate JVM process, and only used for one application. No need to worry about data collision.


text:
Q: Issue with awk statement while passing condition statement I am trying to count the null records of a column in a file, subject to a condition. But the condition is not working.

*

*Example input: fixed width file,

                 761128424607/22/20197611284246CAD052020DHH 0073578EKLAVY3
ELEKBAFXXL7900271761128424406/22/20197611284244CAD042020DKA 0038244EDITTU8
                 761128424606/22/20197611284246CAD052020DHH 0073578EKLAVY3
ELEKBAFXXL7900271761128424406/22/20197611284244CAD042020DKA 0038244EDITTU8

*

*code
RE='[[:space:]]{17}' awk -v m=1 -v p=17 -v r='&& substr($0,28,2)==06'
    $'BEGIN{re = ENVIRON["RE"]}{c = substr($0,m,p)}  c ~ "^(" re ")$" r  {N++}  END {print N+0}' <  input_file.txt

*Desired output: 1, since 2 records having null in file and out of this 1 record satisfies condition substr($0,28,2)==06

*Actual output: 0, which is wrong

A: This would do what you're asking for by letting the contents of the shell variable r expand to become part of the awk script before awk gets called to interpret it but there's almost certainly a better way to do whatever it is you're really trying to do:
$ r='&& substr($0,28,2)=="06"'
$ RE='[[:space:]]{17}' awk -v m=1 -v p=17 '
    BEGIN { re = ENVIRON["RE"] }
    { c = substr($0,m,p) }
    c ~ "^(" re ")$" '"$r"' { N++ }
    END { print N+0 }
' file
1

If you have to write && substr($0,28,2)=="06" somewhere though, then it's not at all obvious why you wouldn't just write it in the awk script instead of in a shell variable - whatever you're trying to do, there's got to be a better way.

A: awk ... r='&& substr($0,28,2)==06'
    '... c ~ "^(" re ")$" r  { ... } '

This looks like you're trying to use an awk variable to build the condition on the fly? That is, to use the contents of the awk variable r as part of awk syntax.
I don't think that can work. In awk, back to back values are taken as string concatenation, so that turns into something like c ~ "^(" re ")$&& substr($0,28,2)==06", i.e. it would take the contents of r as part of the regex to match against.
E.g. awk -v var=bar  '$0 ~ "foo" var' would print lines containing foobar, and it works similarly even if the variable contains && or such.
It probably won't work anywhere near that in any other programming language either, since separation between code and data is pretty much a requirement for sane and safe programs. It doesn't work like that even in the shell. (Without eval or such.)
Just write the whole expression out in full.

A: With some changes you can get it to output expected results:
RE='[^[:space:]]' awk -v m=1 -v p=17 \
$'(r=substr($0,28,2)=="06")&&
(substr($0,m,p) !~ re) {N++}
BEGIN {re = ENVIRON["RE"]}
END {print N+0}' < input_file.txt

Edits:-

*

*Convert the awk variable r declared on the commandline to be inside the $'...' code block.

*Remove the &&, turning it to a boolean.

*stick the && between the c ~ ... and r boolean conditions.

*Change the numeric comparison ==06 to a string comparison =="06"

A: With GNU awk, you can use the FIELDWIDTHS variable to specify the widths of fixed width fields:
gawk '($1!~/[^ ]/) && ($3=="06"){++c} END{print c+0}' FIELDWIDTHS='17 10 2 *' file

You could try to parameterise the awk script – some attempts at that:
str=06 gawk -v FIELDWIDTHS='17 10 2 *' '
  ($1 !~ /[^ ]/) && ($3"" == ENVIRON["str"]) {
      ++c
  }
  END {print c+0}
' file

str=06 rexp='^ {17}$' gawk -v FIELDWIDTHS='17 10 2 *' -v rexp_col=1 -v str_col=3 '
  ($rexp_col ~ ENVIRON["rexp"]) && ($str_col"" == ENVIRON["str"]) {
      ++c
  }
  END {print c+0}
' file


text:
Q: Sharepoint's "New Folder" doesn't ask for a required field I am using Web Part Connections to filter documents in a documents library in SharePoint. To do this, there's a column that is required, which I've named "related contact." Here's my problem: When I go add a New Folder (instead of just a document) SharePoint only asks me for a title for the Folder. The "related contact" column (which is required for the documents) doesn't even appear. Since the info on that column is empty, web part connections doesn't see the folder at all. Is there any way to make the Folder ask for another field at the time of creation?
Thanks
-V

A: Did you try creating a new folder content type with those required fields and trying to use that (and perhaps turn off the standard folders)?
Perhaps this page will help you: SharePoint folders and metadata.

A: Folders are one-dimensional.  They are virtual containers for your documents, but aren't objects in your library that contain actual metadata.
Instead of using folders, I would recommend adding a column to your library that would mimic the names of the folders.  From there, you can sort/filter/group/query the contents of that library.  If users are sticklers for the folder structure, you could create a View that groups the documents by that new column, which would give you the appearance of folders.


text:
Q: adding a UUID4 ID to each row in Pentaho I am inserting the result of a SELECT statement from a relational table into another table using Pentaho, is it possible to add a UUID4 identifier to each row and then insert.
Data before insertion :
ip              country city    start_time
1.7411624393E10 Canada  London  2017-06-01 15:27:23
1.7411221531E10 Canada  Ottawa  2017-06-02 23:57:56
1.846525287E9   Canada  Langley 2017-06-02 22:27:29
2.0647254234E10 Canada  Toronto 2017-06-02 22:22:49
2.0647254234E10 Canada  Toronto 2017-06-02 22:22:12
2.0647254234E10 Canada  Toronto 2017-06-02 22:21:20

Needed as :
UUID ip             country city    start_time
ID1  1.7411624393E10    Canada  London  2017-06-01 15:27:23
ID2  1.7411221531E10    Canada  Ottawa  2017-06-02 23:57:56
ID3  1.846525287E9      Canada  Langley 2017-06-02 22:27:29
ID4  2.0647254234E10    Canada  Toronto 2017-06-02 22:22:49
ID5  2.0647254234E10    Canada  Toronto 2017-06-02 22:22:12
ID6  2.0647254234E10    Canada  Toronto 2017-06-02 22:21:20

I am able to generate one UUID4 ID using random generator for all the records, but I need to generate ofcourse separate UUIDs for all the rows.

A: You can use "Generate random value" step to create a column with a type "Universally Unique Identifier type 4(UUID4)".


text:
Q: UIViewController shouldAutorotateToInterfaceOrientation - would like to add hysteresis I would like to defer auto rotating the user interface until the device has settled on an orientation for a number of seconds, rather than driving the user insane and flicking willy nilly whenever they tilt the device a few degrees off axis by mistake.
the closest i can get to this (which is by no means what I want, as it locks the UI) is:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.

    [NSThread sleepForTimeInterval:2.0];
    return YES;
}

what i would like to do is use something like this - which works in principle, by checking the console log, but i need the appropriate line of code that has been commented out.
-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer {
    autoRotationTimer = nil;

    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)[timer.userInfo integerValue];

    NSLog(@"switching to new orientation %d now",interfaceOrientation);

    // replace this with code to induce manual orientation switch here.
    //[self forceAutoRotateToInterfaceOrientation:interfaceOrientation];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    [autoRotationTimer invalidate];

    autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
                                   selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];

    NSLog(@"denying autorotate, deffering switch to orientation %d by 2 seconds",interfaceOrientation);

    return NO;
}

I realize there are sometimes many ways to do things, so if this approach is not the most efficient, and someone can suggest another way to do this, I am all ears. My main criteria is I want to delay the onset of autorotation, whilst keeping a responsive user interface if indeed they have only leaned to the left slightly because they are in a bus that just went around a corner etc.
EDIT: I found a solution which may not be app store friendly, however i am a few weeks away from completion, and someone may answer this in the meantime. this works calls an undocumented method. the (UIPrintInfoOrientation) typecast is just to suppress the compiler warning, and does not affect the value being passed.
-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
    [(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}

full implementation which includes re-entrance negation is as follows:
- (void)viewDidLoad {
    [super viewDidLoad];
    acceptNewAutoRotation = YES;
}

-(void ) forceUIOrientationInterfaceOrientation:(UIDeviceOrientation) interfaceMode {
    [(id)[UIDevice currentDevice] setOrientation:(UIPrintInfoOrientation) interfaceMode];
}

-(void) deferredAutorotateToInterfaceOrientation:(NSTimer *) timer {
    autoRotationTimer = nil;

    acceptNewAutoRotation = YES;

    [self forceUIOrientationInterfaceOrientation:[[UIDevice currentDevice] orientation]];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    [autoRotationTimer invalidate];

    if (acceptNewAutoRotation) {
        autoRotationTimer = nil;
         acceptNewAutoRotation = NO;
        return YES;
    } else {

        autoRotationTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self
                                                           selector:@selector(deferredAutorotateToInterfaceOrientation:) userInfo:[NSNumber numberWithInt:(int)interfaceOrientation ] repeats:NO];

        return  NO;
    }

}

A: To do this with public APIs, you probably would have to forget about autorotation, and do all your own view transforms manually based on filtered (not just delayed!) accelerometer input.

A: I have not tested this and it may not work at all but you can try this out:
start out self.rotate = NO; then:
- (void)shouldRotateTo:(UIInteraceOrientation *)interfaceOrientation {
    self.rotate = YES;
    // or test interfaceOrientation and assign accordingly.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    bool rot = self.rotate;
    self.rotate = NO
    [self performSelector:selector(shouldRotateTo:) withObject:[NSNumber numberWithInt:interfaceOrientation] afterDelay:2.0];
    return rot;
}

Parameter interfaceOrientation is an enum (UIInteraceOrientation) so wrap it in an NSNumber when passing.


text:
Q: FCfield Attribut error while sniffing packets using Scapy I tried to sniff DNS request packets on mon0 interface, using scapy.
I wanted to send back a spoofed IP.
But I get an error:

AttributeError: 'Ether' object has no attribute 'FCfield'

Code:
def send_response(x):
x.show()
req_domain = x[DNS].qd.qname
logger.info('Found request for ' + req_domain)
# First, we delete the existing lengths and checksums..
# We will let Scapy re-create them
del(x[UDP].len)
del(x[UDP].chksum)
del(x[IP].len)
del(x[IP].chksum)
response = x.copy()
response.FCfield = '2L'

response.addr1, response.addr2 = x.addr2, x.addr1
# Switch the IP addresses
response.src, response.dst = x.dst, x.src
# Switch the ports
response.sport, response.dport = x.dport, x.sport
# Set the DNS flags
response[DNS].qr = '1L'
response[DNS].ra = '1L'
response[DNS].ancount = 1

response[DNS].an = DNSRR(
    rrname = req_domain,
    type = 'A',
    rclass = 'IN',
    ttl = 900,
    rdata = spoofed_ip
    )
#inject the response
sendp(response)
logger.info('Sent response: ' + req_domain + ' -> ' + spoofed_ip + '\n')

def main():
    logger.info('Starting to intercept [CTRL+C to stop]')
    sniff(prn=lambda x: send_response(x), lfilter=lambda x:x.haslayer(UDP) and x.dport == 53)

A: Your interface is probably not configured in monitor mode, that's why you get an ethernet (Ether) layer, and not a WiFi (Dot11) layer.


text:
Q: I have an error with my php trigger#1064 -check the manual that corresponds to your MySQL server version for the right syntax to use near '' I have written Upate trigger on user in trigger I written Update query to update login table
CREATE trigger auou AFTER update ON  `user`
FOR each
ROW
BEGIN
update login
set `user`='new.user_id',`password`='new.password'
where  `user`='new.user_id';


text:
Q: Botão voltar do navegador apagar uma classe Estou fazendo um site que funciona em uma página única. Então quando clico em um botão do menu ele rola até a área que quero com:
$('html, body').animate({scrollTop: $('#nomedoid').offset().top},Math.abs(0));

E ao mesmo tempo coloco o window.history.pushState:
window.history.pushState(null, 'blablabla', 'link');

Funciona como eu esperava, se eu clicar no botão voltar do navegador (ou celular) o site volta pra última "página" do site, inclusive rolando (scroll) pra ela.
O PROBLEMA: Existe agora uma "página" que abre sobre o site, entra uma div na frente  do site com addClass e também dou o window.history.pushState:
$('.frente_site').addClass('frente_site_aparece');
window.history.pushState(null, 'blablabla', 'link-frente');

Aí se dou um voltar no navegador a URL até muda, mas ele não da o removeClass na class '.frente_site'. Teria como fazer isso acontecer? Estou fazendo da forma errada?

A: Acabei descobrindo uma forma, se não for a ideal me avisem!
Usei essa função:
window.onpopstate = function (event) {
    if(qualLink == 'perfil'){
        // faz algo
    }
}

Só alimento a variável qualLink toda vez que mudo a URL e depois verifico ela com o onpopstate.


text:
Q: WPF Aero theme standard styles When using the Aero theme, are there resource names for styles that I can hook in to to achieve the same appearance as standard Win7 apps:

In other words, are there already well-known style names for TextBlocks (and other controls) that would let me achieve a similar appearance to what is in the image above?
In XAML it would look something like this:
<TextBlock Style="{DynamicResource WindowsHeading}" />

A: "Windows Vista User Experience Guidelines Aero Theme Aesthetics"
That's AFAIK all there is.


text:
Q: Including laravel 5 packages in lumen Im currently trying to include illuminate/filesystem into lumen
So far I have managed to install the package running the following command:
composer require Illuminate/Filesystem

However I have no idea how to register the static class inside the application, I can't seem to find anything on the internet which talks about how to implement laravel 5 packages into lumen.
I have tried adding a class alias to the core of lumen, but this seems wrong to me.

A: There's nothing wrong with registering a class alias for the File facade, just don't do it in the framework source files (within the vendor directory). A good place to put that is inside the bootstrap/app.php file. Just add this and you're good to go:
class_alias('Illuminate\Support\Facades\File', 'File');

No additional packages need to be installed for this to work because Illuminate/Filesystem already comes with Lumen.


text:
Q: Django decorator @permission_required I'm new to Django. I'll be appreciate if anyone can help me.
When I was trying to use the decorator @permission_required in a view in Django, it always told that my app name is not defined.
I put this before a view in
request/views.py:
@permission_required(request.change_part_status)

and got this error

NameError: name 'request' is not defined

Do I have to import something or is there something I missed?


text:
Q: insertar varios registros a la vez en mysql desde android studio Hola a toda la comunidad, por favor su apoyo con el siguiente caso, tengo que enviar los siguientes registros a través de un app a una tabla en phpMyAdmin:

Este es el código del activity que utilizo para ingresar los registros:
package com.example.appgloria;

public class Registro extends AppCompatActivity {

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

    final EditText clienteT          = EditText)findViewById(R.id.clienteRegistro);
    final EditText direccionT        = (EditText)findViewById(R.id.direcionRegistro);
    final TextView productoT         = (TextView)findViewById(R.id.producto1);
    final EditText compraT           = (EditText)findViewById(R.id.ETPC);
    final EditText ventaT            = (EditText)findViewById(R.id.ETPV);
    Button btnRegistro = (Button)findViewById(R.id.btnRegistro);

    btnRegistro.setOnClickListener(new View.OnClickListener() {
        @Override
        //esto va en registro request
        public void onClick(View view) {
            final  String cliente       = clienteT.getText().toString();
            final  String direccion     = direccionT.getText().toString();
            final  String producto      = productoT.getText().toString();
            final  String compra        = compraT.getText().toString();
            final  String venta         = ventaT.getText().toString();

            Response.Listener<String> respuesta = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try{
                        JSONObject jsonrespuesta = new JSONObject(response);
                        boolean ok = jsonrespuesta.getBoolean("success");
                        if(ok == true){
                            Intent i = new Intent(Registro.this,Final.class);
                            Registro.this.startActivity(i);
                            Registro.this.finish();
                        }else{
                            AlertDialog.Builder alerta = new AlertDialog.Builder(Registro.this);
                            alerta.setMessage("Fallo en el registro")
                                    .setNegativeButton("Reintentar",null)
                                    .create()
                                    .show();
                        }
                    }catch (JSONException e){
                        e.getMessage();
                    }
                }
            };

            RegistroRequest r = new RegistroRequest(cliente,direccion,producto,compra,venta,respuesta);
            RequestQueue cola = Volley.newRequestQueue(Registro.this);
            cola.add(r);
        }
    });
}
}

Y este es el código del Activity que envía la información:
package com.example.appgloria;

public class Bienvenido extends AppCompatActivity {

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

    final TextView mensaje = (TextView)findViewById(R.id.mensaje);

    Intent i = this.getIntent();
    String nombre = i.getStringExtra("nombre");
    int edad = i.getIntExtra("edad",-1);
    mensaje.setText(mensaje.getText()+" "+nombre+" Su edad:"+edad+"");
}

//Metodo para para pasar de bienvenido a registro
public void levantamiento_de_precios(View view){
    Intent levantamiento_de_precios = new Intent(this,Registro.class);
    startActivity(levantamiento_de_precios);
}

//Metodo para para pasar de bienvenido a asistencia
public void asistencia(View view){
    Intent asistencia = new Intent(this,Asistencia.class);
    startActivity(asistencia);
}

//Metodo para para pasar de bienvenido a visitas
public void visitas(View view){
    Intent visitas = new Intent(this,Visitas.class);
    startActivity(visitas);
}
}

A continuación el archivo php que utilizo para insertar los datos a la tabla que se encuentra en phpMyAdmin:
<?php
$con = mysqli_connect("localhost", "id9055504_root", "root123", "id9055504_bdgloria");

$cliente        = $_POST["cliente"];
$direccion      = $_POST["direccion"];
$producto       = $_POST["producto"];
$compra         = $_POST["compra"];
$venta          = $_POST["venta"];
$statement = mysqli_prepare($con, "INSERT INTO precios (cliente, direccion, producto, compra, venta) VALUES (?,?,?,?,?)");
mysqli_stmt_bind_param($statement, "sssss", $cliente, $direccion, $producto, $compra, $venta);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>

Por favor me podrían enseñar que debo de modificar en mis códigos para poder insertar todos los registros al mismo tiempo. Les estoy muy agradecido de antemano. Muchas gracias.


text:
Q: Python script to convert complicated flattened data to JSON Sorry about the vague title, I need some help with Python magic and couldn't think of anything more descriptive.
I have a fixed JSON data structure that I need to convert a CSV file to. The structure is fixed, but deeply nested with lists and such. It's similar to this but more complicated:
{
    "foo" : bar,
    "baz" : qux,
    "nub" : [
        {
            "bub": "gob",
            "nab": [
                {
                    "nip": "jus",
                    "the": "tip",
                },
                ...
            ],
        },
        ...
    ],
    "cok": "hed"
}

Hopefully you get the idea. Lists on dicts on lists on lists and so forth. My csv for that might look like this:
foo, baz, nub.bub, nub.nab.nip, nub.nab.the, cok

bar, qux, "gob" ,,,, "hed"

,,,,, "nab", "jus","tip",,

,,,,, "nab", "other", "values",,

Sorry if this is hard to read, but the basic idea is if there's a listed item it will be in the next row, and values are repeated to denote what sub-lists belong to what.
I'm not looking for anyone to come up with a solution to this mess, just maybe some pointers on techniques or things to look into.
Right now I have a rough plan:
I start by turning the header into a list of tuples containing the keys. For each group of rows (item) I'll create a copy of my template dict. I have a function that will set a dict value from a tuple of keys, unless it finds a list. In this case I'm going to call a funky recursive function and pass it my iterator, and continue filling up the dict in that function, and making recursive calls as I find new lists.
I could also do a lot of hardcoding, but what's the fun in that?
So that's my story. Again, just looking for some pointers on what the best way to do this might be. I wrote this quickly so it might be kinda confusing, please let me know if any more info would help. Thanks!

A: Your JSON is malformed. Additionally, your json must not contain arrays in order to achieve what you want.
def _tocsv(obj, base=''):
    flat_dict = {}
    for k in obj:
        value = obj[k]
        if isinstance(value, dict):
            flat_dict.update(_tocsv(value, base + k + '.'))
        elif isinstance(value, (int, long, str, unicode, float, bool)):
            flat_dict[base + k] = value
        else:
            raise ValueError("Can't serialize value of type "+ type(value).__name__)
    return flat_dict

def tocsv(json_content):
    #assume you imported json
    value = json.loads(json_content)
    if isinstance(value, dict):
        return _tocsv(value)
    else:
        raise ValueError("JSON root object must be a hash")

will let you flatten something like:
{
    foo: "nestor",
    bar: "kirchner",
    baz: {
        clorch: 1,
        narf: 2,
        peep: {
            ooo: "you suck"
        }
    }
}

into something like:
{"foo": "nestor", "bar": "kirchner", "baz.clorch": 1, "baz.narf": 2, "baz.peep.ooo": "you suck"}

the keys don't preserve any specific order. you can replace flat_dict = {} with the construction of an OrderedDict if you want to preserve order.
assuming you have an array of such flat dicts:
def tocsv_many(json_str):
    #assume you imported json
    value = json.loads(json_content)
    result = []
    if isinstance(value, list):
        for element in value:
            if isinstance(element, dict):
                result.append(_tocsv(element))
            else:
                raise ValueError("root children must be dicts")
    else:
        raise ValueError("The JSON root must be a list")
flat_dicts = tocsv_many(yourJsonInput)

you could:

*

*create a csvlines = [] list which will hold the csv lines for ur file.

*create a keysSet = set() which will hold the possible keys.

*for each dict you have in this way, add the .keys() to the set. no key order is guaranteed with a normal set; use a sorted set instead. Finally we get the first CSV line.
 for flat_dict in flat_dicts:
     keysSet.extend(flat_dict.keys())
 csvlines.appens(",".join(keysSet))

*for each dict you have (iterate again), you generate an array like this:
 for flat_dict in flat_dicts:
     csvline = ",".join([json.dumps(flat_dict.get(keyInSet, '')) for keyInSet in keysSet])
     csvlines.append(csvline)

*voilah! you have your lines in csvlines


text:
Q: When using boost::asio LNK 2001 (Release) I'm developing chat server (name is PengChat) and it is main source code.
(CServerSocket.h is included boost/asio.hpp) and there are two errors.
1>main.obj : error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::system_category(void)" (?system_category@system@boost@@YAABVerror_category@12@XZ)
1>main.obj : error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::generic_category(void)" (?generic_category@system@boost@@YAABVerror_category@12@XZ)

My environment is

*

*OS - Windows 8 Pro K (I'm Korean)

*IDE - Visual Studio 2012

*Properties → Code Generator → Runtime Library - Multi Thread (/MT) (in release)

Do you know about these errors?
Please help me.
Thanks.
PS. In debug mode (using /MTd option). it is compiled well. but in release mode (using /MT option), there are two errors.
PS2. I can't use Ctrl+K, it is strange; please look comment window
EDIT
Source code for application is as follows:
#include <stdio.h>
#include <memory>
#include "../PengChatServerLib/CServerSocket.h"

#ifdef _MSC_VER
    #ifdef _DEBUG
        #pragma comment(lib, "../Debug/PengChatServerLib")
    #else
        #pragma comment(lib, "../Release/PengChatServerLib")
    #endif
#endif

int main()
{
    boost::asio::io_service iosrv;

    std::unique_ptr<PengChat::CServerSocket> pSock(new PengChat::CServerSocket(iosrv, 8888));

    getchar();

    pSock.reset();

    return 0;
}


text:
Q: Why can't I get my moderncv to compile? - unrecognized command (tex editor) I have moved to windows 10 from arch linux. I am now attempting to use MiKTeX and TexStudio to alter an existing CV. I have added the package entitled moderncv within the MiKTeX Console. However when I open my existing moderncv CV to edit it in TexEditor, I have multiple compilation errors around \cvline; my compiler (MiKTeX) claims it doesn't recognise the command. Please help.

A: It seems that your existing CV is a little bit old. Command \cvline is not longer used in current class moderncv 2.0.0, it uses now \cvitem.
With installing package moderncv via MiKTeX Console you got the current version 2.0.0 installed. Now you have to check the examples for moderncv 2.0.0 to use the correct new commands for layouting your cv.  Be aware that several commands changed their names, you have to correct all of them. If you can not do that by your own, copy your cv to file mwe.tex, delete your personal informations from your new file and post it in your question. Then I can compile it and tell you the incorrect commands used ...
Without seeing your cv tex code I can not help you more ...


text:
Q: How to open another tab (fragment) if today a specific day? I am developing an app with fragment tabs, and I want to open another tab, when the activity is started. If today is Monday - open first tab, if today is Tuesday open second tab and etc. How I can do that?
My fragmentactivity.java:
public class FragmentActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    SharedPreferences sp;

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

        sp = PreferenceManager.getDefaultSharedPreferences(this);
        String select_class = sp.getString("select_class", "");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new MondayFragment(), "ПН");
        adapter.addFragment(new TuesdayFragment(), "ВТ");
        adapter.addFragment(new WednesdayFragment(), "СР");
        adapter.addFragment(new ThursdayFragment(), "ЧТ");
        adapter.addFragment(new FridayFragment(), "ПТ");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

A: First, get the day of the week using Calendar:
Calendar c = Calendar.getInstance();
int date = c.get(Calendar.DAY_OF_WEEK);

Now, for determining which tab to open, it is easiest done with a switch. You can either say case Calendar.SUNDAY:, or case 1:. They are both the same, but Calendar.SUNDAY is easier because you don't need to know the numbers of the days
switch(date){

case Calendar.SUNDAY:
    //create tab
    break;

case Calendar.MONDAY:
    //create tab
    break;
and so on...

}

This is a simple way to get the day and create tabs based on input. The best way to call this code is to call it when the app is opened, and you should check if it has been called before if you only want it to call once. For that purpose, save the value that checks if you have opened the "tab of the day" before.
Checking if you have opened the tab before
There are 4 different options for saving values as of writing this answer:
Internal/external
SQLite
Shared preferences
Day numbers:
Copied from the Calendar class. No need to add these lines to your project:
/**
* Value of the {@code DAY_OF_WEEK} field indicating Sunday.
*/
public static final int SUNDAY = 1;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Monday.
 */
public static final int MONDAY = 2;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Tuesday.
 */
public static final int TUESDAY = 3;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Wednesday.
 */
public static final int WEDNESDAY = 4;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Thursday.
 */
public static final int THURSDAY = 5;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Friday.
 */
public static final int FRIDAY = 6;

/**
 * Value of the {@code DAY_OF_WEEK} field indicating Saturday.
 */
public static final int SATURDAY = 7;

A: try viewpager.setCurrentItem(index)

A: To find the current day of the week and select a particular tab accordingly:
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);

switch (day) {
    case Calendar.SUNDAY:
        viewPager.setCurrentItem(0);

    case Calendar.MONDAY:
        viewPager.setCurrentItem(1);

    case Calendar.TUESDAY:
        viewPager.setCurrentItem(2);
        ...
        ... //etc
}


text:
Q: How can I get the row view of data read from parquet file? Example: Let's say a table name user has id, name, email, phone, and is_active as attributes. And there are 1000s of users part of this table. I would like to read the details per user.
void ParquetReaderPlus::read_next_row(long row_group_index, long local_row_num)
{
    std::vector<int> columns_to_tabulate(this->total_row);
    for (int idx = 0; idx < this->total_row; idx++)
        columns_to_tabulate[idx] = idx;

    this->file_reader->set_num_threads(4);
    int rg = this->total_row_group;

    // Read into table as row group rather than the whole Parquet file.
    std::shared_ptr<arrow::Table> table;
    this->file_reader->ReadRowGroup(row_group_index, columns_to_tabulate, &table);
    auto rows = table->num_rows();
    //TODO
    // Now I am confused how to proceed from here
}

Any suggestions?
I am confused if converting the ColumnarTableToVector will work?

A: It's difficult to answer this question without knowing what you plan on doing with those details.  A Table has a list of columns and each column (in Arrow-C++) has a type-agnostic array of data.  Since the columns are type-agnostic there is not much you can do with them other than get the count and access the underlying bytes.
If you want to interact with the values then you will either need to know the type of a column ahead of time (and cast), have a series of different actions for each different type of data you might encounter (switch case plus cast), or interact with the values as buffers of bytes.  One could probably write a complete answer for all three of those options.
You might want to read up a bit on the Arrow compute API (https://arrow.apache.org/docs/cpp/compute.html although the documentation is a bit sparse for C++).  This API allows you to perform some common operations on your data (somewhat) regardless of type.  For example, I see the word "tabulate" in your code snippet.  If you wanted to sum up the values in a column then you could use the "sum" function in the compute API.  This function follows the "have a series of different actions for each different type of data you might encounter" advice above and will allow you to sum up any numeric column.

A: As far as I know what you are trying to do isn't easy. You'd have to:

*

*iterate through each row

*iterate through each column

*figure out the type of the column

*cast the arrow::Array of the column to the underlying type (eg: arrow::StringArray)

*get the value for that column, convert it to string and append it to your output

This is further complciated by:

*

*the fact that the rows are grouped in chunked (so iterating through rows isn't as simple)

*you also need to deal with list and struct types.

It's not impossible, it's a lot of code (but you'd only have to write it once).
Another option is to write that table to CSV in memory and print it:
arrow::Status dumpTable(const std::shared_ptr<arrow::Table>& table) {
  auto outputResult = arrow::io::BufferOutputStream::Create();
  ARROW_RETURN_NOT_OK(outputResult.status());
  std::shared_ptr<arrow::io::BufferOutputStream> output = outputResult.ValueOrDie();
  ARROW_RETURN_NOT_OK(arrow::csv::WriteCSV(*table, arrow::csv::WriteOptions::Defaults(), output.get()));
  auto finishResult = output->Finish();
  ARROW_RETURN_NOT_OK(finishResult.status());
  std::cout << finishResult.ValueOrDie()->ToString();
  return arrow::Status::OK();
}


text:
Q: How to check if my build version is above x.x.x in perl I'm  trying to check if my etcd version is above 3.4.0 or not
Below is the command I use to fetch the version
podman exec -it etcd-pod-etcd etcdctl version
The final output from the above command will be in string format
$output = '3.4.15'
I tried to validate the version in the following way $output =~ 3.4
But the problem here is if the version changes to 3.5.x I will have to change my script again.
What is the best way to check if the version is above 3.4.x? Is there any modules in Perl to do the following?

A: Perl's version objects and version pragma make it trivial:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010; # This needs at least 5.10, which hopefully isn't an issue these days
use feature qw/say/;
use version 0.77;

my $vers = version->parse('3.4.15');
if ($vers > v3.4.0) {
    say "Version $vers is new enough.";
} else {
    say "Version $vers is too old. You need to upgrade.";
}


text:
Q: like operator in ngresource of angularjs I use Loopback with node to query MongoDB via ngresource of AngularJS.
I wish to implement autocomplete.
Product is my ngResource
Product.find({filter:{where:{name:'search string'}, limit:10}})

The above code only search for 'search string' (Not all matching elements)
Like
'search string2'
'search string1'
'search string3'

How to search equivalent to mongoDB's
db.Product.find({name:/.*search string*/});

A: You need to use the like operator in your query filter object :
{filter:
  where: {myField: {like: '.*search string.*'}}
}

And that will do the trick.


text:
Q: How does top (Activity Monitor) update memory usage as the heap is written to? (C) My friend implemented a dynamic array to learn C. When out of allocated memory, he doubles the allocated space.
We watched his test program write 4 GB of random characters (to avoid memory compression), char by char. But the Activity Monitor (on Mac, based on top) showed memory usage increasing gradually, not doubling on each extend.
Yet on deletion/compaction, memory usage would drop immediately and exactly as the code would free memory.
How does top track "actual" memory used within an allocated range? And why would it do this, if the rest of the allocated space isn't available for use by other processes anyway?

A: Most modern operating systems allocate real memory lazily, only providing the memory when an attempt is made to use it. You can increase the heap as much as you want without using any memory at all; the only effect is to allocate virtual memory addresses.
Only when you actually touch a page, for example by writing to it, is the memory actually given to the process.
One of the consequences is that malloc() can succeed even if no physical memory is available.
If you actually use top you will see both the virtual memory allocation (which is only an allocation of virtual addresses) and the memory actually in use (the "resident set").


text:
Q: Convert CSV to Gridded Binary I am trying to convert a CSV text file with three columns and 572 rows to a gridded binary file (.bin) using gfortran.
I have two Fortran programs that I have written to achieve this.
The issue is that my binary file size is ending up way too large (9.6GB) by the end, which is not correct.
I have a sneaking suspicion that my nx and ny values in ascii2grd.90 are not correct and that is leading to the bad .bin file being created. With such a small list (only 572 rows), I am expecting the final .bin to be more in KBs, not GBs.
temp.90
!PROGRAM TO CONVERT ASCII TO GRD
program gridded
real lon(572),lat(572),temp(572)
open(2,file='/home/weather/data/file')
open(3,file='/home/weather/out.dat')
 do 20 i=1,572
 read(2,*)lat(i),lon(i),temp(i)
 write(3,*)temp(i)
20 continue

stop
end

ascii2grd.f90
!PROGRAM TO CONVERT ASCII TO GRD
program ascii2grd
parameter(nx=26,ny=22,np=1)
real u(nx,ny,np),temp1(nx,ny)

integer :: reclen
inquire(iolength=reclen)a

open(12,file='/home/weather/test.bin',&
form='unformatted',access='direct',recl=nx*ny*reclen)
open(11,file='/home/weather/out.dat')

 do k=1,np
 read(11,*)((u(j,i,k),j=1,nx),i=1,ny)
10  continue
 enddo

 rec=1
 do kk=1,np
 write(12,rec=irec)((u(j,i,kk),j=1,nx),i=1,ny)
 write(*,*)'Processing...'
irec=irec+1
 enddo
 write(*,*)'Finished'

stop
end

Sample from out.dat
6.90000010
15.1999998
21.2999992
999.000000
6.50000000
10.1000004
999.000000
18.0000000
999.000000
20.1000004
15.6000004
8.30000019
9.89999962
999.000000

Sample from file
-69.93500 43.90028 6.9
-69.79722 44.32056 15.2
-69.71076 43.96401 21.3
-69.68333 44.53333 999.00000
-69.55380 45.46462 6.5
-69.53333 46.61667 10.1
-69.1 44.06667 999.00000
-68.81861 44.79722 18.0
-68.69194 45.64778 999.00000
-68.36667 44.45 20.1
-68.30722 47.28500 15.6
-68.05 46.68333 8.3
-68.01333 46.86722 9.9
-67.79194 46.12306 999.00000

A: I would suggest a general strategy like the following:

*

*Read the CSV with python/pandas (it could be many other things, although using python will be nice for step 2, as you'll see).  But the important thing is that many other languages are more convenient than fortran for reading a CSV, and that will allow you to check that that step 1 is working before moving on.

*Output to binary with numpy's tofile().  Also note that numpy will default to 'c' order for arrays so you may need to specify 'f' (fortran) order.
I have a utility at github called dataset2binary that automates this and may be of interest to you, or you could refer to the code at this answer.    That is probably overkill though, because you seem to just be reading one big array of the same datatype.  Nevertheless, the code you'd want will be similar, just simpler.


text: Q: how to evaluate rendering performance of d3 I'm using d3 for 3rd party visualization solution. And I'm wondering is there anyway to evaluate the rendering performance of d3? I'm rending about 500 gauges at the same time. And it's rendering within 100ms. But is there any way to use the numbers to evaluate this performance?


text:
Q: Prestashop 1.7 Customer Order history cart problem I have a problem with PrestaShop 1.7 order history page. My last ordered items is loaded in shopping cart but this happens only in the customer order history page.
Thanks.