问:
Jest: test suite failed to run Error: No message was provided
I am converting existing tests to use typescript with ts-jest and I have everything finding all the files but all of the tests fail with the error

```<code> FAIL  src/components/Buttons/__tests__/index.tsx
  ● Test suite failed to run

    Error: No message was provided
</code>```

I have no idea what is going on and I can't seem to find anyone who had the same problem by Googling either, which is scary...

package.json with jest config

```<code>  "jest": {
    "globals": {
      "ts-jest": {
        "tsConfigFile": "<rootDir>/tsconfig.json",
        "babelConfig": {
          "presets": ["@babel/preset-env", "@babel/preset-react"]
        }
      }
    },
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.ts",
    "verbose": true,
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "typeface-roboto|\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "moduleFileExtensions": [
      "ts", "tsx", "js", "jsx", "json", "node"
    ]
  },
</code>```

example test file...

```<code>import React from 'react';

import { shallow } from 'enzyme';

import Account from '../account';

it('renders without crashing', () => {
  expect(shallow(<Account />)).toBe(1);
});
</code>```

答: I was getting similar error for 3 test suits and one was running perfectly. These were running before code merge. After investigation I found that My components are having AAD authentication and the configuration for the same were missing, which I removed for doing check-in. After adding correct configuration resolved my issue.

Body:
I am converting existing tests to use typescript with ts-jest and I have everything finding all the files but all of the tests fail with the error

 FAIL  src/components/Buttons/__tests__/index.tsx
  ● Test suite failed to run

    Error: No message was provided

I have no idea what is going on and I can't seem to find anyone who had the same problem by Googling either, which is scary...

package.json with jest config

  "jest": {
    "globals": {
      "ts-jest": {
        "tsConfigFile": "<rootDir>/tsconfig.json",
        "babelConfig": {
          "presets": ["@babel/preset-env", "@babel/preset-react"]
        }
      }
    },
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.ts",
    "verbose": true,
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "typeface-roboto|\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "moduleFileExtensions": [
      "ts", "tsx", "js", "jsx", "json", "node"
    ]
  },

example test file...

import React from 'react';

import { shallow } from 'enzyme';

import Account from '../account';

it('renders without crashing', () => {
  expect(shallow(<Account />)).toBe(1);
});


来源: stackexchange

问:
Vue + Vuex: input value not set by store if no store change
```<code><template>
  <input
    @input="formatValue"
    type="text"
    :value="formattedValue"
  />
</template>

<script type="text/javascript">
  import {formatPhoneNumber} from '~/utils/string';

  export default {
    computed: {
      formattedValue: function(){
        return formatPhoneNumber(this.value)
      },
    },
    methods: {
      formatValue(e) {
        this.$emit('input', formatPhoneNumber(e.target.value))
      }
    },
    props: ['value']
  }
</script>
</code>```

As long as the formatPhoneNumber(value) produces a different value, every thing works fine, but once the max length is reached (Since formatPhoneNumber('xx xx xx xx xx whatever') == 'xx xx xx xx xx'), the emitted value is the same as the current store one.

It is totally fine, except that as a consequence, state is not mutated and component is not re-rendered, hence formattedValue() is not called.

So I end up with xx xx xx xx xx in the store, but the input displays xx xx xx xx xx whatever as local input value varies from the store one.

How can I avoid this unexpected behavior? Moving formatPhoneNumber() to the store would not solve my issue since it would still prevent mutation, and only using formatPhoneNumber() in formattedValue() would make me end up with an un-formatted value in the store which is not what I want either.

How come Vue's input with dynamic value set still manages a local state?

答:
I would use a v-model instead of a v-value since that would give me full control over what I want to display in the input field.

In this way, you can format the input value, and then set it back in the model. It would look something like this:

```<code><template>
  <input @input="formatValue" type="text" v-model="inputModel">
</template>

<script type="text/javascript">
export default {
  data() {
    return {
      inputModel: this.value
    };
  },
  methods: {
    formatValue() {
      this.inputModel = formatPhoneNumber(this.inputModel);
      this.$emit("input", this.inputModel);
    }
  },
  props: ["value"]
};
</script>
</code>```

Here's a working example I created to test this.

ContentLicense: CC BY-SA 4.0

Body:
<template>
  <input
    @input="formatValue"
    type="text"
    :value="formattedValue"
  />
</template>

As long as the formatPhoneNumber(value) produces a different value, every thing works fine, but once the max length is reached (Since formatPhoneNumber('xx xx xx xx xx whatever') == 'xx xx xx xx xx'), the emitted value is the same as the current store one.

It is totally fine, except that as a consequence, state is not mutated and component is not re-rendered, hence formattedValue() is not called.

So I end up with xx xx xx xx xx in the store, but the input displays xx xx xx xx xx whatever as local input value varies from the store one.

How can I avoid this unexpected behavior? Moving formatPhoneNumber() to the store would not solve my issue since it would still prevent mutation, and only using formatPhoneNumber() in formattedValue() would make me end up with an un-formatted value in the store which is not what I want either.

How come Vue's input with dynamic value set still manages a local state?

Body:
I would use a v-model instead of a v-value since that would give me full control over what I want to display in the input field.

In this way, you can format the input value, and then set it back in the model. It would look something like this:

<template>
  <input @input="formatValue" type="text" v-model="inputModel">
</template>

<script type="text/javascript">
export default {
  data() {
    return {
      inputModel: this.value
    };
  },
  methods: {
    formatValue() {
      this.inputModel = formatPhoneNumber(this.inputModel);
      this.$emit("input", this.inputModel);
    }
  },
  props: ["value"]
};
</script>

Here's a working example I created to test this.


问:
Getting 401 error on api request using RestClient::Request authorization header in Ruby
The api documentation calls for a returned token after authorizing using a username, password. I added the returned token, but I keep receiving a 401 response.

Here is the curl request in the api documentation:

```<code>curl \
  -H "Authorization: Token token=\"be08f1f4-c315-4d59-9c7c-d7a8b45a7db5\""
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  https://something.fake/api/lists
</code>```

And here is my code using Rest::Client:

```<code>RestClient::Request.execute(
    method: post,
    url:  https://something.fake/api/lists,
    :content_type => :json,
    :accept => :json,
    headers: {"Authorization" => "Token token=${token}"}
   )
</code>```

I am not sure what I am missing.

答:
The curl request has the token in quotes. So it won't be

```<code>token=be08f1f4-c315-4d59-9c7c-d7a8b45a7db5
</code>```

it'll be

```<code>token="be08f1f4-c315-4d59-9c7c-d7a8b45a7db5"
</code>```

so your code needs to be:

```<code>headers: {"Authorization" => "Token token=\"${token}\""}
</code>```

Body:
The api documentation calls for a returned token after authorizing using a username, password. I added the returned token, but I keep receiving a 401 response.

Here is the curl request in the api documentation:

curl \
  -H "Authorization: Token token=\"be08f1f4-c315-4d59-9c7c-d7a8b45a7db5\""
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  https://something.fake/api/lists

And here is my code using Rest::Client:

RestClient::Request.execute(
    method: post,
    url:  https://something.fake/api/lists,
    :content_type => :json,
    :accept => :json,
    headers: {"Authorization" => "Token token=${token}"}
   )

I am not sure what I am missing.

Body:
The curl request has the token in quotes. So it won't be

token=be08f1f4-c315-4d59-9c7c-d7a8b45a7db5

it'll be

token="be08f1f4-c315-4d59-9c7c-d7a8b45a7db5"

so your code needs to be:

headers: {"Authorization" => "Token token=\"${token}\""}


问:
Laravel database relationships not working
What am I doing wrong here?

My entradas table:

Schema::create('entradas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('categoria_id');
            $table->string('descricao', 200);
            $table->double('valor');
            $table->timestamps();
        });
```

<p>My <code>categorias</code> table:</p>

<pre class="lang-php prettyprint-override"><code>Schema::create('categorias', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('titulo', 100);
            $table->enum('tipo', ['debito', 'credito']);
            $table->timestamps();
        });
</code>```

My Entrada model:

public function categoria()
    {
        return $this->belongsTo('App\Categoria');
    }
```

<p>My <code>Categoria</code> model:</p>

<pre class="lang-php prettyprint-override"><code>public function entradas()
    {
        return $this->hasMany('App\Entrada');
    }
</code>```

Returning this on my EntradaController:

public function index() {
        return(Entrada::find(1));
    }
