问:
RegEx for replacing capture group content using sed
Have inputs.conf files in multiple directories that needs to match and parse each stanza and modify the index= to index=secure.
This are files type in inputs.conf and also do run the script to locate the inputs file in this dir (_GWAS_pr_linux_t1/local/inputs.conf) to modify the index</p>

```<code>[monitor:///var/log/messages]
index=BDBD_np
sourcetype=syslog

[monitor:///var/log/cron]
index=NDNW_np
sourcetype=syslog

[monitor:///var/log/maillog]
index=BSKX_np
sourcetype=syslog

[monitor:///var/log/secure]
index=NDNDK_np
sourcetype=syslog

[monitor:///var/log/spooler]
index=DNWN_np
sourcetype=syslog

[monitor:///var/log/audit/audit.log]
index=XBJB_np
sourcetype=syslog

    sed -i -e 's/.*(?s)((\[monitor\:\/\/\/var\/log\/messages|secure\]).*?)(?:(?:\r*\n){2})' /index=secure *linux*/local/inputs.conf

############################
match each stanza and modify index name to index=windows
inputs file in this dir (_GWAS_pr_window_t1/local/inputs.conf)

    [WinEventLog://Application]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Security]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://System]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://ForwardedEvents]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Setup]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    sed -i -e 's/.*(?s)((\[WinEventLog:\/\/Application|Security|System|ForwardedEvents|Setup\]).*?)(?:(?:\r\n){2}) /index=window *window*/local/inputs.conf
</code>```

答:
Instead of using sed which reads line by line, you might use perl with the -0 mode. You could capture for example this part in group 1:

```<code>[monitor:///var/log/messages]
sourcetype=linux
index=
</code>```

Followed by matching power afterwards.

Then in the replacement you could referer to group 1 and add secure $1secure so that will replace the matched power.

```<code>(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power
</code>```

Regex demo

```<code>perl -0p -i.bak -e 's#(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power#$1secure#g' inputs.conf
</code>```

Result:

```<code>[monitor:///var/log/messages]
sourcetype=linux
index=secure
</code>```

Update

If you want to match any of the listed words from the comments and replace those with what comes after index, you could use 2 capturing groups:

```<code>perl -0p -i.bak -e 's#(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*#$1$2#g' inputs.conf
</code>```

Pattern

```<code>(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*
</code>```

Regex demo

Result:

```<code>[monitor:///var/log/messages]
  sourcetype=linux
index=messages

[monitor:///var/log/secure]
  sourcetype=linux
index=secure
</code>```

Body:
Have inputs.conf files in multiple directories that needs to match and parse each stanza and modify the index= to index=secure.
This are files type in inputs.conf and also do run the script to locate the inputs file in this dir (_GWAS_pr_linux_t1/local/inputs.conf) to modify the index