```

<p>I get the following result:</p>

```{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quia ea voluptatem pariatur et. Tenetur maiores mollitia molestias asperiores. Exercitationem maiores voluptas id dolore rerum unde. Ipsum dolorem facere aut ut quos.",
    "valor": 108,
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}
```

Why don't I get the categoria property?

答:
You have to eager load your categoria property in order to get it, like this:

```<code>public function index () {
    return Entrada::with('categoria')->find(1);
}
</code>```

More info in the docs here

Body:
What am I doing wrong here?

My entradas table:

Schema::create('entradas', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('categoria_id');
            $table->string('descricao', 200);
            $table->double('valor');
            $table->timestamps();
        });

My categorias table:

Schema::create('categorias', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('titulo', 100);
            $table->enum('tipo', ['debito', 'credito']);
            $table->timestamps();
        });

My Entrada model:

public function categoria()
    {
        return $this->belongsTo('App\Categoria');
    }

My Categoria model:

public function entradas()
    {
        return $this->hasMany('App\Entrada');
    }

Returning this on my EntradaController:

public function index() {
        return(Entrada::find(1));
    }

I get the following result:

{
    "id": 1,
    "categoria_id": 3,
    "descricao": "Distinctio minus praesentium quia ea voluptatem pariatur et. Tenetur maiores mollitia molestias asperiores. Exercitationem maiores voluptas id dolore rerum unde. Ipsum dolorem facere aut ut quos.",
    "valor": 108,
    "created_at": "2020-02-17 17:49:36",
    "updated_at": "2020-02-17 17:49:36"
}

Why don't I get the categoria property?

Body:
You have to eager load your categoria property in order to get it, like this:

public function index () {
    return Entrada::with('categoria')->find(1);
}

More info in the docs here


问:
What is a synthetic image?
I don't understand what is a synthetic image in computer vision.
And what are the differences between optical image and synthetic image?

Here's an example of the question. It's a screen shot of a research paper:

答:
A real image is obtained by an imaging device such as a camera, which converts the light from a scene to pixel values. Due to the image formation process that obeys the laws of physics, real images are rich, complex and often noisy and textured. The real world contains a lot of information.

A synthetic image is obtained "out of the blue" by pure computation, i.e. by modelling the real world and simulating the laws of optics.

Two decades ago, you could spot a synthetic image at a glance, because it was lacking realism and was obtained through too simple models (in part due to heavy computation costs). This is no more true nowadays, they tend to be indistinguishable.

Note that in scientific contexts, they can be using very simple images (say a chessboard) for experimental purposes, for instance testing an image filter.

For instance, the scene below has been synthetized by armies of researchers, with the goal of finding the most realistic lighting simulation. This room never existed.

Title: What is a synthetic image?


问:
Android error - Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.SparseArrayCompat
I have these log errors when launching my app:

```<code>> 05-20 01:48:35.312: E/AndroidRuntime(23032): FATAL EXCEPTION: main
05-20 01:48:35.312: E/AndroidRuntime(23032): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomsyweb.suna/com.tomsyweb.suna.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class com.origamilabs.library.views.StaggeredGridView
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.os.Looper.loop(Looper.java:130)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.main(ActivityThread.java:3687)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Method.invokeNative(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Method.invoke(Method.java:507)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at dalvik.system.NativeStart.main(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.origamilabs.library.views.StaggeredGridView
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createView(LayoutInflater.java:518)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:853)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.actionbarsherlock.app.SherlockActivity.setContentView(SherlockActivity.java:229)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.tomsyweb.suna.MainActivity.onCreate(MainActivity.java:72)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 11 more
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: java.lang.reflect.InvocationTargetException
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Constructor.constructNative(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createView(LayoutInflater.java:505)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 21 more
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.SparseArrayCompat
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.origamilabs.library.views.StaggeredGridView.<init>(StaggeredGridView.java:297)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.origamilabs.library.views.StaggeredGridView.<init>(StaggeredGridView.java:304)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 24 more
</code>```

And the problem appeared just after installing Android SDK Tools Rev. 22, Android SDK Build-tools and updating Google Play Services.

Whereas in this error

Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.SparseArrayCompat

and noting that for all "android.support.v4" import, the Javadoc isn't accessible

Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.

the problem is probably due to the Android support library.

Hope all this information will help you find a solution.

答:
You might wanna check from official android documentation.

I've occurred this error below when running my apps to my minimum SDK (15):

```<code>Fatal Exception: java.lang.NoSuchMethodError: android.util.LongSparseArray.removeAt
</code>```

After reading actual android documentation here:
https://developer.android.com/reference/android/util/LongSparseArray (sadly only added in API Level 16)

If you using 3rd-party libraries (in my case, I'm using Chuck), you might wanna ask them about supporting your minimum level SDK API. Otherwise, increase your minimum SDK to match the minimum API library had or do this (not recommended, will crash your apps)

```<code>// AndroidManifest
<manifest
  <uses-sdk tools:overrideLibrary="com.readystatesoftware.chuck, your.another.package.here" />

  <application>
  // ommited...
  </application>
</manifest
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have these log errors when launching my app:

> 05-20 01:48:35.312: E/AndroidRuntime(23032): FATAL EXCEPTION: main
05-20 01:48:35.312: E/AndroidRuntime(23032): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomsyweb.suna/com.tomsyweb.suna.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class com.origamilabs.library.views.StaggeredGridView
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.os.Looper.loop(Looper.java:130)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.main(ActivityThread.java:3687)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Method.invokeNative(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Method.invoke(Method.java:507)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at dalvik.system.NativeStart.main(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.origamilabs.library.views.StaggeredGridView
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createView(LayoutInflater.java:518)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:853)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.actionbarsherlock.app.SherlockActivity.setContentView(SherlockActivity.java:229)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.tomsyweb.suna.MainActivity.onCreate(MainActivity.java:72)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 11 more
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: java.lang.reflect.InvocationTargetException
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Constructor.constructNative(Native Method)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at android.view.LayoutInflater.createView(LayoutInflater.java:505)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 21 more
05-20 01:48:35.312: E/AndroidRuntime(23032): Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.SparseArrayCompat
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.origamilabs.library.views.StaggeredGridView.<init>(StaggeredGridView.java:297)
05-20 01:48:35.312: E/AndroidRuntime(23032):    at com.origamilabs.library.views.StaggeredGridView.<init>(StaggeredGridView.java:304)
05-20 01:48:35.312: E/AndroidRuntime(23032):    ... 24 more

And the problem appeared just after installing Android SDK Tools Rev. 22, Android SDK Build-tools and updating Google Play Services.

Whereas in this error

Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.SparseArrayCompat

and noting that for all "android.support.v4" import, the Javadoc isn't accessible

Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.

the problem is probably due to the Android support library.

Hope all this information will help you find a solution.

Body:
You might wanna check from official android documentation.

I've occurred this error below when running my apps to my minimum SDK (15):

Fatal Exception: java.lang.NoSuchMethodError: android.util.LongSparseArray.removeAt

After reading actual android documentation here:
https://developer.android.com/reference/android/util/LongSparseArray (sadly only added in API Level 16)

If you using 3rd-party libraries (in my case, I'm using Chuck), you might wanna ask them about supporting your minimum level SDK API. Otherwise, increase your minimum SDK to match the minimum API library had or do this (not recommended, will crash your apps)

// AndroidManifest
<manifest
  <uses-sdk tools:overrideLibrary="com.readystatesoftware.chuck, your.another.package.here" />

  <application>
  // ommited...
  </application>
</manifest


问:
Cakephp 4 : How to save hasone data
I have two database table 1) users 2) profiles

profiles has a field called bank_ac

I am trying to save it from user model.

I have created form input like

```<code><?= $this->Form->create($user) ?>
   <?= $this->Form->control('profile.bank_ac'); ?>
<?= $this->Form->end() ?>
</code>```

User model I have added associative like

```<code>$this->hasOne('Profiles');
</code>```

After debug getting data like

```<code>[
    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    'profile' => [
        'bank_ac' => '1212212'
    ]
]
</code>```

after debug patch entity

```<code>object(App\Model\Entity\User) {

    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    '[new]' => true,
    '[accessible]' => [
        'name' => true,
        'email' => true,
        'created' => true,
        'modified' => true
    ],
    '[dirty]' => [
        'name' => true,
        'email' => true,
        'profile' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Users'

}
</code>```

In UsersController/add I have applied code like

```<code>public function add(){

        $user = $this->Users->newEmptyEntity();

        $user = $this->Users->patchEntity($user, $this->request->getData());

        $this->Users->save($user, ['associated' => ['Profiles']]);

}
</code>```

Profile data not saving , also not getting any error. How can I save this associative data ?

答:
Looking at your entity debug result, the profile field is missing from the accessibility config, hence disallowing its use in mass assignment (patching).

Add it to your User::$_accessible property, and it should work:

```<code>protected $_accessible = [
    // ...
    'profile' => true,
];
</code>```

See also

Cookbook > Database Access & ORM > Entities > Mass Assignment

Title: Cakephp 4 : How to save hasone data

Body:
I have two database table 1) users 2) profiles

profiles has a field called bank_ac

I am trying to save it from user model.

I have created form input like

<?= $this->Form->create($user) ?>
   <?= $this->Form->control('profile.bank_ac'); ?>
<?= $this->Form->end() ?>

User model I have added associative like

$this->hasOne('Profiles');

After debug getting data like

[
    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    'profile' => [
        'bank_ac' => '1212212'
    ]
]

after debug patch entity

object(App\Model\Entity\User) {

    'name' => 'Jone',
    'email' => 'abcd@yahoo.com',
    '[new]' => true,
    '[accessible]' => [
        'name' => true,
        'email' => true,
        'created' => true,
        'modified' => true
    ],
    '[dirty]' => [
        'name' => true,
        'email' => true,
        'profile' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Users'

}

In UsersController/add I have applied code like

public function add(){

        $user = $this->Users->newEmptyEntity();

        $user = $this->Users->patchEntity($user, $this->request->getData());

        $this->Users->save($user, ['associated' => ['Profiles']]);

}

Profile data not saving , also not getting any error. How can I save this associative data ?

Body:
Looking at your entity debug result, the profile field is missing from the accessibility config, hence disallowing its use in mass assignment (patching).

Add it to your User::$_accessible property, and it should work:

protected $_accessible = [
    // ...
    'profile' => true,
];

See also

Cookbook > Database Access & ORM > Entities > Mass Assignment


答:
Here is a more long winded solution where I print out the various steps.

Create the sample dataset with numpy. The dimensions and values will be altered from the question to make the response more clear. rawmat will be a 10 by 10 matrix of zeros and ones except for the first column which are larger values. Among the zeros and ones there is a 50 percent probability of a one being obtained.

```<code>import numpy as np
np.random.seed(1000)
rawmat = np.random.randint(2,size=(10,10))
# insert higher values in the first column
rawmat[:,0] = np.random.randint(low=5,high=9,size=10)
print(rawmat)
</code>```

[[5 1 1 0 1 0 0 1 1 0]

 [6 1 0 1 0 1 0 0 1 1]

 [5 0 1 0 0 0 0 1 0 0]

 [6 0 0 0 1 0 0 1 1 0]

 [6 0 1 1 0 1 0 1 0 0]

 [5 1 0 0 1 0 0 1 0 1]

 [5 1 1 0 1 0 1 0 1 1]

 [5 1 1 1 1 1 1 0 1 1]

 [7 1 1 1 0 0 0 0 1 1]

 [8 0 0 0 1 1 0 1 1 0]]

Out of 100 cells, 90 are now zero or one. In fact 46 are 1, which is reasonable given the 50 per cent probability.

```<code>np.count_nonzero(rawmat==1)
</code>```

46

We can creat a mask where 50 percent of the relevant observations are true with randmask. However, the trick in this questions is to just focus on the ones, so we get this with rawones.

```<code>randmask = np.random.choice(a=[False, True], size=(10,10),p=[0.5,0.5])
rawones = np.where(rawmat==1,rawmat,0)
onefin = np.where(randmask,onemask,np.zeros((10,10),dtype=int))
</code>```

Now the number of ones will drop by rougly half. Initially there were 46 ones in rawmat and now there are 23 in onefine.

```<code>np.count_nonzero(onefin==1)
</code>```

23

The filtered ones can be recombined with the old data to get a matrix with half the ones.

```<code>finmat = np.where(rawmat==1,onefin,rawmat)
print(finmat)
</code>```

[[5 0 0 0 0 0 0 1 1 0]

 [6 1 0 1 0 0 0 0 1 0]

 [5 0 1 0 0 0 0 1 0 0]

 [6 0 0 0 0 0 0 1 0 0]

 [6 0 0 1 0 0 0 0 0 0]

 [5 1 0 0 1 0 0 0 0 1]

 [5 0 1 0 1 0 1 0 0 0]

 [5 1 0 0 1 1 0 0 1 1]

 [7 1 1 0 0 0 0 0 0 0]

 [8 0 0 0 0 1 0 0 0 0]]

Now we have the original matrix with the number of ones dropped by one half from 46 to 23.

```<code>np.count_nonzero(finmat==1)
</code>```

23

Title: add random noise in a dataframe

Body:
i have a dataframe with this kind of data :

      0    1    2    3    4    5    6    7    8    9    10   11   12   13   14   15   16   17   18   19   ...  309  310  311  312  313  314  315  316  317  318  319  320  321  322  323  324  325  326  327  328
0      18    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0
1      84    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0
2      50    1    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0

the df shape is (10000, 329)

I would like to turn random 5% of  1 in the dataframe  to 0.

Is this possible?

Body:
Here is a more long winded solution where I print out the various steps.

Create the sample dataset with numpy. The dimensions and values will be altered from the question to make the response more clear. rawmat will be a 10 by 10 matrix of zeros and ones except for the first column which are larger values. Among the zeros and ones there is a 50 percent probability of a one being obtained.

import numpy as np
np.random.seed(1000)
rawmat = np.random.randint(2,size=(10,10))
# insert higher values in the first column
rawmat[:,0] = np.random.randint(low=5,high=9,size=10)
print(rawmat)

[[5 1 1 0 1 0 0 1 1 0]

 [6 1 0 1 0 1 0 0 1 1]

 [5 0 1 0 0 0 0 1 0 0]

 [6 0 0 0 1 0 0 1 1 0]

 [6 0 1 1 0 1 0 1 0 0]

 [5 1 0 0 1 0 0 1 0 1]

 [5 1 1 0 1 0 1 0 1 1]

 [5 1 1 1 1 1 1 0 1 1]

 [7 1 1 1 0 0 0 0 1 1]

 [8 0 0 0 1 1 0 1 1 0]]

Out of 100 cells, 90 are now zero or one. In fact 46 are 1, which is reasonable given the 50 per cent probability.

np.count_nonzero(rawmat==1)

46

We can creat a mask where 50 percent of the relevant observations are true with randmask. However, the trick in this questions is to just focus on the ones, so we get this with rawones.

randmask = np.random.choice(a=[False, True], size=(10,10),p=[0.5,0.5])
rawones = np.where(rawmat==1,rawmat,0)
onefin = np.where(randmask,onemask,np.zeros((10,10),dtype=int))

Now the number of ones will drop by rougly half. Initially there were 46 ones in rawmat and now there are 23 in onefine.

np.count_nonzero(onefin==1)

23

The filtered ones can be recombined with the old data to get a matrix with half the ones.

finmat = np.where(rawmat==1,onefin,rawmat)
print(finmat)

[[5 0 0 0 0 0 0 1 1 0]

 [6 1 0 1 0 0 0 0 1 0]

 [5 0 1 0 0 0 0 1 0 0]

 [6 0 0 0 0 0 0 1 0 0]

 [6 0 0 1 0 0 0 0 0 0]

 [5 1 0 0 1 0 0 0 0 1]

 [5 0 1 0 1 0 1 0 0 0]

 [5 1 0 0 1 1 0 0 1 1]

 [7 1 1 0 0 0 0 0 0 0]

 [8 0 0 0 0 1 0 0 0 0]]

Now we have the original matrix with the number of ones dropped by one half from 46 to 23.

np.count_nonzero(finmat==1)

23


问:
Composer update : Trying to access array offset on value of type null
I updated my server with PHP 7.4.2 and now I am getting this :

```<code>~/public_html/infusionsoft$ php composer.phar update

  [ErrorException]
  Trying to access array offset on value of type null
</code>```

I had to revert back to 7.3.14 and it works. But is composer not PHP 7.4 ready ?

答:
This is a composer issue and has been fixed in this release: https://github.com/composer/composer/pull/8296

In order to fix this issue please update your composer.

Body:
I updated my server with PHP 7.4.2 and now I am getting this :

~/public_html/infusionsoft$ php composer.phar update

  [ErrorException]
  Trying to access array offset on value of type null

I had to revert back to 7.3.14 and it works. But is composer not PHP 7.4 ready ?


问:
having trouble writing a dataframe to an sqlite database
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Here is the exact code to reproduce the error

go to this page with dev tools open

https://stats.nba.com/teams/boxscores-traditional/

on teamgamelogs endpoint right click -> Copy -> copy as curl(bash)

convert to python requests
https://curl.trillworks.com/

```<code>import pandas as pd
import requests
import sqlite3

response = requests.get('https://stats.nba.com/stats/teamgamelogs?DateFrom=&DateTo=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlusMinus=N&Rank=N&Season=2019-20&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&VsConference=&VsDivision=', headers=headers, cookies=cookies)

conn = sqlite3.connect('nbastats.db')
stats = response.json()

df = pd.DataFrame(stats["resultSets"])

df.to_sql('Team_stats', conn, if_exists='append')
</code>```

I dont understand why I am getting this error.

```<code>sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
</code>```

答:
I cannot get access to the page you have cited. Nonetheless, you need to engineer data before putting it to the SQL from dataframe. Check for data types:

```<code> df.dtypes()
</code>```

If there is "object" in the second column, then you need to check whether it is sql supported type.

Body:
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Here is the exact code to reproduce the error

go to this page with dev tools open

https://stats.nba.com/teams/boxscores-traditional/

on teamgamelogs endpoint right click -> Copy -> copy as curl(bash)

convert to python requests
https://curl.trillworks.com/

import pandas as pd
import requests
import sqlite3

response = requests.get('https://stats.nba.com/stats/teamgamelogs?DateFrom=&DateTo=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlusMinus=N&Rank=N&Season=2019-20&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&VsConference=&VsDivision=', headers=headers, cookies=cookies)

conn = sqlite3.connect('nbastats.db')
stats = response.json()

df = pd.DataFrame(stats["resultSets"])

df.to_sql('Team_stats', conn, if_exists='append')

I dont understand why I am getting this error.

sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Body:
I cannot get access to the page you have cited. Nonetheless, you need to engineer data before putting it to the SQL from dataframe. Check for data types:

 df.dtypes()

If there is "object" in the second column, then you need to check whether it is sql supported type.


问:
Why Do I Keep Getting Errors About Else Statements?
Let the function f be defined by the rule that for n ≥ 0, f(n) = n if n < 3 and f(n) = f(n − 1) + 2f(n − 2)
if n ≥ 3. Use a for loop to implement f in R

Here is my loop and errors

for (i in 0:10) {
  if (i < 3)
    print(i)
  } else if (i >= 3) {
Error: unexpected 'else' in:
"    print(i)
  } else"
>     print((i-1)+2(i-2))
Error in print((i - 1) + 2(i - 2)) : attempt to apply non-function
>   }
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"
```

This has been a recurring theme on the else statements. Why are they not working?

答:
This question should likely be closed as "typo", but here is something visual to look for when working on code: most code editors support "paren-matching", which is usually extended to include brackets and braces. Most editors also support keyboard shortcuts to navigate to the matching paren/brace/bracket.

Rstudio: if I place my cursor immediately to the right of the close(right)-brace, (RStudio is only highlighting the matching brace), you'll see the matching brace highlighted. Use Ctrl-P to move to the matching brace.

If you're a Notepad++ user, then it shows both (in red, in this theme). Use Ctrl-B to move to the matching brace.

Lastly, if you by chance use Emacs/ESS, it also highlights both. The default emacs shortcuts are C-M-p (back) and C-M-n (forward).

In short, in this case one might notice that the matching opening brace is on a for line, not the if line, and correct accordingly.

The correct code, including @akash87's fix, is

for (i in 0:10) {
  if (i < 3) {
    print(i)
  } else if (i >= 3) {
    print((i-1)+2*(i-2))
  }
}
```