[monitor:///var/log/messages]
index=BDBD_np
sourcetype=syslog

[monitor:///var/log/cron]
index=NDNW_np
sourcetype=syslog

[monitor:///var/log/maillog]
index=BSKX_np
sourcetype=syslog

[monitor:///var/log/secure]
index=NDNDK_np
sourcetype=syslog

[monitor:///var/log/spooler]
index=DNWN_np
sourcetype=syslog

[monitor:///var/log/audit/audit.log]
index=XBJB_np
sourcetype=syslog

    sed -i -e 's/.*(?s)((\[monitor\:\/\/\/var\/log\/messages|secure\]).*?)(?:(?:\r*\n){2})' /index=secure *linux*/local/inputs.conf

############################
match each stanza and modify index name to index=windows
inputs file in this dir (_GWAS_pr_window_t1/local/inputs.conf)

    [WinEventLog://Application]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Security]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://System]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://ForwardedEvents]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Setup]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    sed -i -e 's/.*(?s)((\[WinEventLog:\/\/Application|Security|System|ForwardedEvents|Setup\]).*?)(?:(?:\r\n){2}) /index=window *window*/local/inputs.conf

Body:
Instead of using sed which reads line by line, you might use perl with the -0 mode. You could capture for example this part in group 1:

[monitor:///var/log/messages]
sourcetype=linux
index=

Followed by matching power afterwards.

Then in the replacement you could referer to group 1 and add secure $1secure so that will replace the matched power.

(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power

Regex demo

perl -0p -i.bak -e 's#(\[monitor:///var/log/(?:messages|secure)\](?:(?:\R.*){2})index=)power#$1secure#g' inputs.conf

Result:

[monitor:///var/log/messages]
sourcetype=linux
index=secure

Update

If you want to match any of the listed words from the comments and replace those with what comes after index, you could use 2 capturing groups:

perl -0p -i.bak -e 's#(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*#$1$2#g' inputs.conf

Pattern

(\[monitor:///var/log/(messages|secure|cron|spooler|audit\.log)\](?:(?:\R.*){2})index=).*

Regex demo

Result:

[monitor:///var/log/messages]
  sourcetype=linux
index=messages

[monitor:///var/log/secure]
  sourcetype=linux
index=secure


来源: stackexchange

问:
How do you unsubscribe from a ubiquity command
I can't seem to find details on how to unsubscribe from ubiquity commands.   The command list page only seems to have information about the installed commands and there are no links to deleting them.  Am I missing something?</p>

答:
Check this out:
http://getsatisfaction.com/mozilla/topics/how_do_you_edit_delete_the_default_ubiquity_commands_verbs

Also, you can find a utility to reset your ubiquity to default in \extensions\ubiquity@labs.mozilla.com\chrome\content\reset.html
EDIT1: The above file does nothing, please ignore.

EDIT2 (answer?): You can use the ffx addon SQLite Manager to open the \ubiquity_ann.sqlite database and remove all rows for the command you want to delete (there will be several rows, but they are identified by the url the script came from and so easy to identify).  When you restart firefox, the command will be gone.
(The code that populates the Commands page uses javascript to create an instance of UbiquitySetup object, and executes the method .createServices().commandSource which reads that SQLite database directly for a list of commands (returning an object or array of objects/commands to iterate through).  This seems to delete the command itself, since it will no longer be found in ubiquity or the command list.)

Good luck.

OwnerDisplayName: aryeh

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: threecheeseopera

LastEditorDisplayName: threecheeseopera


问:
Cannot resolve MapActivity class on Android
I have an application which has 11 different activities.  One of these activities is an extension of MapActivity (it is a map for data visualization).  To get to this activity the user must first travel through the launch activity, then 3 other activities.  The code to launch the MapActivity is:

```<code>Intent i = new Intent(getBaseContext(), MapVis.class);
i.putExtra("edu.uml.cs.isense.visualizations.session_list", sessions);
startActivity(i);
</code>```

When this is executed I get the following output from the Log:

```<code>09-01 14:36:22.389: WARN/dalvikvm(592): Class resolved by unexpected DEX: Ledu/uml/cs/isense/visualizations/MapVis;(0x44981910):0x128260 ref [Lcom/google/android/maps/MapActivity;] Lcom/google/android/maps/MapActivity;(0x44981910):0x13d330
09-01 14:36:22.389: WARN/dalvikvm(592): (Ledu/uml/cs/isense/visualizations/MapVis; had used a different Lcom/google/android/maps/MapActivity; during pre-verification)
09-01 14:36:22.389: WARN/dalvikvm(592): Unable to resolve superclass of Ledu/uml/cs/isense/visualizations/MapVis; (118)
09-01 14:36:22.389: WARN/dalvikvm(592): Link of class 'Ledu/uml/cs/isense/visualizations/MapVis;' failed
09-01 14:36:22.389: DEBUG/AndroidRuntime(592): Shutting down VM
09-01 14:36:22.389: WARN/dalvikvm(592): threadid=1: thread exiting with uncaught exception (group=0x4001d7f0)
09-01 14:36:22.399: ERROR/AndroidRuntime(592): FATAL EXCEPTION: main
09-01 14:36:22.399: ERROR/AndroidRuntime(592): java.lang.NoClassDefFoundError: edu.uml.cs.isense.visualizations.MapVis
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at edu.uml.cs.isense.visualizations.Visualizations.onOptionsItemSelected(Visualizations.java:213)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.app.Activity.onMenuItemSelected(Activity.java:2195)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.view.View$PerformClick.run(View.java:8816)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Handler.handleCallback(Handler.java:587)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Looper.loop(Looper.java:123)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.reflect.Method.invokeNative(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.reflect.Method.invoke(Method.java:521)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.NativeStart.main(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592): Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.DexFile.defineClass(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:209)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:203)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     ... 17 more
09-01 14:36:22.409: WARN/ActivityManager(92):   Force finishing activity edu.uml.cs.isense/.visualizations.Visualizations
09-01 14:36:22.909: WARN/ActivityManager(92): Activity pause timeout for HistoryRecord{44c84a90 edu.uml.cs.isense/.visualizations.Visualizations}
</code>```

I do have the target set to Google APIs, this is an app meant for Android 1.5, and specifies the minsdk to be level 3 in the manifest file.  uses-library for maps is also in manifest file.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="edu.uml.cs.isense"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Isense" 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=".experiments.Experiments" android:label="@string/app_name_experiments"/>
  <activity android:name=".sessions.Sessions" android:label="@string/app_name"/>
  <activity android:name=".people.People" android:label="@string/app_name_people"/>
  <activity android:name=".profile.Profile" android:label="@string/app_name"/>
  <activity android:name=".sensors.Sensors" android:label="@string/app_name_sensors"/>
  <activity android:name=".visualizations.DataTable" android:label="@string/app_name"/>
  <activity android:name=".visualizations.Visualizations" android:label="@string/app_name"/>
  <activity android:name=".sensors.DataListActivity"
                  android:label="@string/selectFile"
                  android:theme="@android:style/Theme.Dialog"
                  android:configChanges="orientation|keyboardHidden" />
        <activity android:name=".sensors.Upload" android:label="@string/app_name_uploader"/>
        <activity android:name=".visualizations.MapVis" android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" />
        <uses-library android:name="com.google.android.maps"/>
</application>
    <uses-sdk android:minSdkVersion="3"/>
</manifest>
</code>```

I have been at this for almost 2 days now with no results.  It seems that there are a lot of people having issues launching a MapActivity from other activities but there are no solutions anywhere.  Does anyone have a clue?  Thanks.

答:
try this:

on your Android  .jar right click Build Path-> Configure Build Path. then if you see 2 maps.jar includes remove one of them...

Body:
I have an application which has 11 different activities.  One of these activities is an extension of MapActivity (it is a map for data visualization).  To get to this activity the user must first travel through the launch activity, then 3 other activities.  The code to launch the MapActivity is:

Intent i = new Intent(getBaseContext(), MapVis.class);
i.putExtra("edu.uml.cs.isense.visualizations.session_list", sessions);
startActivity(i);

When this is executed I get the following output from the Log:

09-01 14:36:22.389: WARN/dalvikvm(592): Class resolved by unexpected DEX: Ledu/uml/cs/isense/visualizations/MapVis;(0x44981910):0x128260 ref [Lcom/google/android/maps/MapActivity;] Lcom/google/android/maps/MapActivity;(0x44981910):0x13d330
09-01 14:36:22.389: WARN/dalvikvm(592): (Ledu/uml/cs/isense/visualizations/MapVis; had used a different Lcom/google/android/maps/MapActivity; during pre-verification)
09-01 14:36:22.389: WARN/dalvikvm(592): Unable to resolve superclass of Ledu/uml/cs/isense/visualizations/MapVis; (118)
09-01 14:36:22.389: WARN/dalvikvm(592): Link of class 'Ledu/uml/cs/isense/visualizations/MapVis;' failed
09-01 14:36:22.389: DEBUG/AndroidRuntime(592): Shutting down VM
09-01 14:36:22.389: WARN/dalvikvm(592): threadid=1: thread exiting with uncaught exception (group=0x4001d7f0)
09-01 14:36:22.399: ERROR/AndroidRuntime(592): FATAL EXCEPTION: main
09-01 14:36:22.399: ERROR/AndroidRuntime(592): java.lang.NoClassDefFoundError: edu.uml.cs.isense.visualizations.MapVis
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at edu.uml.cs.isense.visualizations.Visualizations.onOptionsItemSelected(Visualizations.java:213)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.app.Activity.onMenuItemSelected(Activity.java:2195)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:532)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.view.View$PerformClick.run(View.java:8816)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Handler.handleCallback(Handler.java:587)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.os.Looper.loop(Looper.java:123)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.reflect.Method.invokeNative(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.reflect.Method.invoke(Method.java:521)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.NativeStart.main(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592): Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.DexFile.defineClass(Native Method)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:209)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:203)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
09-01 14:36:22.399: ERROR/AndroidRuntime(592):     ... 17 more
09-01 14:36:22.409: WARN/ActivityManager(92):   Force finishing activity edu.uml.cs.isense/.visualizations.Visualizations
09-01 14:36:22.909: WARN/ActivityManager(92): Activity pause timeout for HistoryRecord{44c84a90 edu.uml.cs.isense/.visualizations.Visualizations}

I do have the target set to Google APIs, this is an app meant for Android 1.5, and specifies the minsdk to be level 3 in the manifest file.  uses-library for maps is also in manifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="edu.uml.cs.isense"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Isense" 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=".experiments.Experiments" android:label="@string/app_name_experiments"/>
  <activity android:name=".sessions.Sessions" android:label="@string/app_name"/>
  <activity android:name=".people.People" android:label="@string/app_name_people"/>
  <activity android:name=".profile.Profile" android:label="@string/app_name"/>
  <activity android:name=".sensors.Sensors" android:label="@string/app_name_sensors"/>
  <activity android:name=".visualizations.DataTable" android:label="@string/app_name"/>
  <activity android:name=".visualizations.Visualizations" android:label="@string/app_name"/>
  <activity android:name=".sensors.DataListActivity"
                  android:label="@string/selectFile"
                  android:theme="@android:style/Theme.Dialog"
                  android:configChanges="orientation|keyboardHidden" />
        <activity android:name=".sensors.Upload" android:label="@string/app_name_uploader"/>
        <activity android:name=".visualizations.MapVis" android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" />
        <uses-library android:name="com.google.android.maps"/>
</application>
    <uses-sdk android:minSdkVersion="3"/>
</manifest>

I have been at this for almost 2 days now with no results.  It seems that there are a lot of people having issues launching a MapActivity from other activities but there are no solutions anywhere.  Does anyone have a clue?  Thanks.

ContentLicense: CC BY-SA 3.0


问:
Permission denied after allowing read and write permissions in manifest and runtime
I am getting this error

```<code>   W/System.err: java.io.FileNotFoundException: /root/storage/emulated/0/DCIM/Camera/IMG_20181116_172404.jpg (Permission denied)
</code>```

I added the following in my manifests:

```<code>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Added following code in MainActivity.java

```<code>    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    private void checkIfPermissionGranted() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            int hasWritePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int hasReadPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if(hasWritePermission != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
            if(hasReadPermission != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
        }

    }
</code>```

How do I fix this? Here's a screenshot of app permissions in settings menu

答:
```<code>  // Implement this overide method..

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults)
{

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

    //  implement Your File related Code here,

        } else {
            Toast.makeText(this, "Permission is Require for Access External Storage", Toast.LENGTH_SHORT).show();
        }

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error

   W/System.err: java.io.FileNotFoundException: /root/storage/emulated/0/DCIM/Camera/IMG_20181116_172404.jpg (Permission denied)

I added the following in my manifests:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Added following code in MainActivity.java

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    private void checkIfPermissionGranted() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            int hasWritePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int hasReadPermission = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if(hasWritePermission != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
            if(hasReadPermission != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
        }

    }

How do I fix this? Here's a screenshot of app permissions in settings menu


问:
Can I change Price Granularity in prebid
Can I change price granularity in prebid header auction as per our need ? Prebid has the following price granularity- Low, Medium, High, Dense, Custom. I want to know if I set my DFP line items in a way where I will have a flexibility to use Price Granularity according to my preferences so that when required I can use low and when required medium or high. But I don't want to make changes to our DFP line items for that every time.

Can this be achieved ?

I've created DFP line items already in a increments of $0.05 like 0.05, 0.10, 0.15, 0.20, 0.25, 0.30 .... so on.

I want to understand for example if I set the line items at 0.05 increments capped at $20.00 then let's say if price granularity is set "low" then the increments will happen at 0.05 while in "medium" may be 0.10 increments. While I don't want to change DFP line item values every time I wish to change price granularity.

Also, please suggest, if we get $20 and above CPM, then how will we get it because prebid wil automatically round off and reduce the highest cpm to $20 bid.

答:
You can use multiple price granularities if you wish, as long as your line items have price buckets to match at the most granular level. For example, if you are using "medium" granularity and setup line items at $0.10 increments, switching to a "high" granularity ($0.01) would cause you to lose bids at those bids that didn't land exactly on a $0.10 increment (i.e. $1.17, $1.23 etc). However, switching to a lower granularity (ie "low") would be fine.

Related links:

http://prebid.org/adops/before-you-start.html#decide-on-price-bucket-granularity

http://prebid.org/dev-docs/common-issues.html#price-granularity-mismatch

http://prebid.org/dev-docs/publisher-api-reference.html#setConfig-Price-Granularity


问:
How to load line array objects from a file using object serialization java
The program is meant to enable the user draw something with lines and save it to a file which can then be loaded, saving using     ObjectOutput writeObject method works fine, but it is loading the file that does not work, if you save the file you can draw an additional line to make the display different from what was saved, but on loading it using ObjectInputStream readObject method, It does not display the saved drawing on the panel.</p>

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.io.*;

public class DrawLine extends JPanel
{
  private LineClass lines[];
  private String fileName;
  private int lineCount;
  private LineClass currentLine;
  public JLabel statusLabel;
  private int currShapeX1,currShapeY1;
  private static JButton saveButton, loadButton;
  private ObjectOutputStream output;
  private ObjectInputStream input;
  private JFileChooser fileChooser;
  public DrawLine()
  {
    statusLabel = new JLabel("(0,0)");
    saveButton = new JButton("Save");
    loadButton = new JButton("Load");
    lines = new LineClass[100];
    lineCount = 0;
    currentLine = null;

    MouseHandler handler = new MouseHandler();
    addMouseListener(handler);
    addMouseMotionListener(handler);
    saveButton.addActionListener(handler);
        loadButton.addActionListener(handler);

      }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);

    for(int count = 0; count < lineCount; ++count)
    {
      lines[count].draw(g);
    }
    if( currentLine != null ) {
  currentLine.draw(g);
}
  }

  public static void main(String args[])
  {
JFrame frame = new JFrame();
DrawLine panel = new DrawLine();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(saveButton,BorderLayout.NORTH);
frame.add(loadButton,BorderLayout.SOUTH);
frame.add(panel,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
  }

  private class MouseHandler extends MouseAdapter implements         MouseMotionListener, ActionListener
  {
    public void actionPerformed(ActionEvent event)
    {
      if (event.getSource() == loadButton)
      {
          fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int result = fileChooser.showOpenDialog(DrawLine.this);

    if (result == JFileChooser.CANCEL_OPTION)
      System.err.println("No file selected.");
    else
    {
      File file = fileChooser.getSelectedFile();
      if ((file != null) && !(file.getName().equals("")))
      {
        fileName = file.getName();

try
{
input = new ObjectInputStream(new FileInputStream(fileName));

lines = ((LineClass[])input.readObject());
     lineCount = 0;
    for(int j = 0; j < 100; ++j)
    {
      if (lines[j] == null)
        break;
      else
        lineCount++;
    }
repaint();
}
catch(EOFException ex)
{
  System.out.println("Finished loading file");
}
catch(IOException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Error loading \""+fileName+"\"", "Error Message", JOptionPane.ERROR_MESSAGE);
}
catch(ClassNotFoundException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Unable to create object", "Error Message", JOptionPane.ERROR_MESSAGE);
}
      }
  }
  }
  if (event.getSource() == saveButton)
  {
    fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int result = fileChooser.showSaveDialog(DrawLine.this);

    if (result == JFileChooser.CANCEL_OPTION)
      System.err.println("File was not saved");
    else if (result == JFileChooser.APPROVE_OPTION)
    {
      File file = fileChooser.getSelectedFile();

      if ((file != null)&&!(file.getName().equals("")))
      {
        fileName = file.getName()+".drw";

     try
{
  output = new ObjectOutputStream(new FileOutputStream(fileName));
    output.writeObject(lines);
  output.close();
  System.out.println(fileName+" saved");
}
catch(IOException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Error saving \""+fileName+"\"", "Error Message", JOptionPane.ERROR_MESSAGE);
}
  }
    }
  }
}
public void mousePressed(MouseEvent event)
{
  //it assigns currentShape a new shape and initializes both points to the mouse position.
  currShapeX1 = event.getX();
  currShapeY1 = event.getY();
}
public void mouseReleased(MouseEvent event)
{
  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.
  lines[lineCount] = currentLine;
  lineCount++;

  currentLine = null;
  repaint();
}
public void mouseDragged(MouseEvent event)
{

  //it sets the second point of the currentShape to the current mouse position and calls method repaint

  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.
  //lines[lineCount] = currentLine;

  //currentLine = null;
  repaint();
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}

public void mouseMoved(MouseEvent event)
{
  //to set the text of the statusLabel so that it displays the mouse coordinates—this will update the label with the coordinates every time the user moves
  //(but does not drag) the mouse within the DrawPanel
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}
}
}

//LineClass
class LineClass implements Serializable
{
private int x1;
private int y1;
private int x2;
private int y2;

public LineClass(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public void draw(Graphics g)
{
g.drawLine(x1,y1,x2,y2);
}
}
</code>```

答:
It appears that when you read your file back in lineCount is set to 100 as this is the size of your array that you saved.

If you only drew 3 lines lineCount is 100 instead of 3.

This means that when you do a repaint it is trying to draw null objects.

What you need to do is when you load the file find the first null value in the lines array and set your lineCount according to that, and not the length of the array.

A simplistic method would be

```<code>for (int loop = 0; loop < lines.length; loop++)
{
  if (lines[loop] == null)
  {
    lineCount = loop;
    break;
  }
}
</code>```

instead of

```<code>lineCount = lines.length;
</code>```

Body:
The program is meant to enable the user draw something with lines and save it to a file which can then be loaded, saving using     ObjectOutput writeObject method works fine, but it is loading the file that does not work, if you save the file you can draw an additional line to make the display different from what was saved, but on loading it using ObjectInputStream readObject method, It does not display the saved drawing on the panel.

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.io.*;

public class DrawLine extends JPanel
{
  private LineClass lines[];
  private String fileName;
  private int lineCount;
  private LineClass currentLine;
  public JLabel statusLabel;
  private int currShapeX1,currShapeY1;
  private static JButton saveButton, loadButton;
  private ObjectOutputStream output;
  private ObjectInputStream input;
  private JFileChooser fileChooser;
  public DrawLine()
  {
    statusLabel = new JLabel("(0,0)");
    saveButton = new JButton("Save");
    loadButton = new JButton("Load");
    lines = new LineClass[100];
    lineCount = 0;
    currentLine = null;

    MouseHandler handler = new MouseHandler();
    addMouseListener(handler);
    addMouseMotionListener(handler);
    saveButton.addActionListener(handler);
        loadButton.addActionListener(handler);

      }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);

    for(int count = 0; count < lineCount; ++count)
    {
      lines[count].draw(g);
    }
    if( currentLine != null ) {
  currentLine.draw(g);
}
  }

  public static void main(String args[])
  {
JFrame frame = new JFrame();
DrawLine panel = new DrawLine();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(saveButton,BorderLayout.NORTH);
frame.add(loadButton,BorderLayout.SOUTH);
frame.add(panel,BorderLayout.CENTER);
frame.setSize(400,400);
frame.setVisible(true);
  }

  private class MouseHandler extends MouseAdapter implements         MouseMotionListener, ActionListener
  {
    public void actionPerformed(ActionEvent event)
    {
      if (event.getSource() == loadButton)
      {
          fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int result = fileChooser.showOpenDialog(DrawLine.this);

    if (result == JFileChooser.CANCEL_OPTION)
      System.err.println("No file selected.");
    else
    {
      File file = fileChooser.getSelectedFile();
      if ((file != null) && !(file.getName().equals("")))
      {
        fileName = file.getName();

try
{
input = new ObjectInputStream(new FileInputStream(fileName));

lines = ((LineClass[])input.readObject());
     lineCount = 0;
    for(int j = 0; j < 100; ++j)
    {
      if (lines[j] == null)
        break;
      else
        lineCount++;
    }
repaint();
}
catch(EOFException ex)
{
  System.out.println("Finished loading file");
}
catch(IOException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Error loading \""+fileName+"\"", "Error Message", JOptionPane.ERROR_MESSAGE);
}
catch(ClassNotFoundException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Unable to create object", "Error Message", JOptionPane.ERROR_MESSAGE);
}
      }
  }
  }
  if (event.getSource() == saveButton)
  {
    fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int result = fileChooser.showSaveDialog(DrawLine.this);

    if (result == JFileChooser.CANCEL_OPTION)
      System.err.println("File was not saved");
    else if (result == JFileChooser.APPROVE_OPTION)
    {
      File file = fileChooser.getSelectedFile();

      if ((file != null)&&!(file.getName().equals("")))
      {
        fileName = file.getName()+".drw";

     try
{
  output = new ObjectOutputStream(new FileOutputStream(fileName));
    output.writeObject(lines);
  output.close();
  System.out.println(fileName+" saved");
}
catch(IOException ex)
{
  JOptionPane.showMessageDialog(DrawLine.this, "Error saving \""+fileName+"\"", "Error Message", JOptionPane.ERROR_MESSAGE);
}
  }
    }
  }
}
public void mousePressed(MouseEvent event)
{
  //it assigns currentShape a new shape and initializes both points to the mouse position.
  currShapeX1 = event.getX();
  currShapeY1 = event.getY();
}
public void mouseReleased(MouseEvent event)
{
  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.
  lines[lineCount] = currentLine;
  lineCount++;

  currentLine = null;
  repaint();
}
public void mouseDragged(MouseEvent event)
{

  //it sets the second point of the currentShape to the current mouse position and calls method repaint

  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.
  //lines[lineCount] = currentLine;

  //currentLine = null;
  repaint();
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}

public void mouseMoved(MouseEvent event)
{
  //to set the text of the statusLabel so that it displays the mouse coordinates—this will update the label with the coordinates every time the user moves
  //(but does not drag) the mouse within the DrawPanel
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}
}
}

//LineClass
class LineClass implements Serializable
{
private int x1;
private int y1;
private int x2;
private int y2;

public LineClass(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public void draw(Graphics g)
{
g.drawLine(x1,y1,x2,y2);
}
}

Body:
It appears that when you read your file back in lineCount is set to 100 as this is the size of your array that you saved.

If you only drew 3 lines lineCount is 100 instead of 3.

This means that when you do a repaint it is trying to draw null objects.

What you need to do is when you load the file find the first null value in the lines array and set your lineCount according to that, and not the length of the array.

A simplistic method would be

for (int loop = 0; loop < lines.length; loop++)
{
  if (lines[loop] == null)
  {
    lineCount = loop;
    break;
  }
}

instead of

lineCount = lines.length;


问:
Using Mailchimp RSS to Only Send Last Post
I have a very simple RSS integration campaign set up for a tumblr blog to mailchimp. The idea is that there is a daily post on the tumblr blog that gets emailed out to a list by mailchimp. That email is set to go out at 12:00.

Sometimes, if a different campaign was used for some reason or there were other issues, mailchimp will try to send the campaign with the last 2 posts - one of which might have already been sent out.

How can I get mailchimp to send only the most recent post?

答:
Use RSSITEM family tags:

https://mailchimp.com/es/help/rss-merge-tags/

It will load the information of the last post.


问:
How do I delete a key and its nested key value pairs in a json file?
I want to be able to check if a json file has the top level key I'm looking for and delete that nested dictionary.

Json file:

```<code>{
    "One": {
        "action": "One",
        "delay": 1559243024.3665395,
        "seconds": 0,
        "score": 0,
        "delta": 1559183024.3665395,
        "grace_sec": 60000
    },
    "Two": {
        "action": "Two",
        "delay": 1559321009.969849,
        "seconds": 0,
        "score": 14,
        "delta": 1559261009.969849,
        "grace_sec": 60000
    },
    "Three": {
        "action": "Three",
        "delay": 1559909745.5981774,
        "seconds": 0,
        "score": 0,
        "delta": 1559309745.5981774,
        "grace_sec": 600000
    },
    "Four": {
        "action": "Four",
        "delay": 1559909757.0363235,
        "seconds": 0,
        "score": 1,
        "delta": 1559309757.0363235,
        "grace_sec": 600000
    }
}
</code>```

This is what I have tried so for but hasn't worked:

```<code>if name == child.text:
              ...
                with open("streak.json", "r+") as f:
                    data = json.load(f)

                for x in data:
                    if name in x:
                        del x[name]

                with open("streak.json", "w") as file:
                    data = json.dump(data, file)
</code>```

So for instance if the name == "Two", then all of Two's key value pairs would be deleted including Two itself.

答:
Just delete the top level item:</p>

```<code>with open("streak.json", "r") as f:
    data = json.load(f)

if name in data:
    del data[name]

with open("streak.json", "w") as file:
    json.dump(data, file)
</code>```

Body:
I want to be able to check if a json file has the top level key I'm looking for and delete that nested dictionary.

Json file:

{
    "One": {
        "action": "One",
        "delay": 1559243024.3665395,
        "seconds": 0,
        "score": 0,
        "delta": 1559183024.3665395,
        "grace_sec": 60000
    },
    "Two": {
        "action": "Two",
        "delay": 1559321009.969849,
        "seconds": 0,
        "score": 14,
        "delta": 1559261009.969849,
        "grace_sec": 60000
    },
    "Three": {
        "action": "Three",
        "delay": 1559909745.5981774,
        "seconds": 0,
        "score": 0,
        "delta": 1559309745.5981774,
        "grace_sec": 600000
    },
    "Four": {
        "action": "Four",
        "delay": 1559909757.0363235,
        "seconds": 0,
        "score": 1,
        "delta": 1559309757.0363235,
        "grace_sec": 600000
    }
}

This is what I have tried so for but hasn't worked:

if name == child.text:
              ...
                with open("streak.json", "r+") as f:
                    data = json.load(f)

                for x in data:
                    if name in x:
                        del x[name]

                with open("streak.json", "w") as file:
                    data = json.dump(data, file)

So for instance if the name == "Two", then all of Two's key value pairs would be deleted including Two itself.

Body:
Just delete the top level item:

with open("streak.json", "r") as f:
    data = json.load(f)

if name in data:
    del data[name]

with open("streak.json", "w") as file:
    json.dump(data, file)


问:
Doctrine query iterate not working on MS SQL Server - New transaction is not allowed
I'm trying to iterate over results and remove them using the entity manager, as described in https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/batch-processing.html#iterating-results

However, I'm getting the following error when flush() is being called:

PHP Fatal error:  Uncaught Doctrine\DBAL\Driver\SQLSrv\SQLSrvException: SQLSTATE [42000, 3988]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]New transaction is not allowed because there are other threads running in the session. in D:\inetpub\wwwroot\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\SQLSrv\SQLSrvException.php:54

<?php

$batchSize = 20;
$i = 0;

$q = $em->createQuery('select u from MyProject\Model\User u WHERE credit < :minCredit');
$q->setParameter('minCredit', 20);

$iterableResult = $q->iterate();
while (($row = $iterableResult->next()) !== false) {
    $em->remove($row[0]);
    if (($i % $batchSize) === 0) {
        $em->flush();
        $em->clear();
    }
    ++$i;
}
$em->flush();
```

答:
The problem is because SQL Server can't begin a new transaction while iterating over a prepared statement.

The solution is to begin a transaction that includes the prepared statement and then committing after altering all objects.

<?php

$conn = $em->getConnection();

$batchSize = 20;
$i = 0;

$q = $em->createQuery('select u from MyProject\Model\User u WHERE credit < :minCredit');
$q->setParameter('minCredit', 20);

$conn->beginTransaction();

try {
    $iterableResult = $q->iterate();
    while (($row = $iterableResult->next()) !== false) {
        $em->remove($row[0]);
        if (($i % $batchSize) === 0) {
            $em->flush();
            $em->clear();
        }
        ++$i;
    }
    $em->flush();

    $conn->commit();
} catch (\Exception $e) {
    $conn->rollBack();
    throw $e;
}
```


问:
Is it possible to apply a decorator to a line in python?
As you may now, the common usage of decorator is for example:

```<code>@log
def func(...)
</code>```

What actualy takes func as parameter returns a function what takes func as an argument, like :

```<code>def log(func):
    def function_wrapper(*args , **kwargs):
    log_enter_func(func, args, kwargs)

    result = func(*args, **kwargs)
    log_exit_func(func, result )
    return result
</code>```

In code above, logging of function calls and returns are fine, without hand- made log (...) entries with just @log decorator over a function.
So its easy to remove after testing, so logging does not consume time.

But is it possible to hang it just to lines of code?
Like for loops, etc, so something like :

```<code>def func(...):
 ...
@log
    for x in range(whatever)
</code>```

Taking the line as soft of a function, accessing in some kinf of args to x, whatever ( variables and code in the line) cause actualy everything is a function in python?

Or maybe there is some kind of method to apply decorator to a method and propagate it to source lines in a function ?

The idea is to make a brief logging of whats happens in every line without lots of hand- written log entries like
log.info(msg)
in many lines of code

Any ideas about that?
I v tryed to inspect the func. __ code __  built- in, but its python byte- code there , not source code...

答:
No, decorators are meant to wrap functions only.

That said, you can run your line inside a function and then use the decorator.

```<code>def func(...):
    ...

    @log
    def _f(): #you can define this inside func() if you want
        for x in range(whatever):
            ...

    #call decorated function
    _f()
</code>```

Body:
As you may now, the common usage of decorator is for example:

@log
def func(...)

What actualy takes func as parameter returns a function what takes func as an argument, like :

def log(func):
    def function_wrapper(*args , **kwargs):
    log_enter_func(func, args, kwargs)

    result = func(*args, **kwargs)
    log_exit_func(func, result )
    return result

In code above, logging of function calls and returns are fine, without hand- made log (...) entries with just @log decorator over a function.
So its easy to remove after testing, so logging does not consume time.

But is it possible to hang it just to lines of code?
Like for loops, etc, so something like :

def func(...):
 ...
@log
    for x in range(whatever)

Taking the line as soft of a function, accessing in some kinf of args to x, whatever ( variables and code in the line) cause actualy everything is a function in python?

Or maybe there is some kind of method to apply decorator to a method and propagate it to source lines in a function ?

The idea is to make a brief logging of whats happens in every line without lots of hand- written log entries like
log.info(msg)
in many lines of code

Any ideas about that?
I v tryed to inspect the func. __ code __  built- in, but its python byte- code there , not source code...

Body:
No, decorators are meant to wrap functions only.

That said, you can run your line inside a function and then use the decorator.

def func(...):
    ...

    @log
    def _f(): #you can define this inside func() if you want
        for x in range(whatever):
            ...

    #call decorated function
    _f()


问:
.NET - A fast lightweight persistent key-value storage
I'm looking for a persistent key-value storage for .NET. The requirements are:

Storage is used for objects that are identified by strings and have several optional (named) properties with values that are just byte arrays. For an SQL solution I would model it as one string -> id table, and several id -> blob tables.

The expected amount of data is several megabytes (more than 10 Mb is currently unlikely, but scaling up to 100 Mb would be a nice bonus)

Lightweight - preferably single-assembly, definitely without external applications

Reads are more frequent than writes, at least by a factor of 100.

Fast read/write access - I expect in-memory storage and lazy writes on the updates to the data; I can periodically spawn async writes myself, bonus points if the storage does it.

Atomic I/O - the database should not break if the process is terminated in the middle of writing; otherwise the data is not critical, i.e. no additional redundancy is needed.

Currently I think that SQLite will work here; however it seems to be a slight overkill - I only need key-value storage, not full SQL support. I've also heard of bdb, and of libdb-dotnet binding - it seems to be more lightweight, but I don't know the performance/consistency characteristics.

Can anyone recommend something here? Additional references are welcome (i.e. it would be awesome if there's something in .NET Framework that can do the job), as well as experiences with SQLite or libdb-dotnet (or bdb in general) or home-grown solution, if it was painless.

答:
Perhaps have a look at http://ravendb.net/. It stores JSON documents in a key-value storage, but with great .NET object support.

From your explanation of your needs, you could also look into just utilizing it's managed storage engine, "Raven.Munin", which is a single assembly.


问:
Exclude all email records from a domain except those that begin with a string
I'm trying to exclude all records in a table from a specific domain except for those that begin with a specific string.

So, for example I have a bunch of records with yopmail.com as the domain.  I want to exclude all records from yopmail.com except those that start with abc.

The current code to exclude is just WHERE emailAddress NOT LIKE '%yopmail.com', but now I need to figure out how to add to that except 'WHERE emailAddress LIKE abc%yopmail.com'.

I've wracked my brain for how to do this and I can't come up with anything useful.

Ben

答: The key to solving this mystery is to use regular expressions. You can match literal characters [A-Z] and use wildcards like # and $ to match strings. The regular expressions can become quite complex, so there are editors available such RegEx Buddy.</p>


问:
Split the select of the same association on different fields
I'm in the middle of developing a bike website when I stumbled on question.

I have the follow models (to simplify my description I left some models and attributes aside):

model_name:some attributes (example)

bike: name, price, color (Giant Anthem, 3999, black)

category: name (Brakes or Shifts or Transmissions, etc)

component: name (Shimano SLX or Shimano XT or Shimano XTR - in this case for components for the transmission category)

So the relationship of these models are the followed:

A bike has many components

A component is on many bikes

A component belongs to a category

A category has many components

Right now I've created these 3 tables and made the association: category has_many components and component belong_to category. Everything works well. Now I have to create  a jointable and use the has many through association between bike and component BUT the problem for me is to understand the next step after that because I don't want only one dropdown to select all components. I want to select the components divided by category. Something like this:

How can I achieve this? Hope you can help me. Thank you!

答:
The tricky part is that you want to split the select of the same association on different fields. You may need to handle the name of the field manually, something like this:

```<code>= select_tag 'bike[component_ids][]', options_from_collection_for_select(frames_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(breakes_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(transmissions_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(tyres_category.components.all, :id, :name)
</code>```

Note the names of the attribute `bike[components_ids][]'. The params hash on your controller will look something like:

```<code>params == {bike: {name: 'some name', price: '200', component_ids: [1,3,6,8]}
</code>```

ActiveRecord should handle the assignment of the components using the collection_singular_ids= https://guides.rubyonrails.org/association_basics.html#methods-added-by-has-many-collection-singular-ids-ids

I'm not 100% sure it works on has many through but personally I wouldn't use a has many through there, "has and belong to many" seems to just fit your needs and it requires less configuration.

Body:
The tricky part is that you want to split the select of the same association on different fields. You may need to handle the name of the field manually, something like this:

= select_tag 'bike[component_ids][]', options_from_collection_for_select(frames_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(breakes_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(transmissions_category.components.all, :id, :name)
= select_tag 'bike[component_ids][]', options_from_collection_for_select(tyres_category.components.all, :id, :name)

Note the names of the attribute `bike[components_ids][]'. The params hash on your controller will look something like:

params == {bike: {name: 'some name', price: '200', component_ids: [1,3,6,8]}

ActiveRecord should handle the assignment of the components using the collection_singular_ids= https://guides.rubyonrails.org/association_basics.html#methods-added-by-has-many-collection-singular-ids-ids

I'm not 100% sure it works on has many through but personally I wouldn't use a has many through there, "has and belong to many" seems to just fit your needs and it requires less configuration.


问:
How to use :before on child element?
I have a wordpress site and I use css to replace an image of a plugin (polylang's flags).

```<code>.lang-item-42 a img {
    content:url(/wp-content/uploads/2019/05/en.png);
}
</code>```

So this is working on Chrome and Safari but not on Firefox and IE. As I found out is because I should use :before selector but im not sure where to put it because if I place it right after the "img" element it not works.

答:
First you should declare ::before with double colon (not :before) since it is considered a pseudo-element and not a pseudo-class.
Consider this element like "something that is inside and at the beginning of the element it is put on".
So if you want to put an image inside the link, you hide the other and type

```<code>.lang-item-42 a::before {
    content:url(/wp-content/uploads/2019/05/en.png);
}

.lang-item-42 a img {
    display: none;
}
</code>```

I haven't tried this out but it should work.

Title: How to use :before on child element?

Body:
I have a wordpress site and I use css to replace an image of a plugin (polylang's flags).

.lang-item-42 a img {
    content:url(/wp-content/uploads/2019/05/en.png);
}

So this is working on Chrome and Safari but not on Firefox and IE. As I found out is because I should use :before selector but im not sure where to put it because if I place it right after the "img" element it not works.

Body:
First you should declare ::before with double colon (not :before) since it is considered a pseudo-element and not a pseudo-class.
Consider this element like "something that is inside and at the beginning of the element it is put on".
So if you want to put an image inside the link, you hide the other and type

.lang-item-42 a::before {
    content:url(/wp-content/uploads/2019/05/en.png);
}

.lang-item-42 a img {
    display: none;
}

I haven't tried this out but it should work.


问:
Hidden text animation is not working properly
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}</code>```

  <button>
</button>

some text

```

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

答:
you don't need js to do that its a simple css method

```<code><div>
  <button class="hoverbtn" id="hoverbtn">
  </button>
  <div id="textcontent" class = "textcontent">
    <span>some text</span>
  </div>
</div>
</code>```

and here is css to hide and show text

If the second item is directly inside the container:

```<code>#hoverbtn:hover > #textcontent { opacity : 1 }
</code>```

If the second item is next to (after containers closing tag) the container:

```<code>#hoverbtn:hover + #textcontent { opacity : 1 }
</code>```

If the second item is somewhere inside the container:

```<code>#hoverbtn:hover #textcontent { opacity : 1 }
</code>```

If the second item is a sibling of the container:

```<code>#hoverbtn:hover ~ #textcontent { opacity : 1 }
</code>```

so here is your css :

```<code>.hoverbtn {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

.hoverbtn:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all 0.3s ease 0s;
  border: none;
}

.textcontent {
  opacity: 0;
}

.hoverbtn:hover+.textcontent {
  opacity: 1;
}
</code>```

reference : https://stackoverflow.com/a/4502693/6550949

Body:
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}

button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}

  <button>
</button>

some text

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

Body:
you don't need js to do that its a simple css method

<div>
  <button class="hoverbtn" id="hoverbtn">
  </button>
  <div id="textcontent" class = "textcontent">
    <span>some text</span>
  </div>
</div>

and here is css to hide and show text

If the second item is directly inside the container:

#hoverbtn:hover > #textcontent { opacity : 1 }

If the second item is next to (after containers closing tag) the container:

#hoverbtn:hover + #textcontent { opacity : 1 }

If the second item is somewhere inside the container:

#hoverbtn:hover #textcontent { opacity : 1 }

If the second item is a sibling of the container:

#hoverbtn:hover ~ #textcontent { opacity : 1 }

so here is your css :

.hoverbtn {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

.hoverbtn:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all 0.3s ease 0s;
  border: none;
}

.textcontent {
  opacity: 0;
}

.hoverbtn:hover+.textcontent {
  opacity: 1;
}

reference : https://stackoverflow.com/a/4502693/6550949


问:
how to revers a diagonal matrix in C?
and if we want to reverse diagonal matrix, like:

```<code>1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
</code>```

and if we reverse the diagonals it will be like that:

```<code>5  2  3  4  1
6  9  8  7  10
11 12 13 14 15
16 19 18 17 20
25 22 23 24 21
</code>```

or like this example:

```<code>1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16
</code>```

and it will be like this:

```<code>4  2  3  1
5  7  6  8
9 11 10 12
16 14 15 13
</code>```

but were not allowed to use functions and the matrix is always the a[N][N] kind..

Title: how to revers a diagonal matrix in C?

Body:
and if we want to reverse diagonal matrix, like:

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

and if we reverse the diagonals it will be like that:

5  2  3  4  1
6  9  8  7  10
11 12 13 14 15
16 19 18 17 20
25 22 23 24 21

or like this example:

1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16

and it will be like this:

4  2  3  1
5  7  6  8
9 11 10 12
16 14 15 13

but were not allowed to use functions and the matrix is always the a[N][N] kind..

Body:
This seems so do the trick - it's not pretty though. You can probably make it more generic to different sized arrays.

#include <stdio.h>
const int N = 5;

void print (int arr[][N]) {
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            printf("%d ", arr[i][j]);
        }
        printf ("\n");
    }
    printf ("\n");
}

void flip (int arr[][N]) {
    int a[5][5] = {0};
    int x, y;
    for (y = 0; y < N; y++) {
        for (x = 0; x < N; x++) {
            if (x == y){
                a[y][x] = arr[y][N-y-1];
            } else if (x == N-(y+1)) {
                a[y][x] = arr[y][y];
            } else {
                a[y][x] = arr[y][x];
            }
        }
    }
    print(a);
}

int main() {
  int a[5][5] = {
    {1, 2, 3, 4, 5},
    {6,7,8,9,10},
    {11,12,13,14,15},
    {16,17,18,19,20},
    {21,22,23,24,25}
  };
  flip(a);
  return 0;
}

Outputs:

5 2 3 4 1
6 9 8 7 10
11 12 13 14 15
16 19 18 17 20
25 22 23 24 21


问:
Where to get a reference image for any unicode code point?
I am looking for an online service (or collection of images) that can return an image for any unicode code point.

Unicode.org does not have an image for each one, consider for example
http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=31cf

EDIT:  I need to use these images programmatically, so the code chart PDFs provided at unicode.org are not useful.

答:
The images in the PDF are copyrighted, so there are legal issues around extracting them. (I am not a lawyer.) I suspect that those legal issues prevent a simple solution from being provided, unless someone wants to go to the trouble of drawing all of those images. It might happen, but seems unlikely.

Your best bet is to download a selection of fonts that collectively cover the entire range of characters, and display the characters using those fonts. There are two difficulties with this approach: combining characters and invisible characters.

The combining characters can easily be detected from the Unicode database, and you can supply a base character (such as NBSP) to use for displaying them. (There is a special code point intended for this purpose, but I can't find it at the moment.)

Invisible characters could be displayed with a dotted square box containing the abbreviation for the character. Those you may have to locate manually and construct the necessary abbreviations. I am not aware of any shortcuts for that.


问:
Using images to style scroll bars?
Can anyone recommend the best solution for using images to style scroll bar?  I guess a decent cross-browser solution would involve a merge of JQuery/javascrip and CSS?

Thanks
Paul

答: I recommend using the jScrollPane jQuery plugin for this. It lets you use CSS to style scroll bars. If you want to use images, you'd use the background-image property, as the Lozenge theme demo shows.

Title: Using images to style scroll bars?


答:
You can use the pop() function. This function will delete the key from the dictionary and return the value. If the key does not exist, it will return a default value.
eg:

```<code>>>> d = {'a': 1, 'b': 2}
>>> d.pop('a', None)
1
>>> d
{'b': 2}
>>> d.pop('c', None)
>>> d
{'b': 2}
>>>
</code>```

This will reduce the burden of checking if a key exists or not when deleting and you won't have to rely on KeyError to check if it failed.
You can check if the return value is not your sentinel value, None in this case, then the key was successfully deleted. If it is the sentinel value, then the key never existed.

Title: How do I delete a key and its nested key value pairs in a json file?

Body:
You can use the pop() function. This function will delete the key from the dictionary and return the value. If the key does not exist, it will return a default value.
eg:

>>> d = {'a': 1, 'b': 2}
>>> d.pop('a', None)
1
>>> d
{'b': 2}
>>> d.pop('c', None)
>>> d
{'b': 2}
>>>

This will reduce the burden of checking if a key exists or not when deleting and you won't have to rely on KeyError to check if it failed.
You can check if the return value is not your sentinel value, None in this case, then the key was successfully deleted. If it is the sentinel value, then the key never existed.


问:
How to implement datatables server-side pagination in Django app
I need server-side pagination + individual column search for my django project. Sadly I was not able to implement the pagination. </p>

<p>I searched a lot for working examples but did not find any. I want to implement my server side api myself, there are some django apps but they seem not the be maintained anymore. Following is my datatables code + django view. Anyone here who could give me some advice? </p>

```<code>var table = $('#mainTable').DataTable({
        dom: 'Bfrtip',
        responsive: true,
        serverSide: true,
        processing: true,
        pageLength: 25,
        buttons: [
            'csv', 'print',
            {
                extend: 'colvis',
                text: 'Spalten filtern',
                columns: ':not(.noVis)'
            },
        ],
        ajax: {
            url: '/akquise/mainTableData',
            dataSrc: function ( json ) {
                return json;
           }
        },
        columnDefs: [
            { targets: [0,1,2,3,4,5,6,7,8,9], orderable: false},
            { targets: 0, className: "leadID", searchable: false },
            { targets: 3, className: "firmenname" },
        ],
        columns: [
            { data: "leadID",
                render: function ( data, type, row, meta ) {
                    button = '<a role="button" class="btn btn-secondary" target="_blank" href="details?leadID='+data+'"><i class="fas fa-search"></a>';
                    return button
                }
            },
            { data: "leadID"},
            { data: "status",
                render: function ( data ) {
                    if(data == "Lead"){
                        return "<span class='badge badge-primary'>"+data+"</span>";
                    }
                    if(data == "Kunde"){
                        return "<span class='badge badge-info'>"+data+"</span>";
                    }
                    if(data == "Akquise"){
                        return "<span class='badge badge-warning'>"+data+"</span>";
                    }
                    if(data == "Lieferant"){
                        return "<span class='badge badge-success'>"+data+"</span>";
                    }
                    if(data == "Gesperrt"){
                        return "<span class='badge badge-danger'>"+data+"</span>";
                    }
                }
            },
            { data: "firmenname" },
            { data: "branche" },
            { data: "plz" },
            { data: "ort" },
            { data: "strasse" },
            { data: "telefon" },
            { data: "email" }
        ],
        language: {
                    "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/German.json",
                    "decimal": ",",
                }
    })

</code>```

```<code>def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')
    allLeads_list = list(allLeads)

    return JsonResponse(allLeads_list, safe=False)
</code>```

答:
Firstly you should add:

```<code>from django.core.paginator import Paginator
</code>```

This is builded features server-side pagination.
Try with this:

```<code>def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')

    # Add paginator
    paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

    # Add option to read page
    page = request.GET.get('page')  # Add option in ajax or somewhere
    allLeads_list = paginator.get_page(page) # Return objects list you can make json from this or list

    return JsonResponse(allLeads_list, safe=False)

</code>```

I added this line, you can more read about this here(https://docs.djangoproject.com/en/2.2/topics/pagination/):

```<code> # Add paginator
 paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

 # Add option to read page
 page = request.GET.get('page')  # Add option in ajax or somewhere
 allLeads_list = paginator.get_page(page) # Return objects list you can make
</code>```

Body:
I need server-side pagination + individual column search for my django project. Sadly I was not able to implement the pagination.

I searched a lot for working examples but did not find any. I want to implement my server side api myself, there are some django apps but they seem not the be maintained anymore. Following is my datatables code + django view. Anyone here who could give me some advice?

var table = $('#mainTable').DataTable({
        dom: 'Bfrtip',
        responsive: true,
        serverSide: true,
        processing: true,
        pageLength: 25,
        buttons: [
            'csv', 'print',
            {
                extend: 'colvis',
                text: 'Spalten filtern',
                columns: ':not(.noVis)'
            },
        ],
        ajax: {
            url: '/akquise/mainTableData',
            dataSrc: function ( json ) {
                return json;
           }
        },
        columnDefs: [
            { targets: [0,1,2,3,4,5,6,7,8,9], orderable: false},
            { targets: 0, className: "leadID", searchable: false },
            { targets: 3, className: "firmenname" },
        ],
        columns: [
            { data: "leadID",
                render: function ( data, type, row, meta ) {
                    button = '';
                    return button
                }
            },
            { data: "leadID"},
            { data: "status",
                render: function ( data ) {
                    if(data == "Lead"){
                        return ""+data+"";
                    }
                    if(data == "Kunde"){
                        return ""+data+"";
                    }
                    if(data == "Akquise"){
                        return ""+data+"";
                    }
                    if(data == "Lieferant"){
                        return ""+data+"";
                    }
                    if(data == "Gesperrt"){
                        return ""+data+"";
                    }
                }
            },
            { data: "firmenname" },
            { data: "branche" },
            { data: "plz" },
            { data: "ort" },
            { data: "strasse" },
            { data: "telefon" },
            { data: "email" }
        ],
        language: {
                    "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/German.json",
                    "decimal": ",",
                }
    })

def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')
    allLeads_list = list(allLeads)

    return JsonResponse(allLeads_list, safe=False)

Body:
Firstly you should add:

from django.core.paginator import Paginator

This is builded features server-side pagination.
Try with this:

def mainTableData(request):
    search_values = []
    fields = ['leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email']
    for i in range(1, 10):
        value = request.GET.get('columns['+str(i)+'][search][value]')
        search_values.append(value)

    allLeads = Lead.objects.filter(reduce(AND, (Q(**{fields[i]+'__icontains': value} ) for i, value in enumerate(search_values)))).values('leadID', 'status', 'firmenname', 'branche', 'plz', 'ort', 'strasse', 'telefon', 'email')

    # Add paginator
    paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

    # Add option to read page
    page = request.GET.get('page')  # Add option in ajax or somewhere
    allLeads_list = paginator.get_page(page) # Return objects list you can make json from this or list

    return JsonResponse(allLeads_list, safe=False)

I added this line, you can more read about this here(https://docs.djangoproject.com/en/2.2/topics/pagination/):

 # Add paginator
 paginator = Paginator(allLeads, request.GET.get('page_length', 25)) # Show 25 contacts per page

 # Add option to read page
 page = request.GET.get('page')  # Add option in ajax or somewhere
 allLeads_list = paginator.get_page(page) # Return objects list you can make


问:
Unflatten a dot-separated key/value pair into a nested object using Ramda
The Ramda cookbook explains here how to convert a nested object into dot-separated flattened object.
I'm new to Ramda and I would like to learn how to do the reverse of the above.

It would convert this object:

```<code>{
  "company.name": "Name is required",
  "solarSystemInfo.name": "Name is required",
  "installer.business.name": "slkdfj is required"
}
</code>```

to,

```<code>{
  "company": {
    "name": "Name is required"
  },
  "solarSystemInfo": {
    "name": "Name is required"
  },
  "installer": {
    "business": {
      "name": "slkdfj is requried"
    }
  }
}
</code>```

A working fiddle using plain JS is here.

答:
From "Using Reduce you can avoid overwriting of objects with multiple keys."

If you are on Typescript project and you have "Cannot find key" or "val"... you can use:

const data = {
    "company.name": "Name is required",
    "solarSystemInfo.name": "Name is required",
    "installer.business.name": "Reg. name is required",
    "installer.business.code": "NYSE code is required"
}

const buildObj = (acc, value) => {
  const [key,val] = value
  return R.assocPath(R.split('.', key), val, acc);
}

const unflattenObj = R.pipe(
  R.toPairs,
  R.reduce(buildObj,{})
)

console.log(unflattenObj(data))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script></code>```

Body:
The Ramda cookbook explains here how to convert a nested object into dot-separated flattened object.
I'm new to Ramda and I would like to learn how to do the reverse of the above.

It would convert this object:

{
  "company.name": "Name is required",
  "solarSystemInfo.name": "Name is required",
  "installer.business.name": "slkdfj is required"
}

to,

{
  "company": {
    "name": "Name is required"
  },
  "solarSystemInfo": {
    "name": "Name is required"
  },
  "installer": {
    "business": {
      "name": "slkdfj is requried"
    }
  }
}

A working fiddle using plain JS is here.

Body:
From "Using Reduce you can avoid overwriting of objects with multiple keys."

If you are on Typescript project and you have "Cannot find key" or "val"... you can use:

const data = {
    "company.name": "Name is required",
    "solarSystemInfo.name": "Name is required",
    "installer.business.name": "Reg. name is required",
    "installer.business.code": "NYSE code is required"
}

const buildObj = (acc, value) => {
  const [key,val] = value
  return R.assocPath(R.split('.', key), val, acc);
}

const unflattenObj = R.pipe(
  R.toPairs,
  R.reduce(buildObj,{})
)

console.log(unflattenObj(data))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


问:
Creating bitcoin raw transaction takes all balance
I am creating a raw transaction using the bitcoin testnet, but when I push the raw transaction onto the network it takes all my balance. Am I suppose to send the remaining 'change' back to myself? Here is the code im using to create the raw transaction:

```<code>var bitcoin = require('bitcoinjs-lib');

var keyPair = bitcoin.ECPair.fromWIF('cMvPQZiG5mLARSjxbBwMxKwzhTHaxgpTsXB6ymx7SGAeYUqF8HAT', bitcoin.networks.testnet);
var tx = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);

tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);
tx.sign(0, keyPair);

console.log(tx.build().toHex());
</code>```

Am I correct in thinking i also have to send myself back my remaining amount? so for example if my original balance was 0.00114 BTC I would do this:

```<code>tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);

// senders address
tx.addOutput('ms9ySK54aEC2ykDviet9jo4GZE6GxEZMzf ', 104000);

// receivers address
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);
</code>```

Is this the correct way?

答:
Am I correct in thinking i also have to send myself back my remaining amount?

Yes, you are correct. Any funds that are not sent to any specific address can be claimed by the miner as a transaction fee. This is how the transaction fee is created.

Check out the first bitcoin transaction made by Satoshi Nakamoto to Hal Finney in Block 170. Satoshi sent 10BTC to Hal and 40 back to himself. Since it was so early, there was no need for a transaction fee because they were mining the blocks themselves. Today, if you tried to send a transaction with no fee, the nodes would reject it (min. relay fee not met), but even a low fee miners would probably choose not to mine it any time soon (if ever).

Body:
I am creating a raw transaction using the bitcoin testnet, but when I push the raw transaction onto the network it takes all my balance. Am I suppose to send the remaining 'change' back to myself? Here is the code im using to create the raw transaction:

var bitcoin = require('bitcoinjs-lib');

var keyPair = bitcoin.ECPair.fromWIF('cMvPQZiG5mLARSjxbBwMxKwzhTHaxgpTsXB6ymx7SGAeYUqF8HAT', bitcoin.networks.testnet);
var tx = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);

tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);
tx.sign(0, keyPair);

console.log(tx.build().toHex());

Am I correct in thinking i also have to send myself back my remaining amount? so for example if my original balance was 0.00114 BTC I would do this:

tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);

// senders address
tx.addOutput('ms9ySK54aEC2ykDviet9jo4GZE6GxEZMzf ', 104000);

// receivers address
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);

Is this the correct way?


问:
TestCafe - Checking if the hyperlink is working - redirection to an external email provider
On the website is e-mail address (hyperlink) e.g. example@gmail.com, in one of the test scenarios I would like to click on this link and check if the user is redirected to an external e-mail provider, e.g. outlook. Can I do something like that in TestCafe?</p>

答:
TestCafe is designed to interact with the web browser and does not provide a mechanism to track external processes. Thus, it is impossible to verify whether or not an email client application was launched.

At the same time, I do not completely understand the necessity to check if a email client is launching: this behavior is controlled by the operating system and may vary between different machines. It might be more reliable to test whether or not the "mailto" URL is correct. If this works for you, you can use the following code for this purpose:

```<code>await t.expect(Selector('#anchor').getAttribute('href')).eql('mailto:name@mail.com?subject=The%20subject&body=This%20is%20a%20message%20body');
</code>```

Body:
TestCafe is designed to interact with the web browser and does not provide a mechanism to track external processes. Thus, it is impossible to verify whether or not an email client application was launched.

At the same time, I do not completely understand the necessity to check if a email client is launching: this behavior is controlled by the operating system and may vary between different machines. It might be more reliable to test whether or not the "mailto" URL is correct. If this works for you, you can use the following code for this purpose:

await t.expect(Selector('#anchor').getAttribute('href')).eql('mailto:name@mail.com?subject=The%20subject&amp;body=This%20is%20a%20message%20body');


问:
Update a Tkinter text widget as it's written rather than after the class is finished
I'm in a bind, since this is being written on a classified machine I am unable to copy+paste here. Being somewhat a novice, my approach is probably unorthodox.

I have a GUI written in Tkinter with several buttons. Each button is linked to a class that, in effect, runs a short script. When the button is clicked, I inititalize a class log_window which is simply a Tkinter text widget. I then create a global variable linking log to the log_window I just created, and as the script runs I pipe sys.stdout/stderr to log (I created a write method specifically for this). Everything is kosher, except that the log_window text widget doesn't update with my piped stdout until after the class calling it is finished.  However, if I simply print within the class, it will print in the order it is called.

Example

```<code>import Tkinter
from Tkinter import *
import time

class log_window:
    def __init__(self,master):
        self.textframe = Tkinter.Frame(master)
        self.text = Text(self.textframe)
        self.text.pack()
        self.textframe.pack()
    def write(self,text):
        self.text.insert(END,text)

class some_func1: # This effectively waits 5 seconds then prints both lines at once
    def __init__(self,master):
        log.write("some text")
        time.sleep(5)
        log.write("some text")

class some_func2: # This prints the first object, waits 5 seconds, then prints the second
    def __init__(self,master):
        print "some text"
        time.sleep(5)
        print "some text"

if __name__ == '__main__':
    global log
    root = Tk()
    log = log_window(root)
    root.after(100,some_func1, root)
    root.after(100,some_func2, root)
    root.mainloop()
</code>```

Sorry if my example is a little bit muffed, but I think it makes the point.  The piping I do is through Popen and some system calls, but they aren't part of the issue, so I only highlighted what, I presume, is the LCD of the issue.

答: You have to update your widget content by adding self.text.update() after self.text.insert(END,text)

Body:
I'm in a bind, since this is being written on a classified machine I am unable to copy+paste here. Being somewhat a novice, my approach is probably unorthodox.

I have a GUI written in Tkinter with several buttons. Each button is linked to a class that, in effect, runs a short script. When the button is clicked, I inititalize a class log_window which is simply a Tkinter text widget. I then create a global variable linking log to the log_window I just created, and as the script runs I pipe sys.stdout/stderr to log (I created a write method specifically for this). Everything is kosher, except that the log_window text widget doesn't update with my piped stdout until after the class calling it is finished.  However, if I simply print within the class, it will print in the order it is called.

Example

import Tkinter
from Tkinter import *
import time

class log_window:
    def __init__(self,master):
        self.textframe = Tkinter.Frame(master)
        self.text = Text(self.textframe)
        self.text.pack()
        self.textframe.pack()
    def write(self,text):
        self.text.insert(END,text)

class some_func1: # This effectively waits 5 seconds then prints both lines at once
    def __init__(self,master):
        log.write("some text")
        time.sleep(5)
        log.write("some text")

class some_func2: # This prints the first object, waits 5 seconds, then prints the second
    def __init__(self,master):
        print "some text"
        time.sleep(5)
        print "some text"

if __name__ == '__main__':
    global log
    root = Tk()
    log = log_window(root)
    root.after(100,some_func1, root)
    root.after(100,some_func2, root)
    root.mainloop()

Sorry if my example is a little bit muffed, but I think it makes the point.  The piping I do is through Popen and some system calls, but they aren't part of the issue, so I only highlighted what, I presume, is the LCD of the issue.


问:
iOS Navigation bar title truncated after updating it once
Fixed by changing the title update line to:

```<code>self.title = ""
self.title = "\(currentQuestion+1)/\(gameObject!.results.count)"
</code>```

After messing around with constraints to find a good look on every iPhone device, my navigation bar title has ran into an interesting problem. I am making it track the current question in a trivia app but it seems to cut off(I believe the correct word is truncate) the last part of the text after I update it once.

The first time I load a new game view and call a function that contains:

```<code>self.navigationItem.title = "Current question: \(currentQuestion+1)/\(gameObject!.results.count)"
</code>```

The view loads in the first question like this:

https://i.imgur.com/XDRnJsb.png

Once I press the next question button and use the exact same function, it ends up like this:

https://i.imgur.com/53WsKdY.png

I am not changing views, simply updating labels and buttons.

It was working fine this morning so I assume it has something to do with constraints that I messed with. There's also something weird going on with the xCode simulator's clock. It sometimes gets cut off as well and shows something like 2... instead of 2:30. This happens after a minute or so. No amount of interacting will change when or how it happens, it just does.

Clock Image : https://i.imgur.com/8b8n3Fe.png

答: Fixed it and edited the post to reflect that.</p>

Body:
Fixed by changing the title update line to:

self.title = ""
self.title = "\(currentQuestion+1)/\(gameObject!.results.count)"

After messing around with constraints to find a good look on every iPhone device, my navigation bar title has ran into an interesting problem. I am making it track the current question in a trivia app but it seems to cut off(I believe the correct word is truncate) the last part of the text after I update it once.

The first time I load a new game view and call a function that contains:

self.navigationItem.title = "Current question: \(currentQuestion+1)/\(gameObject!.results.count)"

The view loads in the first question like this:

https://i.imgur.com/XDRnJsb.png

Once I press the next question button and use the exact same function, it ends up like this:

https://i.imgur.com/53WsKdY.png

I am not changing views, simply updating labels and buttons.

It was working fine this morning so I assume it has something to do with constraints that I messed with. There's also something weird going on with the xCode simulator's clock. It sometimes gets cut off as well and shows something like 2... instead of 2:30. This happens after a minute or so. No amount of interacting will change when or how it happens, it just does.

Clock Image : https://i.imgur.com/8b8n3Fe.png