<p>or, slightly reduced:</p>

<pre class="lang-r prettyprint-override"><code>for (i in 0:10) {
  if (i < 3) {
    print(i)
  } else {
    print((i-1)+2(i-2))
  }
}
</code>```

Body:
Let the function f be defined by the rule that for n ≥ 0, f(n) = n if n < 3 and f(n) = f(n − 1) + 2f(n − 2)
if n ≥ 3. Use a for loop to implement f in R

Here is my loop and errors

for (i in 0:10) {
  if (i < 3)
    print(i)
  } else if (i >= 3) {
Error: unexpected 'else' in:
"    print(i)
  } else"
>     print((i-1)+2(i-2))
Error in print((i - 1) + 2(i - 2)) : attempt to apply non-function
>   }
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"

This has been a recurring theme on the else statements. Why are they not working?

Body:
This question should likely be closed as "typo", but here is something visual to look for when working on code: most code editors support "paren-matching", which is usually extended to include brackets and braces. Most editors also support keyboard shortcuts to navigate to the matching paren/brace/bracket.

Rstudio: if I place my cursor immediately to the right of the close(right)-brace, (RStudio is only highlighting the matching brace), you'll see the matching brace highlighted. Use Ctrl-P to move to the matching brace.

If you're a Notepad++ user, then it shows both (in red, in this theme). Use Ctrl-B to move to the matching brace.

Lastly, if you by chance use Emacs/ESS, it also highlights both. The default emacs shortcuts are C-M-p (back) and C-M-n (forward).

In short, in this case one might notice that the matching opening brace is on a for line, not the if line, and correct accordingly.

The correct code, including @akash87's fix, is

for (i in 0:10) {
  if (i < 3) {
    print(i)
  } else if (i >= 3) {
    print((i-1)+2*(i-2))
  }
}

or, slightly reduced:

for (i in 0:10) {
  if (i < 3) {
    print(i)
  } else {
    print((i-1)+2(i-2))
  }
}


问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答:
you must return a valid image, use file_get_contents or readfile for get the conent of image then output to browser</p>

```<code> header("Content-Type:image/png");

    $image_id = $_GET['image_id'];

    if(is_file($file = "image".$image_id.".png") ||  is_file($file = "no_image.png"))
        readfile($file);
</code>```

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";

Body:
you must return a valid image, use file_get_contents or readfile for get the conent of image then output to browser

 header("Content-Type:image/png");

    $image_id = $_GET['image_id'];

    if(is_file($file = "image".$image_id.".png") ||  is_file($file = "no_image.png"))
        readfile($file);


问:
How compare third one in each array in each line?
If I have two array

```<code>A = [ "B,C,D"
      "W,F,G"
      "M,S,E"
    ]
D = [E]
</code>```

and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable .
I wrote this code but didn't give me the response that I need have :

```<code> for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] === E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }
</code>```

How can I improve my code to get that line that have my equal variable?

答:
You could filter the array and have a look up with includes.

var array = ["B,C,D", "W,F,G", "M,S,E"],
    pattern = ['E'],
    result = array.filter(s => pattern.includes(s.split(',')[2]));

console.log(result);```
</div>
</div>
</p>

<p>If you need only the first one, take <code>find</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = ["B,C,D", "W,F,G", "M,S,E"],
    pattern = ['E'],
    result = array.find(s => pattern.includes(s.split(',')[2]));

console.log(result);</code>```

Body:
If I have two array

A = [ "B,C,D"
      "W,F,G"
      "M,S,E"
    ]
D = [E]

and want to compare D OR G with E (I mean the third one in each line)and If they are equal can show all the line for me. The third one in each line a part of each line and I want just compare the third one If it is equal show that line have equal variable .
I wrote this code but didn't give me the response that I need have :

 for(var k=0 ; k<A.length ; k++){
    if(A[k].split(",")[2] === E) {
       finalSuccessServices = A;
       console.log(finalSuccessServices );
     }

How can I improve my code to get that line that have my equal variable?

Body:
You could filter the array and have a look up with includes.

var array = ["B,C,D", "W,F,G", "M,S,E"],
    pattern = ['E'],
    result = array.filter(s => pattern.includes(s.split(',')[2]));

console.log(result);

If you need only the first one, take find.

var array = ["B,C,D", "W,F,G", "M,S,E"],
    pattern = ['E'],
    result = array.find(s => pattern.includes(s.split(',')[2]));

console.log(result);


问:
How to remove spaces only before the First letter
How to remove spaces only before the First letter and do not change to other words / text in line.

答:
Notepad++

Just press ALT while at the same time select with the mouse the first column. This is called "column mode". When done, just press delete to delete the first column just selected.

You can also use: ALT + SHITF + Arrow Key to select the black chars in the first column.


问:
Writing a loop/exception for JSONDecodeError
I'm trying to build a program that will print JSON results in a Tkinter GUI, but I have run into the issue of:
What if the image being posted is clear enough to get a result?

I know I can use a if, else loop or an exception, but I have not been able to get the result I want of a GUI that tells the user there is an error if one occurs.

The error I'm getting in the terminal is:

```<code>File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

And my code thus far is:

```<code>if: json.decoder.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be analyzed!', font='Verdana 70 bold').pack()
    oops.after(5000, oops.destroy)

else:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
</code>```

I have tried a try, except exception such as this as well without getting my desired result as well:

```<code>try:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except json.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be nalyzed!', font='Verdana 70 bold').pack()
</code>```

Any help would be appreciated, thanks!

答:
This code solved my problem: I had needed to add an exception later in my script as well when printing results.

Additionally, i foolishly forgot to add a mainloop line

```<code>try:
    global name
    name = date_time + "_result.json"
    file = open(name, 'wb')
    global data
    data = response.content
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(window_width/2)
    position_down = int(window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops!', font='Verdana 80 bold').pack()
    detail = tk.Label(oops, text='Your Photo could not be analyzed', font='Verdana 60').pack()
    oops.after(5000, oops.destroy)
    oops.mainloop()
</code>```

Body:
I'm trying to build a program that will print JSON results in a Tkinter GUI, but I have run into the issue of:
What if the image being posted is clear enough to get a result?

I know I can use a if, else loop or an exception, but I have not been able to get the result I want of a GUI that tells the user there is an error if one occurs.

The error I'm getting in the terminal is:

File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

And my code thus far is:

if: json.decoder.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be analyzed!', font='Verdana 70 bold').pack()
    oops.after(5000, oops.destroy)

else:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)

I have tried a try, except exception such as this as well without getting my desired result as well:

try:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except json.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be nalyzed!', font='Verdana 70 bold').pack()

Any help would be appreciated, thanks!

Body:
This code solved my problem: I had needed to add an exception later in my script as well when printing results.

Additionally, i foolishly forgot to add a mainloop line

try:
    global name
    name = date_time + "_result.json"
    file = open(name, 'wb')
    global data
    data = response.content
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(window_width/2)
    position_down = int(window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops!', font='Verdana 80 bold').pack()
    detail = tk.Label(oops, text='Your Photo could not be analyzed', font='Verdana 60').pack()
    oops.after(5000, oops.destroy)
    oops.mainloop()


问:
Call an object in another method
I want to use an object of a method in an another method.
How can i do this ?

I got an object named "cell". I custom it in cellForRowAtIndexPath.
I want to custom it in didSelectRowAtIndexPath.

Thanks for help!

Flo

答:
You need to make a global variable that changes when you press didSelectRowAtIndexPath. Then when you've changed that variable, call [theTableView reloadData]. This forces the UITableView to reload all cells that can be seen (which calls cellForRowAtIndexPath again).

If you're trying to add a check box or something like that you might want to add a NSMutableArray and store the boolean values for each cell in there and use the parameter indexPath.row to find out which object you need to change in that array when calling didSelectRowAtIndexPath.

Title: Call an object in another method


答:
You can use find() to get the matching string, provided you have a single match:

const A = [ "B,C,D",
      "W,F,G",
      "M,S,E"
    ];
const D = ['E'];

let result = A.find(str => str.split(',')[2] === D[0]);

console.log(result)```

Title: How compare third one in each array in each line?


问:
Problem with edit function using a modal Laravel
I have the next function

```<code>public function edit($id)
{
    if(request()->ajax())
    {
        $data = Tbl_Perimetro::findOrFail($id);
        return response()->json(['result' => $data]);

    }
}

public function update(Request $request, Tbl_Perimetro $user)
{
    $rules = array(
        'rif'      =>  'required',
        'razon_social'  =>  'required',
        'holdings_id' => 'required',
        'pines_id' => 'required'

    );

    $error = Validator::make($request->all(), $rules);

    if($error->fails())
    {
        return response()->json(['errors' => $error->errors()->all()]);
    }

    $form_data = array(
        'rif'        =>  $request->rif,
        'razon_social'    =>  $request->razon_social,
        'holdings_id' => $request->holdings_id,
        'pines_id' => $request->pines_id

    );

    Tbl_Perimetro::whereId($request->hidden_id)->update($form_data);

    return response()->json(['success' => 'Datos actualizados satisfactoriamente.']);

}
</code>```

My problem is that I would like to work with some models... and I know how to work with one model which is Tbl_Perimetro... I would like to work with another model called Tbl_Holding, But I'm using a modal to edit all this information.. here is the code of the modal:

```<code>$('#create_record').click(function(){
$('.modal-title').text('Add New Record');
$('#action_button').val('Add');
$('#action').val('Add');
$('#form_result').html('');

  $('#formModal').modal('show');
 });

$('#user_form').on('submit', function(event){
event.preventDefault();
var action_url = '';

if($('#action').val() == 'Add')
{
action_url = "{{ route('perimetro.store') }}";
}
if($('#action').val() == 'Editar')
{
action_url = "{{ route('perimetro.update') }}";
}
  $.ajax({
url: action_url,
method:"POST",
data:$(this).serialize(),
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
 html = '<div class="alert alert-danger">';
 for(var count = 0; count < data.errors.length; count++)
 {
  html += '<p>' + data.errors[count] + '</p>';
 }
 html += '</div>';
}
if(data.success)
{
 html = '<div class="alert alert-success">' + data.success + '</div>';
 $('#user_form')[0].reset();
 $('#user_perimetro').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});

 $(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');

$.ajax({

url :"/perimetro/"+id+"/edit",
dataType:"json",
success:function(data)
 {
$('#rif').val(data.result.rif);
$('#razon_social').val(data.result.razon_social);
$('#holdings_id').val(data.result.holdings_id);
$('#pines_id').val(data.result.pines_id);
$('#carteras_id').val(data.result.carteras_id);
$('#hidden_id').val(id);
$('.modal-title').text('Editar Registro');
$('#action_button').val('Editar');
$('#action').val('Editar');
$('#formModal').modal('show');
}
})
});
</code>```

This is the button to edit the information

```<code>$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Editar</button>';
</code>```

I would like to know is it exist a way to work with two models in the same modal... In this way I only can work with one model at the same time...

答:
I think I got what you mean...

What you can do is using a route with 2 variables passed, the first variable could be the id of the tbl_perimetro and the 2nd variable could be the id of the tbl_holding.

So, this would fit like this:

```<code>public function edit($id, $idholding)
{
    if(request()->ajax())
    {
        $data = Tbl_Perimetro::findOrFail($id);
        $data1 = Tbl_Holding::findOrFail($idholding);
        $alldata = array($data, $data1);  //----->THIS WILL BREAK YOUR JSON STRUCTURE BE CAREFUL
        return response()->json(['result' => $alldata]);

    }
}
</code>```

And the same in the update function:

```<code>public function update(Request $request, Tbl_Perimetro $user, Tbl_Holding $holding)
{
    ...
}
</code>```

Be careful editing your routes, because starting in laravel 6 (I think) the variables HAVE to be literal, so the new routes have to match the variable name of the function p.ex:

```<code>Route::get('editmodels/{id}/{idholding}','Controller@edit'); //<----This will work
Route::get('editmodels/{id}/{id2}','Controller@edit'); //<----This won't work
</code>```

Hope it helps!!

Body:
I have the next function

public function edit($id)
{
    if(request()->ajax())
    {
        $data = Tbl_Perimetro::findOrFail($id);
        return response()->json(['result' => $data]);

    }
}

public function update(Request $request, Tbl_Perimetro $user)
{
    $rules = array(
        'rif'      =>  'required',
        'razon_social'  =>  'required',
        'holdings_id' => 'required',
        'pines_id' => 'required'

    );

    $error = Validator::make($request->all(), $rules);

    if($error->fails())
    {
        return response()->json(['errors' => $error->errors()->all()]);
    }

    $form_data = array(
        'rif'        =>  $request->rif,
        'razon_social'    =>  $request->razon_social,
        'holdings_id' => $request->holdings_id,
        'pines_id' => $request->pines_id

    );

    Tbl_Perimetro::whereId($request->hidden_id)->update($form_data);

    return response()->json(['success' => 'Datos actualizados satisfactoriamente.']);

}

My problem is that I would like to work with some models... and I know how to work with one model which is Tbl_Perimetro... I would like to work with another model called Tbl_Holding, But I'm using a modal to edit all this information.. here is the code of the modal:

$('#create_record').click(function(){
$('.modal-title').text('Add New Record');
$('#action_button').val('Add');
$('#action').val('Add');
$('#form_result').html('');

  $('#formModal').modal('show');
 });

$('#user_form').on('submit', function(event){
event.preventDefault();
var action_url = '';

if($('#action').val() == 'Add')
{
action_url = "{{ route('perimetro.store') }}";
}
if($('#action').val() == 'Editar')
{
action_url = "{{ route('perimetro.update') }}";
}
  $.ajax({
url: action_url,
method:"POST",
data:$(this).serialize(),
dataType:"json",
success:function(data)
{
var html = '';
if(data.errors)
{
 html = '
';
 for(var count = 0; count < data.errors.length; count++)
 {
  html += '
' + data.errors[count] + '
';
 }
 html += '
';
}
if(data.success)
{
 html = '
' + data.success + '
';
 $('#user_form')[0].reset();
 $('#user_perimetro').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});

 $(document).on('click', '.edit', function(){
var id = $(this).attr('id');
$('#form_result').html('');

$.ajax({

url :"/perimetro/"+id+"/edit",
dataType:"json",
success:function(data)
 {
$('#rif').val(data.result.rif);
$('#razon_social').val(data.result.razon_social);
$('#holdings_id').val(data.result.holdings_id);
$('#pines_id').val(data.result.pines_id);
$('#carteras_id').val(data.result.carteras_id);
$('#hidden_id').val(id);
$('.modal-title').text('Editar Registro');
$('#action_button').val('Editar');
$('#action').val('Editar');
$('#formModal').modal('show');
}
})
});

This is the button to edit the information

$button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Editar</button>';

I would like to know is it exist a way to work with two models in the same modal... In this way I only can work with one model at the same time...

Body:
I think I got what you mean...

What you can do is using a route with 2 variables passed, the first variable could be the id of the tbl_perimetro and the 2nd variable could be the id of the tbl_holding.

So, this would fit like this:

public function edit($id, $idholding)
{
    if(request()->ajax())
    {
        $data = Tbl_Perimetro::findOrFail($id);
        $data1 = Tbl_Holding::findOrFail($idholding);
        $alldata = array($data, $data1);  //----->THIS WILL BREAK YOUR JSON STRUCTURE BE CAREFUL
        return response()->json(['result' => $alldata]);

    }
}

And the same in the update function:

public function update(Request $request, Tbl_Perimetro $user, Tbl_Holding $holding)
{
    ...
}

Be careful editing your routes, because starting in laravel 6 (I think) the variables HAVE to be literal, so the new routes have to match the variable name of the function p.ex:

Route::get('editmodels/{id}/{idholding}','Controller@edit'); //<----This will work
Route::get('editmodels/{id}/{id2}','Controller@edit'); //<----This won't work

Hope it helps!!


问:
TypeError: Object(...) is not a function while using fingerprint plugin in ionic 3
I am working with Ionic 3 and i just added a Fingerprint plugin

Reference :Fingerprint AIO Plugin

And the code snippet is shown below

```<code>import { FingerprintAIO } from "@ionic-native/fingerprint-aio/ngx";

 constructor(private fingerPrintProvider : FingerprintAIO ){}

            this.fingerPrintProvider.isAvailable().then((result)=>{
                        console.log(result);
                        if(result == 'finger' || result == 'face'){
                            //Fingerprint or Face auth available
                            console.log('Fingerprint or face exist!');
                            self.fingerPrintProvider.show({
                                clientId: 'RetraxFingerPrint',
                                clientSecret: 'RetraxFingerPrint', //Only necessary for Android
                                disableBackup: true, //Only for Android(optional)
                                localizedFallbackTitle: 'Use Pin', //Only for iOS
                                localizedReason: 'Please Authenticate' //Only for iOS
                            })
                            .then((result)=>{
                                console.log(result);
                            })
                            .catch((error) => {
                                //Fingerprint/Face was not successfully verified
                                console.log(error);
                            });
                        }
                        else {
                            //Fingerprint or Face Auth is not available
                            console.log("Fingerprint/Face Auth is not available on this device!")
                        }
                    })
</code>```

RxJs version is shown   below

"rxjs": "5.5.2"

Other Dependencies shown below

```<code>"dependencies": {
    "@angular/animations": "5.0.3",
    "@angular/common": "5.0.3",
    "@angular/compiler": "5.0.3",
    "@angular/compiler-cli": "5.0.3",
    "@angular/core": "5.0.3",
    "@angular/forms": "5.0.3",
    "@angular/http": "5.0.3",
    "@angular/platform-browser": "5.0.3",
    "@angular/platform-browser-dynamic": "5.0.3",
    "@ionic-native/android-permissions": "^4.12.2",
    "@ionic-native/badge": "^4.18.0",
    "@ionic-native/camera": "^4.7.0",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/crop": "^4.7.0",
    "@ionic-native/deeplinks": "^4.6.0",
    "@ionic-native/document-viewer": "^4.11.0",
    "@ionic-native/file": "^4.7.0",
    }
</code>```

But when i do ionic serve i get this below error, Is it a dependency issue or any issue with the code ?

TypeError: Object(...) is not a function
      at FingerprintAIO.isAvailable

```<code>Any help appreciated.
</code>```

答:
You should run this command :

npm install @ionic-native/fingerprint-aio@5.22.0-beta-1

Body:
I am working with Ionic 3 and i just added a Fingerprint plugin

Reference :Fingerprint AIO Plugin

And the code snippet is shown below

import { FingerprintAIO } from "@ionic-native/fingerprint-aio/ngx";

 constructor(private fingerPrintProvider : FingerprintAIO ){}

            this.fingerPrintProvider.isAvailable().then((result)=>{
                        console.log(result);
                        if(result == 'finger' || result == 'face'){
                            //Fingerprint or Face auth available
                            console.log('Fingerprint or face exist!');
                            self.fingerPrintProvider.show({
                                clientId: 'RetraxFingerPrint',
                                clientSecret: 'RetraxFingerPrint', //Only necessary for Android
                                disableBackup: true, //Only for Android(optional)
                                localizedFallbackTitle: 'Use Pin', //Only for iOS
                                localizedReason: 'Please Authenticate' //Only for iOS
                            })
                            .then((result)=>{
                                console.log(result);
                            })
                            .catch((error) => {
                                //Fingerprint/Face was not successfully verified
                                console.log(error);
                            });
                        }
                        else {
                            //Fingerprint or Face Auth is not available
                            console.log("Fingerprint/Face Auth is not available on this device!")
                        }
                    })

RxJs version is shown   below

"rxjs": "5.5.2"

Other Dependencies shown below

"dependencies": {
    "@angular/animations": "5.0.3",
    "@angular/common": "5.0.3",
    "@angular/compiler": "5.0.3",
    "@angular/compiler-cli": "5.0.3",
    "@angular/core": "5.0.3",
    "@angular/forms": "5.0.3",
    "@angular/http": "5.0.3",
    "@angular/platform-browser": "5.0.3",
    "@angular/platform-browser-dynamic": "5.0.3",
    "@ionic-native/android-permissions": "^4.12.2",
    "@ionic-native/badge": "^4.18.0",
    "@ionic-native/camera": "^4.7.0",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/crop": "^4.7.0",
    "@ionic-native/deeplinks": "^4.6.0",
    "@ionic-native/document-viewer": "^4.11.0",
    "@ionic-native/file": "^4.7.0",
    }

But when i do ionic serve i get this below error, Is it a dependency issue or any issue with the code ?

TypeError: Object(...) is not a function
      at FingerprintAIO.isAvailable

Any help appreciated.


问:
WSL - GEDIT Unable to init server: Could not connect: Connection refused
I'm using Ubuntu 18.04 as Windows Subsystem for Linux on my Windows 10 machine.

I've installed gedit without any errors or warnings.

But whenever I try to use the command gedit something (here something is a filename)

I get this error:

```<code>Unable to init server: Could not connect: Connection refused

(gedit:48): Gtk-WARNING **: 21:03:26.729: cannot open display:
</code>```

答:
It's probably because you are running it with root user.
Run it as non-root user.

(If you don't know that if you are running it as root or not, enter the command below and if it returns 0, it means you are root and you must to login to non-root user:  id -u)

(If you had run sudo su or something like that, It means you are root and you must use exit to go back!)

Body:
I'm using Ubuntu 18.04 as Windows Subsystem for Linux on my Windows 10 machine.

I've installed gedit without any errors or warnings.

But whenever I try to use the command gedit something (here something is a filename)

I get this error:

Unable to init server: Could not connect: Connection refused

(gedit:48): Gtk-WARNING **: 21:03:26.729: cannot open display:


问:
Why angular date pipe do not support locale language default format like Intl.DateTimeFormat?
I am using angular date pipe for date formatting. I want to format date based on user/client locale. For example 'mm/dd/yyyy' for English US(en-US) and dd.mm.yyyy for German(de-de). Angular have format options like short, medium and long. They do not match the locale default format. If i go for customized date format, I do not have the locale separator. Intl DateTimeFormat provides the exact formatted date. Is there any way to achieve this with angular date pipe?</p>

答:
**EDIT**

I can't see that the recent Angular docs mention registerLocaleData, so I assume it can be ignored now, so you can skip the first part. I guess Angular figures out which locales you use automatically, or all locale data is bundled into Angular.

<s>
  The first thing to make sure is that you have loaded the locale data.
  You can do this in `app.module.ts` as stated in the documentation:
```<code>import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';

registerLocaleData(localeDe);
</code>```
</s>

Then, you have two alternatives.

You can set the LOCALE_ID variable to your preferred locale (de-DE in your case). This can be done either by using the --i18nLocale flag in ng build or ng serve, or it can be done by providing a value during bootstrap (see documentation). If you use this, the date will be formatted according to that locale's rules anywhere you use it.

You can set the locale as the third parameter in DatePipe. If you use this approach, it will only affect that specific usage of the date pipe. The parameters are separated by :, and if you want the default behavior for some prior parameter you can set it to undefined. The following example shows the date and time using the de-DE date format without using any timezone offset: myDate | date : 'medium' : undefined : 'de-DE'. Check out this stackblitz for more examples

Body:
**EDIT**

I can't see that the recent Angular docs mention registerLocaleData, so I assume it can be ignored now, so you can skip the first part. I guess Angular figures out which locales you use automatically, or all locale data is bundled into Angular.

<s>
  The first thing to make sure is that you have loaded the locale data.
  You can do this in `app.module.ts` as stated in the documentation:

import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';

registerLocaleData(localeDe);

</s>

Then, you have two alternatives.

You can set the LOCALE_ID variable to your preferred locale (de-DE in your case). This can be done either by using the --i18nLocale flag in ng build or ng serve, or it can be done by providing a value during bootstrap (see documentation). If you use this, the date will be formatted according to that locale's rules anywhere you use it.

You can set the locale as the third parameter in DatePipe. If you use this approach, it will only affect that specific usage of the date pipe. The parameters are separated by :, and if you want the default behavior for some prior parameter you can set it to undefined. The following example shows the date and time using the de-DE date format without using any timezone offset: myDate | date : 'medium' : undefined : 'de-DE'. Check out this stackblitz for more examples


问:
From C#, How to validate whether Table is already exists in MS Access DB
From C#, I am opening MS Access DB & importing values to Access Table. We need to validate whether Table is already exists in MS Access DB ??</p>

```<code> access.OpenCurrentDatabase(sMedExpressAccessDB, true, null);

 // Drop the existing table data

 access.DoCmd.DeleteObject(Access.AcObjectType.acTable, "drug");
 // Run the saved import
 access.DoCmd.RunSavedImportExport("MedExpressODBC");

 // Close the database
 access.CloseCurrentDatabase();
</code>```

答:
Chok, try using a try...catch construct around your delete command to ignore the error when you delete an object that's not there.

If you really need to find out if a table is there, as you're using .Net, I'd suggest using the GetOleDbSchemaTable method for OleDbConnections, see e.g. here:
TekTips post by Headwinds
with this vb code:

```<code>Dim schemaDT As DataTable
Dim thisNull As System.DBNull()
schemaDT = thisConn.GetOleDbSchemaTable( _
OleDbSchemaGuid.Tables, thisNull)
</code>```

As the referenced post mentions:

The DataTable that is returned from this statement is the collection of information about tables
  The advantage is that this approach will work (with slight modifications) for other ADO.Net databases as well.
  For more info, see the MSDN documentation.

Alternatives:
As people have said, you can use the msysobjects system table in Access, but that table is not guaranteed to have the same info in various Access versions.

Also, you could use the DAO Tabledefs collection, or its ADO equivalent.

Body:
From C#, I am opening MS Access DB & importing values to Access Table. We need to validate whether Table is already exists in MS Access DB ??

 access.OpenCurrentDatabase(sMedExpressAccessDB, true, null);

 // Drop the existing table data

 access.DoCmd.DeleteObject(Access.AcObjectType.acTable, "drug");
 // Run the saved import
 access.DoCmd.RunSavedImportExport("MedExpressODBC");

 // Close the database
 access.CloseCurrentDatabase();

Body:
Chok, try using a try...catch construct around your delete command to ignore the error when you delete an object that's not there.

If you really need to find out if a table is there, as you're using .Net, I'd suggest using the GetOleDbSchemaTable method for OleDbConnections, see e.g. here:
TekTips post by Headwinds
with this vb code:

Dim schemaDT As DataTable
Dim thisNull As System.DBNull()
schemaDT = thisConn.GetOleDbSchemaTable( _
OleDbSchemaGuid.Tables, thisNull)

As the referenced post mentions:

The DataTable that is returned from this statement is the collection of information about tables
  The advantage is that this approach will work (with slight modifications) for other ADO.Net databases as well.
  For more info, see the MSDN documentation.

Alternatives:
As people have said, you can use the msysobjects system table in Access, but that table is not guaranteed to have the same info in various Access versions.

Also, you could use the DAO Tabledefs collection, or its ADO equivalent.


问:
Gradle task for Sentry not compiling
I have to add the Analytics tool Sentry to our Android project. In order to make it work, one needs to create mappings for the obfuscated code (from Proguard/R8) and upload it later to Sentry.

On the website https://docs.sentry.io/platforms/android/ it is even described how to do that.
There it is written that one needs to create a gradle task looking like this:

```<code>gradle.projectsEvaluated {
    android.applicationVariants.each { variant ->
        def variantName = variant.name.capitalize();
        def proguardTask = project.tasks.findByName(
            "transformClassesAndResourcesWithProguardFor${variantName}")
        def dexTask = project.tasks.findByName(
            "transformClassesWithDexFor${variantName}")
        def task = project.tasks.create(
                name: "processSentryProguardFor${variantName}",
                type: Exec) {
            workingDir project.rootDir
            commandLine *[
                "sentry-cli",
                "upload-proguard",
                "--write-properties",
                "${project.rootDir.toPath()}/app/build/intermediates/assets" +
                    "/${variant.dirName}/sentry-debug-meta.properties",
                variant.getMappingFile(),
                "--no-upload"
            ]
        }
        dexTask.dependsOn task
        task.dependsOn proguardTask
    }
}
</code>```

This shall wait until Proguard is finished, than copy this properties file to the assets. However, when I add this to my Android gradle script I get the error:

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

No signature of method: java.util.ArrayList.multiply() is applicable for argument types: (ArrayList) values: [[sentry-cli, upload-proguard,
    --write-properties, {Application-Path}/app/build/intermediates/assets/playStoreStaging/debug/sentry-debug-meta.properties,
    ...]]   Possible solutions: multiply(java.lang.Number),
    multiply(java.lang.Number)

I assume there is something wrong with the multiplication symbol * before the commandLine array. But when I remove it I get the error

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

Cannot cast object 'sentry-cli' with class 'java.lang.String' to class 'int'

So I tried to test this with only that line

```<code>commandLine "sentry-cli", ...
</code>```

Which gave me another error

What went wrong: Cannot invoke method dependsOn() on null object

Thus I assume something went really wrong with that gradle script since it seems the dependend task can't be found. Does anyone have any idea how to fix this (or optionally have any other idea how to copy that sentry-debug-meta.properties file to my assets in another way, once Proguard/R8 is finished)?

Thanks!

-------- EDIT --------

I noticed something important.
The gradle tasks are defined in a different name than what was defined in the manual. Looking at my tasks I have them named

```<code>transformClassesAndResourcesWithR8For...
</code>```

and

```<code>transformClassesWithDexBuilderFor...
</code>```

However, I print the variantName then for checking but it seems my tasks are incomplete.

In my tasks list there exist

```<code>transformClassesAndResourcesWithR8ForPlayStoreStagingDebug
</code>```

but not

```<code>transformClassesAndResourcesWithR8ForPlayStoreStagingRelease
</code>```

and thus the task can't be found. I think that is the real problem here. So where are these gradle tasks defined?

------- EDIT 2 --------

Okay I noticed something strange here. Some variants don't have tasks. It makes sense that DEBUG tasks don't have R8 tasks but I found this here:

Variant: PlayStoreStagingRelease DexTask is null

Variant: PlayStorePreviewRelease DexTask is null

Variant: HockeyAppRelease DexTask is null

Variant: LocalServerRelease DexTask is null

Variant: PlayStoreProductionRelease DexTask is null

So how can this be?

答:
I'd recommend using the Sentry Gradle integration (Gradle plugin) which is described here https://docs.sentry.io/platforms/android/#gradle-integration

The official Android Gradle plugin changed its task names over versions, Gradle version also affects those code snippets.

Google also replaced Proguard with R8 and it also affected those code snippets.

Is there a reason why not using the Sentry Gradle integration? if so, We'll be looking into updating them.

Thanks.

Title: Gradle task for Sentry not compiling

Body:
I have to add the Analytics tool Sentry to our Android project. In order to make it work, one needs to create mappings for the obfuscated code (from Proguard/R8) and upload it later to Sentry.

On the website https://docs.sentry.io/platforms/android/ it is even described how to do that.
There it is written that one needs to create a gradle task looking like this:

gradle.projectsEvaluated {
    android.applicationVariants.each { variant ->
        def variantName = variant.name.capitalize();
        def proguardTask = project.tasks.findByName(
            "transformClassesAndResourcesWithProguardFor${variantName}")
        def dexTask = project.tasks.findByName(
            "transformClassesWithDexFor${variantName}")
        def task = project.tasks.create(
                name: "processSentryProguardFor${variantName}",
                type: Exec) {
            workingDir project.rootDir
            commandLine *[
                "sentry-cli",
                "upload-proguard",
                "--write-properties",
                "${project.rootDir.toPath()}/app/build/intermediates/assets" +
                    "/${variant.dirName}/sentry-debug-meta.properties",
                variant.getMappingFile(),
                "--no-upload"
            ]
        }
        dexTask.dependsOn task
        task.dependsOn proguardTask
    }
}

This shall wait until Proguard is finished, than copy this properties file to the assets. However, when I add this to my Android gradle script I get the error:

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

No signature of method: java.util.ArrayList.multiply() is applicable for argument types: (ArrayList) values: [[sentry-cli, upload-proguard,
    --write-properties, {Application-Path}/app/build/intermediates/assets/playStoreStaging/debug/sentry-debug-meta.properties,
    ...]]   Possible solutions: multiply(java.lang.Number),
    multiply(java.lang.Number)

I assume there is something wrong with the multiplication symbol * before the commandLine array. But when I remove it I get the error

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

Cannot cast object 'sentry-cli' with class 'java.lang.String' to class 'int'

So I tried to test this with only that line

commandLine "sentry-cli", ...

Which gave me another error

What went wrong: Cannot invoke method dependsOn() on null object

Thus I assume something went really wrong with that gradle script since it seems the dependend task can't be found. Does anyone have any idea how to fix this (or optionally have any other idea how to copy that sentry-debug-meta.properties file to my assets in another way, once Proguard/R8 is finished)?

Thanks!

-------- EDIT --------

I noticed something important.
The gradle tasks are defined in a different name than what was defined in the manual. Looking at my tasks I have them named

transformClassesAndResourcesWithR8For...

and

transformClassesWithDexBuilderFor...

However, I print the variantName then for checking but it seems my tasks are incomplete.

In my tasks list there exist

transformClassesAndResourcesWithR8ForPlayStoreStagingDebug

but not

transformClassesAndResourcesWithR8ForPlayStoreStagingRelease

and thus the task can't be found. I think that is the real problem here. So where are these gradle tasks defined?

------- EDIT 2 --------

Okay I noticed something strange here. Some variants don't have tasks. It makes sense that DEBUG tasks don't have R8 tasks but I found this here:

Variant: PlayStoreStagingRelease DexTask is null

Variant: PlayStorePreviewRelease DexTask is null

Variant: HockeyAppRelease DexTask is null

Variant: LocalServerRelease DexTask is null

Variant: PlayStoreProductionRelease DexTask is null

So how can this be?


问:
now-cli deployment doesn't build package.json dependencies
I'm trying to deploy a Sapper built application via
@now-node. The task is basically to deploy a Polka server with dependencies and to serve static/ and client/ files statically. I have managed to include the files that Lambda requires via includeFiles but now I see in the logs that the builder ignores dependencies described in package.json. The exact message is

```<code>Starting server on port 3000
Cannot find module 'sirv'
Did you forget to add it to "dependencies" in `package.json`?
</code>```

But I see in the build log that dependencies are not collected. Both package.json and package-lock.json are present in the source files.

I'd appreciate any advice on how to approach this.

The now.json config I arrived at looks like this:

```<code>{
    "version": 2,
    "name": "experimental-sapper",
    "builds": [
        {
            "src": "__sapper__/build/index.js",
            "use": "@now/node",
            "config": {
                "includeFiles": [
                    "../build/**",
                    "../../static/**"
                    ]
            }
        },
        {
            "src": "static/**",
            "use": "@now/static"
        },
        {
            "src": "__sapper__/build/client/**",
            "use": "@now/static"
        }
    ],
    "routes": [
        { "src": "/(.*(\\.css)|(\\.json)|(\\.png))", "dest": "/static/$1" },
        { "src": "/client/(.*)", "dest": "/__sapper__/build/client/$1" },
        { "src": "/(.*)", "dest": "/__sapper__/build/index.js" }
    ],
    "alias": "..."
}
</code>```

And the src/server.js looks like this (before Rollup bundling):

```<code>import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = polka() // You can also use Express
    .use(compression({ threshold: 0 }));
if (dev) {
    app.use(sirv('static', { dev }));
}
app.use(sapper.middleware())
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });
export default app.handler;
</code>```

Then package.json is pretty standard as well:

```<code>  "description": "TODO",
  "version": "0.0.1",
  "scripts": {
    "dev": "sapper dev",
    "build": "sapper build --legacy",
    "export": "sapper export --legacy",
    "start": "node __sapper__/build",
    "cy:run": "cypress run",
    "cy:open": "cypress open",
    "test": "run-p --race dev cy:run"
  },
  "dependencies": {
    "compression": "^1.7.1",
    "express": "^4.17.1",
    "polka": "^0.5.0",
    "postcss-define-property": "^0.5.0",
    "sirv": "^0.4.0"
  },
  "devDependencies": {
    ...
  },
  "browserslist": "last 2 versions"
}
</code>```

Thanks in advance!

答:
For anybody coming across this question, the solution is to use the now-sapper builder at https://www.npmjs.com/package/now-sapper

There are instructions on the site, but essentially you need to export your handler as mentioned above, then let the builder do the rest. There are a few intricacies to now which mean that the node builder alone won't work.

Your now configuration should look like:

```<code>{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "now-sapper"
    }
  ]
}
</code>```

There is a demo project linked from the README which is a basic Sapper template with the required now configuration.

Note for exported applications, @now/static will suffice.

Body:
I'm trying to deploy a Sapper built application via
@now-node. The task is basically to deploy a Polka server with dependencies and to serve static/ and client/ files statically. I have managed to include the files that Lambda requires via includeFiles but now I see in the logs that the builder ignores dependencies described in package.json. The exact message is

Starting server on port 3000
Cannot find module 'sirv'
Did you forget to add it to "dependencies" in `package.json`?

But I see in the build log that dependencies are not collected. Both package.json and package-lock.json are present in the source files.

I'd appreciate any advice on how to approach this.

The now.json config I arrived at looks like this:

{
    "version": 2,
    "name": "experimental-sapper",
    "builds": [
        {
            "src": "__sapper__/build/index.js",
            "use": "@now/node",
            "config": {
                "includeFiles": [
                    "../build/**",
                    "../../static/**"
                    ]
            }
        },
        {
            "src": "static/**",
            "use": "@now/static"
        },
        {
            "src": "__sapper__/build/client/**",
            "use": "@now/static"
        }
    ],
    "routes": [
        { "src": "/(.*(\\.css)|(\\.json)|(\\.png))", "dest": "/static/$1" },
        { "src": "/client/(.*)", "dest": "/__sapper__/build/client/$1" },
        { "src": "/(.*)", "dest": "/__sapper__/build/index.js" }
    ],
    "alias": "..."
}

And the src/server.js looks like this (before Rollup bundling):

import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = polka() // You can also use Express
    .use(compression({ threshold: 0 }));
if (dev) {
    app.use(sirv('static', { dev }));
}
app.use(sapper.middleware())
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });
export default app.handler;

Then package.json is pretty standard as well:

  "description": "TODO",
  "version": "0.0.1",
  "scripts": {
    "dev": "sapper dev",
    "build": "sapper build --legacy",
    "export": "sapper export --legacy",
    "start": "node __sapper__/build",
    "cy:run": "cypress run",
    "cy:open": "cypress open",
    "test": "run-p --race dev cy:run"
  },
  "dependencies": {
    "compression": "^1.7.1",
    "express": "^4.17.1",
    "polka": "^0.5.0",
    "postcss-define-property": "^0.5.0",
    "sirv": "^0.4.0"
  },
  "devDependencies": {
    ...
  },
  "browserslist": "last 2 versions"
}

Thanks in advance!

Body:
For anybody coming across this question, the solution is to use the now-sapper builder at https://www.npmjs.com/package/now-sapper

There are instructions on the site, but essentially you need to export your handler as mentioned above, then let the builder do the rest. There are a few intricacies to now which mean that the node builder alone won't work.

Your now configuration should look like:

{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "now-sapper"
    }
  ]
}

There is a demo project linked from the README which is a basic Sapper template with the required now configuration.

Note for exported applications, @now/static will suffice.


问:
Word Cloud making error in Python: string indices must be integers
I'm trying to make a Word Cloud out of a txt file with this code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()
</code>```

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.

答:
replace

```<code>raw_file.append(line['text'])
</code>```

with

```<code>raw_file.append(line)
</code>```

when you do line['text'] you're trying to take the element 'text' from the object line, but line is a string, and 'text' is not a valid index for a string type.

actually what you want would normally be

```<code>with open('T.txt') as f:
    raw_file = f.readlines()
</code>```

because it does what you seem to be trying to do and then closes the file handler at the end rather than leaving it open (as you are currently doing).

You're then going to have some trouble because you're trying to treat a list of lines as a string, which it isn't. I suggest you try writing this line by line and working out what you actually want to do. Stackoverflow will eventually write this whole code for you, but that's not really helping you learn anything.

Body:
I'm trying to make a Word Cloud out of a txt file with this code:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from IPython.display import Image as im

file = open("T.txt", encoding='utf-8')
FR = file.read()

raw_file = []

for line in FR:
    raw_file.append(line['text'])

words = raw_file.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

word_list = (words)
word_counter = {}
for word in word_list:
     if word in word_counter:
         word_counter[word] += 1
     else:
         word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

topp = popular_words

topp.remove('https')

mask = np.array(Image.open('/Users/x/Downloads/B.png'))

wc = WordCloud(background_color="black", max_words=2000, mask=mask)
clean_string = ','.join(topp)
wc.generate(clean_string)

plt.imshow(wc, interpolation='bilinear')
plt.title("Title", size=40)
plt.axis("off")
plt.show()

As in the title, it gives me Error: string indices must be integers on raw_file.append(line['text']).
I tried a few different methods to make it work but it didn't, so I'm asking here for help.

Thanks in advance.

Body:
replace

raw_file.append(line['text'])

with

raw_file.append(line)

when you do line['text'] you're trying to take the element 'text' from the object line, but line is a string, and 'text' is not a valid index for a string type.

actually what you want would normally be

with open('T.txt') as f:
    raw_file = f.readlines()

because it does what you seem to be trying to do and then closes the file handler at the end rather than leaving it open (as you are currently doing).

You're then going to have some trouble because you're trying to treat a list of lines as a string, which it isn't. I suggest you try writing this line by line and working out what you actually want to do. Stackoverflow will eventually write this whole code for you, but that's not really helping you learn anything.


问:
jenkins terminates automatically due to a process "/var/tmp/bbb/bbb"
I am using non-containerized jenkins on server. It gets terminated automatically each time I try to restart it.

Process which is killing jenkins is "/var/tmp/bbb/bbb". This process gets triggered by jenkins and even If I try to kill this process and restart jenkins service, jenkins again trigger this process which eventually happen to be a reason for termination of jenkins.

/var/tmp/bbb/bbb

I've also searched on google but couldn't find anything useful. Please help.

servers htop report here

答:
Check your root crontab.

I found the same process, made investigation. My instance was using for mining with scripts in crontab.

These scripts stop processes, stop all security services and syslog, create new users, find ssh-keys, change iptables, etc.


问:
Months go into a crystal reports Cross-Tab column
```<code>if {workorder.targcompdate} in DateTime (2019, 02, 01, 00, 00, 00) to DateTime (2019, 02, 28, 23, 59, 00) then "FEB" else
if {workorder.targcompdate} in DateTime (2019, 03, 01, 00, 00, 00) to DateTime (2019, 03, 31, 23, 59, 00) then "MAR" else
if {workorder.targcompdate} in DateTime (2019, 04, 01, 00, 00, 00) to DateTime (2019, 04, 30, 23, 59, 00) then "APR" else
if {workorder.targcompdate} in DateTime (2019, 05, 01, 00, 00, 00) to DateTime (2019, 05, 31, 23, 59, 00) then "MAY" else
if {workorder.targcompdate} in DateTime (2019, 06, 01, 00, 00, 00) to DateTime (2019, 06, 30, 23, 59, 00) then "JUN" else
if {workorder.targcompdate} in DateTime (2019, 07, 01, 00, 00, 00) to DateTime (2019, 07, 31, 23, 59, 00) then "JUL" else
if {workorder.targcompdate} in DateTime (2019, 08, 01, 00, 00, 00) to DateTime (2019, 08, 31, 23, 59, 00) then "AUG" else
if {workorder.targcompdate} in DateTime (2019, 09, 01, 00, 00, 00) to DateTime (2019, 09, 30, 23, 59, 00) then "SEP" else
if {workorder.targcompdate} in DateTime (2019, 10, 01, 00, 00, 00) to DateTime (2019, 10, 31, 23, 59, 00) then "OCT" else
if {workorder.targcompdate} in DateTime (2019, 11, 01, 00, 00, 00) to DateTime (2019, 11, 30, 23, 59, 00) then "NOV" else
if {workorder.targcompdate} in DateTime (2019, 12, 01, 00, 00, 00) to DateTime (2019, 12, 31, 23, 59, 00) then "DEC" else
if {workorder.targcompdate} in DateTime (2020, 01, 01, 00, 00, 00) to DateTime (2020, 01, 31, 23, 59, 00) then "JAN'20" else
if {workorder.targcompdate} in DateTime (2020, 02, 01, 00, 00, 00) to DateTime (2020, 02, 29, 23, 59, 00) then "FEB'20"
</code>```

Body: Ucase(ToText({workorder.targcompdate}, "MMM yy"))


问:
How can I make my browser to go on a site every X seconds?
So, I simply need a script for Tampermonkey to go to a specific site every x seconds on the same tab no matter what website or addon is open in the browser.

```<code>// ==UserScript==
// @name        arga
// @description arga
// @include     *
// ==/UserScript==

function view() {
setTimeout(function() {

window.location.replace("https://www.google.com/");

}, 250000);
};
</code>```

I expect that this script goes to google.com every 250 seconds, no matter what extension page or website is opend but it doesn't.

答:
Per Brock Adam's comment:

```<code>// ==UserScript==
// @name        arga
// @description arga

// ==/UserScript==

setTimeout(function() {

window.location.replace(“https://www.google.com/“);

}, 250000);
</code>```

Your script defines a function, but doesn't call it.

To call the function you defined, you would do this:

```<code>(function view () {
  // your code here
})();
</code>```

Which is effectively the same as:

```<code>function view () {
  // your code here
}

view();
</code>```

Body:
So, I simply need a script for Tampermonkey to go to a specific site every x seconds on the same tab no matter what website or addon is open in the browser.

// ==UserScript==
// @name        arga
// @description arga
// @include     *
// ==/UserScript==

function view() {
setTimeout(function() {

window.location.replace("https://www.google.com/");

}, 250000);
};

I expect that this script goes to google.com every 250 seconds, no matter what extension page or website is opend but it doesn't.

Body:
Per Brock Adam's comment:

// ==UserScript==
// @name        arga
// @description arga

// ==/UserScript==

setTimeout(function() {

window.location.replace(“https://www.google.com/“);

}, 250000);

Your script defines a function, but doesn't call it.

To call the function you defined, you would do this:

(function view () {
  // your code here
})();

Which is effectively the same as:

function view () {
  // your code here
}

view();