问:
contextBridge.exposeInMainWorld and IPC with Typescript in Electron app: Cannot read property 'send' of undefined
I defined contextBridge ( https://www.electronjs.org/docs/all#contextbridge )
in preload.js as follows:

```<code>const {
  contextBridge,
  ipcRenderer
} = require("electron")

contextBridge.exposeInMainWorld(
  "api", {
      send: (channel, data) => {
          ipcRenderer.invoke(channel, data).catch(e => console.log(e))
      },
      receive: (channel, func) => {
        console.log("preload-receive called. args: ");
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      },
      // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args
      electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => {
        ipcRenderer.sendTo(window_id, channel, arg);
      },
      // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload
/preload.ts
      electronIpcSend: (channel: string, ...arg: any) => {
        ipcRenderer.send(channel, arg);
      },
      electronIpcSendSync: (channel: string, ...arg: any) => {
        return ipcRenderer.sendSync(channel, arg);
      },
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.on(channel, listener);
      },
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.once(channel, listener);
      },
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>
void) => {
        ipcRenderer.removeListener(channel, listener);
      },
      electronIpcRemoveAllListeners: (channel: string) => {
        ipcRenderer.removeAllListeners(channel);
      }
  }
)
</code>```

I defined a global.ts :

```<code>export {}
declare global {
  interface Window {
    "api": {
      send: (channel: string, ...arg: any) => void;
      receive: (channel: string, func: (event: any, ...arg: any) => void) => void;
      // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload
/preload.ts
      // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args
      electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => void;
      electronIpcSend: (channel: string, ...arg: any) => void;
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => void;
      electronIpcSendSync: (channel: string, ...arg: any) => void;
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) =>
void;
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>
 void) => void;
      electronIpcRemoveAllListeners: (channel: string) => void;
    }
  }
}
</code>```

and in the renderer process App.tsx I call window.api.send :

```<code>window.api.send('open-type-A-window', '');
</code>```

The typescript compilation looks fine:

```<code>yarn run dev
yarn run v1.22.5
$ yarn run tsc && rimraf dist && cross-env NODE_ENV=development webpack --watch --progress
--color
$ tsc
95% emitting emit(node:18180) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning:
Compilation.assets will be frozen in future, all modifications are deprecated.

BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the
Compilation.
    Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
    Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
(Use `node --trace-deprecation ...` to show where the warning was created)
asset main.bundle.js 32.6 KiB [emitted] (name: main) 1 related asset
asset package.json 632 bytes [emitted] [from: package.json] [copied]
cacheable modules 26.2 KiB
  modules by path ./node_modules/electron-squirrel-startup/ 18.7 KiB
    modules by path ./node_modules/electron-squirrel-startup/node_modules/debug/src/*.js 15
KiB 4 modules
    ./node_modules/electron-squirrel-startup/index.js 1 KiB [built] [code generated]
    ./node_modules/electron-squirrel-startup/node_modules/ms/index.js 2.7 KiB [built] [code
generated]
  ./src/main/main.ts 6.82 KiB [built] [code generated]
  ./node_modules/file-url/index.js 684 bytes [built] [code generated]
external "path" 42 bytes [built] [code generated]
external "url" 42 bytes [built] [code generated]
external "electron" 42 bytes [built] [code generated]
external "child_process" 42 bytes [built] [code generated]
external "tty" 42 bytes [built] [code generated]
external "util" 42 bytes [built] [code generated]
external "fs" 42 bytes [built] [code generated]
external "net" 42 bytes [built] [code generated]
webpack 5.21.2 compiled successfully in 4313 ms

asset renderer.bundle.js 1000 KiB [emitted] (name: main) 1 related asset
asset index.html 196 bytes [emitted]
runtime modules 937 bytes 4 modules
modules by path ./node_modules/ 990 KiB
  modules by path ./node_modules/scheduler/ 31.8 KiB 4 modules
  modules by path ./node_modules/react/ 70.6 KiB 2 modules
  modules by path ./node_modules/react-dom/ 875 KiB 2 modules
  modules by path ./node_modules/css-loader/dist/runtime/*.js 3.78 KiB 2 modules
  ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built]
[code generated]
  ./node_modules/object-assign/index.js 2.06 KiB [built] [code generated]
modules by path ./src/ 5 KiB
  modules by path ./src/app/styles/*.less 3.16 KiB
    ./src/app/styles/index.less 385 bytes [built] [code generated]
    ./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/app
/styles/index.less 2.78 KiB [built] [code generated]
  ./src/renderer/renderer.tsx 373 bytes [built] [code generated]
  ./src/app/components/App.tsx 1.48 KiB [built] [code generated]
webpack 5.21.2 compiled successfully in 4039 ms
</code>```

But I get Cannot read property 'send' of undefined

If I set in App.tsx :

```<code>const sendProxy = window.api.send;
</code>```

I get the same error and the window is not rendered :

What am I doing wrongly with Typescript and with Electron IPC?
Looking forward to your kind help

答:
Below is my setup based on https://www.electronforge.io, which also adds typings for the exposed api. Hope it helps, even if not a focused answer.

In package.json (using @electron-forge package.json setup, webpack + typescript template), under entryPoints, make sure you have:

```<code>"preload": {
    "js": "./src/preload.ts"
}
</code>```

In src/index.ts where you create your BrowserWindow, use the magic webpack constant to reference the bundled preload script (maybe your preload script didn't get bundled?):

```<code>const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY
    }
  });
</code>```

Contents of src/preload.ts:

```<code>import { contextBridge } from "electron";
import api from './api'

contextBridge.exposeInMainWorld("api", api);

</code>```

src/api/index.ts just exports all features of the api. Example:

```<code>import * as myFeature from "./my-feature";

// api exports functions that make up the frontend api, ie that in
// turn either do IPC calls to main for db communication or use
// allowed nodejs features like file i/o.
// Example `my-feature.ts`:
// export const fetchX = async (): Promise<X> => { ... }

export default {
    ...myFeature
}
</code>```

Typescript 2.9+ can recognise your api functions like api.fetchX by adding a global declaration, e.g. src/index.d.ts (reference):

```<code>declare const api: typeof import("./api").default;
</code>```

...which you need to reference from tsconfig.json:

```<code>{
  ...
  "files": [
    "src/index.d.ts"
  ]
}
</code>```

All that done and you should be good to call api.fetchX with typing support (ymmv by IDE) from renderer-side without importing anything. Example App.tsx:

```<code>import * as React from 'react'
// do not import api here, it should be globally available

export const App = () => {
  useEffect(() => {
    (async () => {
      const x = await api.fetchX();
      ...
    })();
  }, []);

  return <h1>My App</h1>
}
</code>```

Body:
I defined contextBridge ( https://www.electronjs.org/docs/all#contextbridge )
in preload.js as follows:

const {
  contextBridge,
  ipcRenderer
} = require("electron")

contextBridge.exposeInMainWorld(
  "api", {
      send: (channel, data) => {
          ipcRenderer.invoke(channel, data).catch(e => console.log(e))
      },
      receive: (channel, func) => {
        console.log("preload-receive called. args: ");
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      },
      // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args
      electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => {
        ipcRenderer.sendTo(window_id, channel, arg);
      },
      // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload
/preload.ts
      electronIpcSend: (channel: string, ...arg: any) => {
        ipcRenderer.send(channel, arg);
      },
      electronIpcSendSync: (channel: string, ...arg: any) => {
        return ipcRenderer.sendSync(channel, arg);
      },
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.on(channel, listener);
      },
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.once(channel, listener);
      },
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>
void) => {
        ipcRenderer.removeListener(channel, listener);
      },
      electronIpcRemoveAllListeners: (channel: string) => {
        ipcRenderer.removeAllListeners(channel);
      }
  }
)

I defined a global.ts :

export {}
declare global {
  interface Window {
    "api": {
      send: (channel: string, ...arg: any) => void;
      receive: (channel: string, func: (event: any, ...arg: any) => void) => void;
      // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload
/preload.ts
      // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args
      electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => void;
      electronIpcSend: (channel: string, ...arg: any) => void;
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => void;
      electronIpcSendSync: (channel: string, ...arg: any) => void;
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) =>
void;
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>
 void) => void;
      electronIpcRemoveAllListeners: (channel: string) => void;
    }
  }
}

and in the renderer process App.tsx I call window.api.send :

window.api.send('open-type-A-window', '');

The typescript compilation looks fine:

yarn run dev
yarn run v1.22.5
$ yarn run tsc && rimraf dist && cross-env NODE_ENV=development webpack --watch --progress
--color
$ tsc
95% emitting emit(node:18180) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning:
Compilation.assets will be frozen in future, all modifications are deprecated.

BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the
Compilation.
    Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
    Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
(Use `node --trace-deprecation ...` to show where the warning was created)
asset main.bundle.js 32.6 KiB [emitted] (name: main) 1 related asset
asset package.json 632 bytes [emitted] [from: package.json] [copied]
cacheable modules 26.2 KiB
  modules by path ./node_modules/electron-squirrel-startup/ 18.7 KiB
    modules by path ./node_modules/electron-squirrel-startup/node_modules/debug/src/*.js 15
KiB 4 modules
    ./node_modules/electron-squirrel-startup/index.js 1 KiB [built] [code generated]
    ./node_modules/electron-squirrel-startup/node_modules/ms/index.js 2.7 KiB [built] [code
generated]
  ./src/main/main.ts 6.82 KiB [built] [code generated]
  ./node_modules/file-url/index.js 684 bytes [built] [code generated]
external "path" 42 bytes [built] [code generated]
external "url" 42 bytes [built] [code generated]
external "electron" 42 bytes [built] [code generated]
external "child_process" 42 bytes [built] [code generated]
external "tty" 42 bytes [built] [code generated]
external "util" 42 bytes [built] [code generated]
external "fs" 42 bytes [built] [code generated]
external "net" 42 bytes [built] [code generated]
webpack 5.21.2 compiled successfully in 4313 ms

asset renderer.bundle.js 1000 KiB [emitted] (name: main) 1 related asset
asset index.html 196 bytes [emitted]
runtime modules 937 bytes 4 modules
modules by path ./node_modules/ 990 KiB
  modules by path ./node_modules/scheduler/ 31.8 KiB 4 modules
  modules by path ./node_modules/react/ 70.6 KiB 2 modules
  modules by path ./node_modules/react-dom/ 875 KiB 2 modules
  modules by path ./node_modules/css-loader/dist/runtime/*.js 3.78 KiB 2 modules
  ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built]
[code generated]
  ./node_modules/object-assign/index.js 2.06 KiB [built] [code generated]
modules by path ./src/ 5 KiB
  modules by path ./src/app/styles/*.less 3.16 KiB
    ./src/app/styles/index.less 385 bytes [built] [code generated]
    ./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/app
/styles/index.less 2.78 KiB [built] [code generated]
  ./src/renderer/renderer.tsx 373 bytes [built] [code generated]
  ./src/app/components/App.tsx 1.48 KiB [built] [code generated]
webpack 5.21.2 compiled successfully in 4039 ms

But I get Cannot read property 'send' of undefined

If I set in App.tsx :

const sendProxy = window.api.send;

I get the same error and the window is not rendered :

What am I doing wrongly with Typescript and with Electron IPC?
Looking forward to your kind help

Body:
Below is my setup based on https://www.electronforge.io, which also adds typings for the exposed api. Hope it helps, even if not a focused answer.

In package.json (using @electron-forge package.json setup, webpack + typescript template), under entryPoints, make sure you have:

"preload": {
    "js": "./src/preload.ts"
}

In src/index.ts where you create your BrowserWindow, use the magic webpack constant to reference the bundled preload script (maybe your preload script didn't get bundled?):

const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY
    }
  });

Contents of src/preload.ts:

import { contextBridge } from "electron";
import api from './api'

contextBridge.exposeInMainWorld("api", api);

src/api/index.ts just exports all features of the api. Example:

import * as myFeature from "./my-feature";

// api exports functions that make up the frontend api, ie that in
// turn either do IPC calls to main for db communication or use
// allowed nodejs features like file i/o.
// Example `my-feature.ts`:
// export const fetchX = async (): Promise<X> => { ... }

export default {
    ...myFeature
}

Typescript 2.9+ can recognise your api functions like api.fetchX by adding a global declaration, e.g. src/index.d.ts (reference):

declare const api: typeof import("./api").default;

...which you need to reference from tsconfig.json:

{
  ...
  "files": [
    "src/index.d.ts"
  ]
}

All that done and you should be good to call api.fetchX with typing support (ymmv by IDE) from renderer-side without importing anything. Example App.tsx:

import * as React from 'react'
// do not import api here, it should be globally available

export const App = () => {
  useEffect(() => {
    (async () => {
      const x = await api.fetchX();
      ...
    })();
  }, []);

  return <h1>My App</h1>
}


来源: stackexchange

问:
How to use yapf (or black) in VSCode
I installed yapf using:

```<code>conda install yapf
</code>```

and add next lines in my .vscode/settings.json file:

```<code>{
    //"python.linting.pylintEnabled": true,
    //"python.linting.pycodestyleEnabled": false,
    //"python.linting.flake8Enabled": true,
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        " — style",
        "{based_on_style: pep8, indent_width: 4}"
    ],
    "python.linting.enabled": true,
}
</code>```

But I can't understand how to use it - it doesn't show any error in a bad-formatted script:

```<code>import pandas as pd

class MyClass(object):
    def __init__(self, some_value: int):
        self.value = some_value
    def one_more_function(self, another_value):
        print(another_value)
myObject = MyClass(45)
myObject.one_more_function(2)
my__object2 = MyClass(324)

    print('ok')
def some_foo():
    """
    """
    pass
</code>```

答:
Answer from 2022

If you prefer a 'GUI', you can also enter these values under settings (File->Preferences->Settings) directly:

ContentLicense: CC BY-SA 4.0

Title: How to use yapf (or black) in VSCode

Body:
I installed yapf using:

conda install yapf

and add next lines in my .vscode/settings.json file:

{
    //"python.linting.pylintEnabled": true,
    //"python.linting.pycodestyleEnabled": false,
    //"python.linting.flake8Enabled": true,
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        " — style",
        "{based_on_style: pep8, indent_width: 4}"
    ],
    "python.linting.enabled": true,
}

But I can't understand how to use it - it doesn't show any error in a bad-formatted script:

import pandas as pd

class MyClass(object):
    def __init__(self, some_value: int):
        self.value = some_value
    def one_more_function(self, another_value):
        print(another_value)
myObject = MyClass(45)
myObject.one_more_function(2)
my__object2 = MyClass(324)

    print('ok')
def some_foo():
    """
    """
    pass


问:
Rather use the Jenkins Agent images from quay.io or from registry.redhat.io?
For updating my Jenkins Agents running in OpenShift, I consider using the Jenkins Agent image available at quay.io/openshift/origin-jenkins-agent-base:4.7. However, there is another one available at registry.redhat.io/openshift4/ose-jenkins-agent-base:v4.7.

Are there any substantial differences between these images?

If my research is correct (docker inspect ...), the one on registry.redhat.io is based on a Git commit from November 2021 (https://github.com/openshift/jenkins/commit/1524f28a04cf6882177968c95b11a8018596e05c), while the one on quay.io is based on a Git commit from February 2 2022 (https://github.com/openshift/jenkins/commit/1383028376d7619e1930d0f2a88aa00cce770226). And of course, the one at quay.io is available without any authentication.

答:
It probably makes sense to use the quay images, if you want to stick to publicly available images.

```<code>Starting with v4.0, the images are only available on quay.io for public community support. Their pull specs are:
</code>```

Please note, that this strongly depends if you're using OpenShift v3 (which is EOL) or OpenShift v4
https://github.com/openshift/jenkins#installation-openshift-v4

Body:
It probably makes sense to use the quay images, if you want to stick to publicly available images.

Starting with v4.0, the images are only available on quay.io for public community support. Their pull specs are:

Please note, that this strongly depends if you're using OpenShift v3 (which is EOL) or OpenShift v4
https://github.com/openshift/jenkins#installation-openshift-v4


问:
Cannot scan data using fscanf into array in c
I am writing a program that can mark the students' result. However I have problem to scan to input file data into array before I analyze them.
This is my input data structure:

BECDCBAADEBACBAEDDBE

2019000  BEAABEBCCDDEECXBEBXC

2019001  ABXBBDAXAEAAEAABECED

2019002  ABBCXCBBCBAXCCBEAEAD
```
<p>The first line is the correct answer. Below included the student number and their answer. Currently I just want to save the data inside array. This is what I tried:</p>
```#include <stdio.h>
#include <string.h>

// Function Prototype
void ReadFile(char* correct_ans, int* number, char student_ans[100][20]);

int main(void)
{
    char correct_ans[20], student_ans[100][20];
    int student_number[100];

    FILE *fp1;
    fp1 = fopen("answer.txt", "r");
    int temp;
    char temp_answer[20];

    fscanf(fp1, "%s\n", correct_ans);

    for(int i = 0; i < 100; i++)
    {
        fscanf(fp1, "%d %s\n", &student_number[i], temp_answer);

        strcpy(*(student_ans + i), temp_answer);
    }

    printf("%s\n", correct_ans);
    for(int i = 0; i < 100; i++)
    {
        printf("%d %s\n", student_number[i], student_ans[i]);
    }

    return 0;
}
```
<p>When I run the code:</p>
<pre class="lang-none prettyprint-override"><code>2019000 BEAABEBCCDDEECXBEBXCABXBBDAXAEAAEAABECEDABBCXCBBCBAXCCBEAEADACDEDCEDXECDABBCDACCCADCCEAAXDEEBACDBBXXAXCBEACCDACCCDBCADBDEAXXXBCDEXEBDAACXCDEXXEBEXBAABXBDBEDXDACAAACAXADXAAAABDDADCXEXDECXCBEEDCDXACDEBCACCECCACAADDXBCCXECDEXCEBBCEABADCAAEXXXECXDCBEEBACEBBEAEEDBBAABBDBDCBXEBABBDXAEDXCDBDEDDCXECDACBCDCECADBEDEXABXADXCDCDAACBEBECEAXADCDAEDAECECAAEBXEXBBACABCCEAXADDEEDECCXAEXBXEXBEAAEXABDXXXEAEBXEAACEXXDDABDADACAXXCDXXACAADXEDXDXBDACECBEEAECAEXABDBAABEBXBBCEXBCEACBCAXXBXBXEXACCCCAACXXXXCXEDECEBDCDDCEDEXDCXAECXEBXBDDBCXEDXDAXCCABXEBAEXEEXBCABXAXABECAECBXDXBDXCCDXDABEBXXBBDEAXECCCAEDDCXXABXCABXXCAEAXAEEECDEACXDXECDCDCBXAADCECBXDXDBDABAXABACEXXCEDBDEBDCDXBDBAEEEEEBCBCACXCBXBEXDDCDBXCADABXCACACBEBCEXBBCACDEDEXXCDXEBBCCXBDXEXBAEDCCCCXCEXABABDXEDADECEEEXABDBABBAABBBCBBADBEXDXECEXCXDADAXEEBABADECBECXXAAACCAAAXBAACBBXXBBXEXADCBBADXBDACCBDAXBDEBCAXABABBDACCACDABADADBXCADBADADCXCEACBBADAEEXEEEEEXBBBCEEABBXCDDDDEDEXAAEBCDEEXEAEXEECXCEBCBADDXDXEBEDCECDXBAEAAEBBADEEDEDDEXXBCDDAABADADDBAXBXECDDBEXBBDEDCBADEEXEECBDCXCDXACCBBXBDXBEBBCEEXEEXDDADECABEAXEDCEDDDBDXBAXECBECDBEXBCBADDXXBXBEXDCCDBDAECBBCCAEDEEBAXDXXCEAAEDXEBCDXXDXDAADADBEDCXXCBCABABAABAECDECACDDEBCCAACAEBXEXXCEBABXEDCEXBBBCAEXABAEXXBADBACEEBDAAEXDDECCXDCBXBEEAEAXEADACBECEEADAEXXXEXBXAECXEAECCCXADCDCBCDDBCAEBAABDBXXEDAAXCCXXDABCXBXDDCBCECCCEXCXXABEABECEDBXADECCBBCEECEDEBBBBEAAXXCXEXEXCDCCECCAEABXXBDCEAAEADDXXACDXCXBXXCADBAXABXXCDBEBXEBDBEBECBDXCXDDEEDCDAAXABCCEBDABDBXCXEBXAEBXDCXBBCBDDEBDCBBDDCDEEXACDBDXXDBAEEBEBCCCXEAACEBECEEEDEBXAEXECBCBECEDCBEAEXEDDADBCEADEXCECABCCDXAXAXECCEAXEBAEEAAXBEXEXEDCBXBXDBXEBCXEXBACCXXXBXXEADDXXAABECXBEEXXBCXDEXEXDCDACEADEXXCDCBXEDBCBAEADAEBDCCDAXAABXCADCADCBCEEAXBDCXDCACCCDCDXXCBXCDCECXEBAXBXACBBBDBBXCECBAXCXBECAAEDDCCDBCEXEBDAXEXDDCAXXCXEBXXEBCADXBBBBBXDEECXBBBDEEEDACDCEEAADDEEAEDAXACAXDXCEXBACCEEEXBCAEADXBEDEBXDXEEXEBCCABDCCBBDXDACXBXCXDABXDDEADDCDDBBCAAAADAXCDBXXXXACABCADXCEXBXDXEXXEXXCCDDCCEXDXBBBCCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD
</code>```

This is just the front part of result, seems the answer of all students are accumulated and keep decreasing until the last one:

2019095
CCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019096 DECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019097 ECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019098 CXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019099 ACCBDEBECABEBCDECBDD
```

I am quite new to stackoverflow and not so sure how to edit my question. Sorry to it, but my problems are

The first correct answer cannot print out (means it didnt save to array?)

The answer of students keep accumulating

What I want is that the correct answer should be stored in correct_ans, and the student number is scanned according to the answer.
Thx for ur help

答:
The length of the string

CCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

is larger than sizeof(temp_answer).

From the

```<code>    fscanf(fp1, "%d %s\n",
           &student_number[i],
           temp_answer);
</code>```

on, the result is undefined.

If you replace the hardcoded constant 20 with a bigger amount, it should work.

Also, there is no need to a temp_answer here, you can read directly in student_ans[i].

Body:
I am writing a program that can mark the students' result. However I have problem to scan to input file data into array before I analyze them.
This is my input data structure:

BECDCBAADEBACBAEDDBE

2019000  BEAABEBCCDDEECXBEBXC

2019001  ABXBBDAXAEAAEAABECED

2019002  ABBCXCBBCBAXCCBEAEAD

The first line is the correct answer. Below included the student number and their answer. Currently I just want to save the data inside array. This is what I tried:

#include <stdio.h>
#include <string.h>

// Function Prototype
void ReadFile(char* correct_ans, int* number, char student_ans[100][20]);

int main(void)
{
    char correct_ans[20], student_ans[100][20];
    int student_number[100];

    FILE *fp1;
    fp1 = fopen("answer.txt", "r");
    int temp;
    char temp_answer[20];

    fscanf(fp1, "%s\n", correct_ans);

    for(int i = 0; i < 100; i++)
    {
        fscanf(fp1, "%d %s\n", &student_number[i], temp_answer);

        strcpy(*(student_ans + i), temp_answer);
    }

    printf("%s\n", correct_ans);
    for(int i = 0; i < 100; i++)
    {
        printf("%d %s\n", student_number[i], student_ans[i]);
    }

    return 0;
}

When I run the code:

2019000 BEAABEBCCDDEECXBEBXCABXBBDAXAEAAEAABECEDABBCXCBBCBAXCCBEAEADACDEDCEDXECDABBCDACCCADCCEAAXDEEBACDBBXXAXCBEACCDACCCDBCADBDEAXXXBCDEXEBDAACXCDEXXEBEXBAABXBDBEDXDACAAACAXADXAAAABDDADCXEXDECXCBEEDCDXACDEBCACCECCACAADDXBCCXECDEXCEBBCEABADCAAEXXXECXDCBEEBACEBBEAEEDBBAABBDBDCBXEBABBDXAEDXCDBDEDDCXECDACBCDCECADBEDEXABXADXCDCDAACBEBECEAXADCDAEDAECECAAEBXEXBBACABCCEAXADDEEDECCXAEXBXEXBEAAEXABDXXXEAEBXEAACEXXDDABDADACAXXCDXXACAADXEDXDXBDACECBEEAECAEXABDBAABEBXBBCEXBCEACBCAXXBXBXEXACCCCAACXXXXCXEDECEBDCDDCEDEXDCXAECXEBXBDDBCXEDXDAXCCABXEBAEXEEXBCABXAXABECAECBXDXBDXCCDXDABEBXXBBDEAXECCCAEDDCXXABXCABXXCAEAXAEEECDEACXDXECDCDCBXAADCECBXDXDBDABAXABACEXXCEDBDEBDCDXBDBAEEEEEBCBCACXCBXBEXDDCDBXCADABXCACACBEBCEXBBCACDEDEXXCDXEBBCCXBDXEXBAEDCCCCXCEXABABDXEDADECEEEXABDBABBAABBBCBBADBEXDXECEXCXDADAXEEBABADECBECXXAAACCAAAXBAACBBXXBBXEXADCBBADXBDACCBDAXBDEBCAXABABBDACCACDABADADBXCADBADADCXCEACBBADAEEXEEEEEXBBBCEEABBXCDDDDEDEXAAEBCDEEXEAEXEECXCEBCBADDXDXEBEDCECDXBAEAAEBBADEEDEDDEXXBCDDAABADADDBAXBXECDDBEXBBDEDCBADEEXEECBDCXCDXACCBBXBDXBEBBCEEXEEXDDADECABEAXEDCEDDDBDXBAXECBECDBEXBCBADDXXBXBEXDCCDBDAECBBCCAEDEEBAXDXXCEAAEDXEBCDXXDXDAADADBEDCXXCBCABABAABAECDECACDDEBCCAACAEBXEXXCEBABXEDCEXBBBCAEXABAEXXBADBACEEBDAAEXDDECCXDCBXBEEAEAXEADACBECEEADAEXXXEXBXAECXEAECCCXADCDCBCDDBCAEBAABDBXXEDAAXCCXXDABCXBXDDCBCECCCEXCXXABEABECEDBXADECCBBCEECEDEBBBBEAAXXCXEXEXCDCCECCAEABXXBDCEAAEADDXXACDXCXBXXCADBAXABXXCDBEBXEBDBEBECBDXCXDDEEDCDAAXABCCEBDABDBXCXEBXAEBXDCXBBCBDDEBDCBBDDCDEEXACDBDXXDBAEEBEBCCCXEAACEBECEEEDEBXAEXECBCBECEDCBEAEXEDDADBCEADEXCECABCCDXAXAXECCEAXEBAEEAAXBEXEXEDCBXBXDBXEBCXEXBACCXXXBXXEADDXXAABECXBEEXXBCXDEXEXDCDACEADEXXCDCBXEDBCBAEADAEBDCCDAXAABXCADCADCBCEEAXBDCXDCACCCDCDXXCBXCDCECXEBAXBXACBBBDBBXCECBAXCXBECAAEDDCCDBCEXEBDAXEXDDCAXXCXEBXXEBCADXBBBBBXDEECXBBBDEEEDACDCEEAADDEEAEDAXACAXDXCEXBACCEEEXBCAEADXBEDEBXDXEEXEBCCABDCCBBDXDACXBXCXDABXDDEADDCDDBBCAAAADAXCDBXXXXACABCADXCEXBXDXEXXEXXCCDDCCEXDXBBBCCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

This is just the front part of result, seems the answer of all students are accumulated and keep decreasing until the last one:

2019095
CCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019096 DECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019097 ECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019098 CXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

2019099 ACCBDEBECABEBCDECBDD

I am quite new to stackoverflow and not so sure how to edit my question. Sorry to it, but my problems are

The first correct answer cannot print out (means it didnt save to array?)

The answer of students keep accumulating

What I want is that the correct answer should be stored in correct_ans, and the student number is scanned according to the answer.
Thx for ur help

Body:
The length of the string

CCBEBADEADCBECXDECEBDECXXDDXDXBCADEEECCXECBBCDAACBCACDCCXXDDCXDAECAEEAXDCEBXBAEXACCBDEBECABEBCDECBDD

is larger than sizeof(temp_answer).

From the

    fscanf(fp1, "%d %s\n",
           &student_number[i],
           temp_answer);

on, the result is undefined.

If you replace the hardcoded constant 20 with a bigger amount, it should work.

Also, there is no need to a temp_answer here, you can read directly in student_ans[i].


问:
Javascript Code for Coderbyte issue
Hi guys working on a problem in javascript from coder bytes. The problem is:

Using the JavaScript language, have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.

Use the Parameter Testing feature in the box below to test your code with different arguments.

```<code>function abcheck(str){
        for(var i = 0; i < str.length; i++) {
            if(str.split(" ")[i] === "a" && str.split(" ")[i+4] === "b")
                {
                    return true;
                }
            else{
                    return false;
            }
    }
}
</code>```

After doing a check

```<code>abcheck("Laura sobs")
</code>```

I am getting false. Can anyone spot what I am doing wrong?

答:
```<code>function ABCheck(str) {
  if (str.length < 5) {
    return false;
 }
  console.log(str.length);
  for (let i = 0; i < str.length - 4; i++) {
    // look for a
    if (str[i] === 'a') {
      if (str[i + 4] === 'b') {
        return true;
      }
    }

    if (str[i] === 'b') {
      if (str[i + 4] === 'a') {
        return true;
      }
    }
  }

  return false;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript Code for Coderbyte issue

Body:
Hi guys working on a problem in javascript from coder bytes. The problem is:

Using the JavaScript language, have the function ABCheck(str) take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.

Use the Parameter Testing feature in the box below to test your code with different arguments.

function abcheck(str){
        for(var i = 0; i < str.length; i++) {
            if(str.split(" ")[i] === "a" && str.split(" ")[i+4] === "b")
                {
                    return true;
                }
            else{
                    return false;
            }
    }
}

After doing a check

abcheck("Laura sobs")

I am getting false. Can anyone spot what I am doing wrong?


问:
C# OData The server committed a protocol violation. Section=ResponseStatusLine
I'm accessing Dynamics 365 Business Central OData API in C# application, and when accessing data in my local system is good and when we deployed the application to client server, randomly (50%) they are getting the error "The server committed a protocol violation. Section=ResponseStatusLine".

I have checked the article https://techcommunity.microsoft.com/t5/iis-support-blog/protocol-violation-section-responsestatusline/ba-p/1227792 and applied all the 3 suggestions, but none of them worked.

I'm able to access the client Business Central API integration application in my local system without any issues.

Assuming that this is client Firewall or load balancer issue. But not able to find the solution.

答:
There are many case behind this issue, avoiding the problem rather than actually fixing it. One of the most common cause of this error is the corrupt or missing headers in the request.

Solution:

The server responds with a 100 continue in an incorrect way. Setting expect 100 continue to false and reducing the socket idle time to two seconds

```<code>HttpRequestObj.ServicePoint.Expect100Continue = false;
HttpRequestObj.ServicePoint.MaxServicePointIdleTime = 2000;
</code>```

Ignore corrupted/missing headers. Ref: Link

Stop skype if it is running on the machine.

If a webserver uses UTF-8 that outputs the byte-order-marker (BOM). For example, the default constant Encoding.UTF8 outputs the BOM, and it is easy to forget this. The webpages will work correctly in Firefox and Chrome but HttpWebRequest will bomb. A quick fix is to change the webserver to use the UTF-8 encoding that doesn't output the BOM.

Check the end point of your request server. ex:https or http.

Body:
There are many case behind this issue, avoiding the problem rather than actually fixing it. One of the most common cause of this error is the corrupt or missing headers in the request.

Solution:

The server responds with a 100 continue in an incorrect way. Setting expect 100 continue to false and reducing the socket idle time to two seconds

HttpRequestObj.ServicePoint.Expect100Continue = false;
HttpRequestObj.ServicePoint.MaxServicePointIdleTime = 2000;

Ignore corrupted/missing headers. Ref: Link

Stop skype if it is running on the machine.

If a webserver uses UTF-8 that outputs the byte-order-marker (BOM). For example, the default constant Encoding.UTF8 outputs the BOM, and it is easy to forget this. The webpages will work correctly in Firefox and Chrome but HttpWebRequest will bomb. A quick fix is to change the webserver to use the UTF-8 encoding that doesn't output the BOM.

Check the end point of your request server. ex:https or http.


问:
how to get country code like(+91 ,+1 etc) using user's current location flutter
I'm working on flutter app and I have a text widget where I want to show user's current country code based on his location without any dropdown.
I'm getting value like "IN","US" using Locale, but I don't want it,
I need numeric country code like +91 (for India), +1 (for US) etc.
anyone help me please.</p>

答:
You can use country_codes package:

Install:

```<code>dependencies:
  country_codes: ^2.0.1
</code>```

Usage:

```<code>await CountryCodes.init(); // Optionally, you may provide a `Locale` to get countrie's localizadName

final CountryDetails details = CountryCodes.detailsForLocale();
print(details.alpha2Code); // Displays alpha2Code, for example US.
print(details.dialCode); // Displays the dial code, for example +1.
print(details.name); // Displays the extended name, for example United States.
print(details.localizedName);
</code>```

Body:
You can use country_codes package:

Install:

dependencies:
  country_codes: ^2.0.1

Usage:

await CountryCodes.init(); // Optionally, you may provide a `Locale` to get countrie's localizadName

final CountryDetails details = CountryCodes.detailsForLocale();
print(details.alpha2Code); // Displays alpha2Code, for example US.
print(details.dialCode); // Displays the dial code, for example +1.
print(details.name); // Displays the extended name, for example United States.
print(details.localizedName);


问:
Overriding SASS variables in Vue component from parent
In a Vue component, you can define scoped SASS variables. Is it somehow possible to override them from the parent, such that you could customize the look of the component based on where you use it? I have tried using deep selectors and !default values, but with no success. Making the styles non-scoped is not an option.

Example, trying to change the child's color to black from parent:

```
<p>Child:</p>
<pre class="lang-scss prettyprint-override"><code><style lang="scss" scoped>
$color: #fff;

.text {
  color: $color;
}
</style>
</code>```

答:
The current workaround I've found is to pass the value through regular CSS variables.

Parent:

```
<p>Child:</p>
<pre class="lang-scss prettyprint-override"><code><style lang="scss" scoped>
$color: var(--color, #fff);

.text {
  color: $color;
}
</style>
</code>```

Body:
In a Vue component, you can define scoped SASS variables. Is it somehow possible to override them from the parent, such that you could customize the look of the component based on where you use it? I have tried using deep selectors and !default values, but with no success. Making the styles non-scoped is not an option.

Example, trying to change the child's color to black from parent:

Child:

Body:
The current workaround I've found is to pass the value through regular CSS variables.

Parent:

<style lang="scss" scoped>
.child-component {
  --color: #000;
}
</style>

Child:

<style lang="scss" scoped>
$color: var(--color, #fff);

.text {
  color: $color;
}
</style>


问:
Clarification On And Resolution Of 'Java EE Module Dependencies'
I'm attempting to set up a web project's dependency on a utility project.  My utility project is set up with the 'Utility Module' project facet and 'Java 5'.  When I select 'Java EE Module Dependencies' in the properties of my web project, my utility project does not appear.  I believe this is the problem and would love to resolve it!

I did also try the following:
Since the Utility project does, however, show up in the 'Java EE Module Dependencies' in the properties of my EAR, I selected the dependency in my EAR and found that the Utility was now available to my web project, it appears as. e.g., Utility.jar.  Ultimately, this seems to be the desired effect.  However, the issue appears to be with the server's dependency resolution.  The Jar is distributed to the EAR and added to the Web's Manifest as, i.e., Utility.jar.  But the Utility project's dependencies are not being included along with that (or something to that affect).  Note: My company uses Ivy for dependency resolution.  The problem here is that the specific Jar that I'm receiving NoClassDefFoundError s on is included in the Web's dependency as well (i.e., the Jar exists in the WEB-INF/lib directory).  So I'm not sure why, if this is a viable solution, the Jar isn't able to resolve the dependency from the Web's classloader.

Also worth mentioning, the Utility project has been added to the 'Project' tab of the web project's 'Build Path'; therefore, I'm not receiving any compilation errors.

I will continue to dig in and try to find a solution but I would appreciate any help or guidance along the way.

Here are some of the resources I've found related to my exhaustive research:

Setting up dependencies: http://download.oracle.com/docs/cd/E13226_01/workshop/docs92/ws_platform/ideuserguide/conOptimizingProjects.html#SetupDependenciesSelective

Adding Utility Facet: Java EE Module Dependencies page in Eclipse missing projects

Project Dependency Issue: Eclipse Web Project Dependencies

Solution Posted Below

To anyone who was looking into this issue for me, I appreciate your time.  Hopefully this will help someone with a similar issue down the road.

Sincerely,
Beez

答:
Before, I was unable to check the Utility project in the web project's properties > 'Java EE Module Dependencies' > 'Web Libraries'.  I'm not sure why.  The module appeared but when I checked it, clicked 'apply' and 'okay', when I reopened the properties the module was unchecked.  So I added the dependency manually into the org.eclipse.wst.common.component file:

```<code><dependent-module archiveName="Utility.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/Utility/Utility">
    <dependency-type>uses</dependency-type>
</dependent-module>
</code>```

This resolved the issue completely and my app is fully functioning!

Body:
Before, I was unable to check the Utility project in the web project's properties > 'Java EE Module Dependencies' > 'Web Libraries'.  I'm not sure why.  The module appeared but when I checked it, clicked 'apply' and 'okay', when I reopened the properties the module was unchecked.  So I added the dependency manually into the org.eclipse.wst.common.component file:

<dependent-module archiveName="Utility.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/Utility/Utility">
    <dependency-type>uses</dependency-type>
</dependent-module>

This resolved the issue completely and my app is fully functioning!


问:
How can I easily edit a Jupyter notebook's JSON code in VS Code?
I have a Jupyter notebook and I would like to directly edit its JSON code in VS Code. However, when I open the notebook, VS Code goes in "Jupyter" mode instead of showing me the actual JSON code.

My current workaround is to rename the file to .json, edit it, save it, then rename it back to .ipynb. That's not very convenient. Is there a better way?

答:
You can use VS Code Jupyter Notebook Previewer Extension in vs code.

Link : https://marketplace.visualstudio.com/items?itemName=jithurjacob.nbpreviewer


问:
How to write PHP code containing {} in blade
Can someone tell me what is wrong with my syntax? I am trying to write this set of php code in the a laravel blade file

```<code>  @php  $identifiedIndex = $relevantTicketFlows->search(function($query) use ($data->ticket_flow_id){return $query->id == $data->ticket_flow_id;});
                                                            echo '<p> $relevantTicketFlows[$identifiedIndex] </p> '
                                                        @endphp
</code>```

答:
Firstly, you should really avoid this kind of behavior, Laravel uses MVC pattern, and having logic in a view is the devil.

Then, I think you just have a syntax error:

```<code>use ($data->ticket_flow_id){return $query->id
</code>```

You can't have this in a use (I'm pretty sure), try:

```<code>use ($data) {
   // access $data->ticket_flow_id inside closure
</code>```

Body:
Can someone tell me what is wrong with my syntax? I am trying to write this set of php code in the a laravel blade file

  @php  $identifiedIndex = $relevantTicketFlows->search(function($query) use ($data->ticket_flow_id){return $query->id == $data->ticket_flow_id;});
                                                            echo '
 $relevantTicketFlows[$identifiedIndex]
 '
                                                        @endphp

Body:
Firstly, you should really avoid this kind of behavior, Laravel uses MVC pattern, and having logic in a view is the devil.

Then, I think you just have a syntax error:

use ($data->ticket_flow_id){return $query->id

You can't have this in a use (I'm pretty sure), try:

use ($data) {
   // access $data->ticket_flow_id inside closure


问:
JavaScript Date to Delphi TDateTime
I need to send via AJAX a date for a delphi server that accept the date in float format and set a TDateTime property.

Eg.

```<code>var
   date: TDateTime;
begin
   date := StrToFloat(Request.QueryFields.Values['date']);
end;
</code>```

Delphi TDateTime start from 30/12/1989, i have tested with:

```<code>var
   date: TDateTime;
begin
   date := StrToFloat('0');
   ShowMessage( DateTimeToStr(date) ); // show: 30/12/1899
end;
</code>```

JavaScript Date start from unix epoch, i have tested with:

```<code>console.log(new Date(0)); // Thu Jan 01 1970 01:00:00 GMT+0100
</code>```

a simple conversion seem subtract the difference, but doesn't works, eg.:

```<code>// javascipt
var delphiTime = (new Date("07-24-2019") - new Date("12-30-1899")) / 1000;
console.log(delphiTime ); // 3773084400

// delphi
ShowMessage( DateTimeToStr(3773084400) ); // show 00/00/00
</code>```

the strange fact, on delphi, Now is 43670.654378:

```<code>ShowMessage( FloatToStr(Now) ); // 43670.654378
</code>```

In delphi 0 is 1899 and 43670 is 2019...

How works the date format in Delphi and how convert a unix date to delphi date with math?

Side note: i can't modify the server, i need to solve the issue client side with javascript

UPDATE:

In Delphi the float value = 1 would be 31.12.1899, 2 = 01.01.1900 and so on. Each unit seem a day.

```<code>function jsDateToDelphiDate(date){
  const seconds = (new Date(date).getTime() - new Date("12-30-1899").getTime()) / 1000;
  const days = seconds / 60 / 60 / 24;
  return days;
}

console.log(jsDateToDelphiDate(new Date("07-24-2019 16:00:00"))); // 43670.625
</code>```

43670.625 on delphi is 23/07/2019 15:00.

Why i lose 1 hour?

答:
To convert the return value of new Date().valueOf() to Delphi TDateTime you can use this function:

```<code>function jsDateToDelphiDate(millis: int64): TDateTime;
begin
  var UnixSeconds: Integer := Round(millis / MSecsPerSec);
  Result := UnixToDateTime(UnixSeconds, False);
end;
</code>```

Title: JavaScript Date to Delphi TDateTime

Body:
I need to send via AJAX a date for a delphi server that accept the date in float format and set a TDateTime property.

Eg.

var
   date: TDateTime;
begin
   date := StrToFloat(Request.QueryFields.Values['date']);
end;

Delphi TDateTime start from 30/12/1989, i have tested with:

var
   date: TDateTime;
begin
   date := StrToFloat('0');
   ShowMessage( DateTimeToStr(date) ); // show: 30/12/1899
end;

JavaScript Date start from unix epoch, i have tested with:

console.log(new Date(0)); // Thu Jan 01 1970 01:00:00 GMT+0100

a simple conversion seem subtract the difference, but doesn't works, eg.:

// javascipt
var delphiTime = (new Date("07-24-2019") - new Date("12-30-1899")) / 1000;
console.log(delphiTime ); // 3773084400

// delphi
ShowMessage( DateTimeToStr(3773084400) ); // show 00/00/00

the strange fact, on delphi, Now is 43670.654378:

ShowMessage( FloatToStr(Now) ); // 43670.654378

In delphi 0 is 1899 and 43670 is 2019...

How works the date format in Delphi and how convert a unix date to delphi date with math?

Side note: i can't modify the server, i need to solve the issue client side with javascript

UPDATE:

In Delphi the float value = 1 would be 31.12.1899, 2 = 01.01.1900 and so on. Each unit seem a day.

function jsDateToDelphiDate(date){
  const seconds = (new Date(date).getTime() - new Date("12-30-1899").getTime()) / 1000;
  const days = seconds / 60 / 60 / 24;
  return days;
}

console.log(jsDateToDelphiDate(new Date("07-24-2019 16:00:00"))); // 43670.625

43670.625 on delphi is 23/07/2019 15:00.

Why i lose 1 hour?

Body:
To convert the return value of new Date().valueOf() to Delphi TDateTime you can use this function:

function jsDateToDelphiDate(millis: int64): TDateTime;
begin
  var UnixSeconds: Integer := Round(millis / MSecsPerSec);
  Result := UnixToDateTime(UnixSeconds, False);
end;


问:
Appium Python Client Does not Install an exact Apk but a wrapped APK package
When I run a python script with the following code structure.

```<code>from appium import webdriver

desired_capabilities = {
  "appium:deviceName": "Android Emulator",
  "platformName": "Android",
  "appium:appPackage": "za.co.app",
  "appium:appWaitPackage": "za.co.app",
  "appium:appWaitActivity": "za.co.app.SplashActivity",
  "appium:appActivity": "za.co.app.SplashActivity",
  "appium:app": "C:\\Development\\AppiumDev\\myapp.apk"
}

driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_capabilities)
</code>```

What happens is that Appium wraps the myapp.apk and installs a wrapped version on my device.

Is there a way to prevent appium from wrapping the apk to just installing the actual myapp.apk? Similar to TestProject, when running tests,TestProject works on the actual apk & does not wrap the APK to install a wrapped version of the APK.

Thanks!

答:
Disable App Signing

For the latest Appium version (1.22), UIAutomator2 used for Android if automationName capability was not specified.

By default, all apps are always signed with the default Appium debug signature if they don't have any.

To cancel all the signing checks and make the driver to use the application package as is set appium:noSign=true:

```<code>desired_capabilities = {
  "appium:noSign": True,
  ...
</code>```

One more option here:

Disable Appium App Install

Appium is able to work with already pre-installed apps.

Just remove appium:app capability, and install the app before tests yourself, e.g. with adb.

```<code>adb -s <DEVICE ID> install <PATH TO APK>
</code>```

References

https://github.com/appium/appium-uiautomator2-driver#app-signing

https://github.com/appium/appium-uiautomator2-driver#app

https://www.appsdeveloperblog.com/install-apk-on-device-adb/

Body:
When I run a python script with the following code structure.

from appium import webdriver

desired_capabilities = {
  "appium:deviceName": "Android Emulator",
  "platformName": "Android",
  "appium:appPackage": "za.co.app",
  "appium:appWaitPackage": "za.co.app",
  "appium:appWaitActivity": "za.co.app.SplashActivity",
  "appium:appActivity": "za.co.app.SplashActivity",
  "appium:app": "C:\\Development\\AppiumDev\\myapp.apk"
}

driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_capabilities)

What happens is that Appium wraps the myapp.apk and installs a wrapped version on my device.

Is there a way to prevent appium from wrapping the apk to just installing the actual myapp.apk? Similar to TestProject, when running tests,TestProject works on the actual apk & does not wrap the APK to install a wrapped version of the APK.

Thanks!

Body:
Disable App Signing

For the latest Appium version (1.22), UIAutomator2 used for Android if automationName capability was not specified.

By default, all apps are always signed with the default Appium debug signature if they don't have any.

To cancel all the signing checks and make the driver to use the application package as is set appium:noSign=true:

desired_capabilities = {
  "appium:noSign": True,
  ...

One more option here:

Disable Appium App Install

Appium is able to work with already pre-installed apps.

Just remove appium:app capability, and install the app before tests yourself, e.g. with adb.

adb -s <DEVICE ID> install <PATH TO APK>

References

https://github.com/appium/appium-uiautomator2-driver#app-signing

https://github.com/appium/appium-uiautomator2-driver#app

https://www.appsdeveloperblog.com/install-apk-on-device-adb/


问:
how to add slider in tool mode?
I'm trying to add a slider in tool mode like this:

code:

```<code>tool
extends Position2D

export(float) var CustomSlider = 0.1 setget changeSlider_x

func changeSlider_x(changed_val):
    CustomSlider=changed_val
</code>```

答:
First of all, I want to point out that this variable:

```<code>export(float) var CustomSlider = 0.1
</code>```

Is a variant. Even thought Godot shows it as a float on the inspector panel.

This is a float and Godot will also show it as float in the inspector panel:

```<code>export var CustomSlider := 0.1
</code>```

Or if you prefer the type to be explicit, you can write it like this:

```<code>export var CustomSlider:float = 0.1
</code>```

What you specify between parenthesis after export is to controls how it will be shown in the inspector panel.

I know the documentation is a little hard to find - because there are other things called "export" - but here it is: GDScript exports

Now, to get a (useful) slider, you have to either:

Specify a range of values:

```<code>export(float, 0, 10) var CustomSlider:
</code>```

Specify a range of values, with snapping to a step size:

```<code>export(float, 0, 10, 0.1) var CustomSlider:
</code>```

The snapping will be to a multiple of the step size. That is, the snapping is not offset by the minimum and maximum.

Specify an exponential slider, with a maximum greater than zero (the minimum will be zero):

```<code>export(float, EXP, 10) var CustomSlider:
</code>```

With this the slider is not linear. You will find that at the half point the value is the square root of the maximum, not the half. And a third of the way, you find the cubic root of the maximum, and so on. As a result, number are more tightly packed near the maximum (e.g. for a range from 0 to 100, the half point is 10, so the first half goes from 0 to 10 and the second half goes from 10 to 100).

Specify an exponential slider, with a minimum and a maximum:

```<code>export(float, EXP, 10, 100) var CustomSlider:
</code>```

This is similar to the behavior above, except it is offset so the minimum is not zero, but the one you specified.

Specify an exponential slider, with a minimum, a maximum, and snapping to a step size:

```<code>export(float, EXP, 10, 100, 2) var CustomSlider:
</code>```

This creates an exponential slider similar to the previous case. Except this one will snap the value, similar to the snapping described before.

Aside from using export, there is another way to have something show in the inspector panel: use _get_property_list (requires a tool script), which would give us more control (some options are only available this way). Furthermore, we could call property_list_changed_notify to tell Godot to check again what it should show in the inspector panel, and that would allow you to have it change dynamically.

By the way, you can write your variable name in lower caps and with _, and Godot will capitalize it and replace the _ with spaces when it shows it in the inspector panel.

Title: how to add slider in tool mode?

Body:
I'm trying to add a slider in tool mode like this:

code:

tool
extends Position2D

export(float) var CustomSlider = 0.1 setget changeSlider_x

func changeSlider_x(changed_val):
    CustomSlider=changed_val

Body:
First of all, I want to point out that this variable:

export(float) var CustomSlider = 0.1

Is a variant. Even thought Godot shows it as a float on the inspector panel.

This is a float and Godot will also show it as float in the inspector panel:

export var CustomSlider := 0.1

Or if you prefer the type to be explicit, you can write it like this:

export var CustomSlider:float = 0.1

What you specify between parenthesis after export is to controls how it will be shown in the inspector panel.

I know the documentation is a little hard to find - because there are other things called "export" - but here it is: GDScript exports

Now, to get a (useful) slider, you have to either:

Specify a range of values:

export(float, 0, 10) var CustomSlider:

Specify a range of values, with snapping to a step size:

export(float, 0, 10, 0.1) var CustomSlider:

The snapping will be to a multiple of the step size. That is, the snapping is not offset by the minimum and maximum.

Specify an exponential slider, with a maximum greater than zero (the minimum will be zero):

export(float, EXP, 10) var CustomSlider:

With this the slider is not linear. You will find that at the half point the value is the square root of the maximum, not the half. And a third of the way, you find the cubic root of the maximum, and so on. As a result, number are more tightly packed near the maximum (e.g. for a range from 0 to 100, the half point is 10, so the first half goes from 0 to 10 and the second half goes from 10 to 100).

Specify an exponential slider, with a minimum and a maximum:

export(float, EXP, 10, 100) var CustomSlider:

This is similar to the behavior above, except it is offset so the minimum is not zero, but the one you specified.

Specify an exponential slider, with a minimum, a maximum, and snapping to a step size:

export(float, EXP, 10, 100, 2) var CustomSlider:

This creates an exponential slider similar to the previous case. Except this one will snap the value, similar to the snapping described before.

Aside from using export, there is another way to have something show in the inspector panel: use _get_property_list (requires a tool script), which would give us more control (some options are only available this way). Furthermore, we could call property_list_changed_notify to tell Godot to check again what it should show in the inspector panel, and that would allow you to have it change dynamically.

By the way, you can write your variable name in lower caps and with _, and Godot will capitalize it and replace the _ with spaces when it shows it in the inspector panel.


问:
How to use one array in multiple classes?
I am definitely doing something wrong here. I created a program and a class. Here is the program code I have written so far:

```<code>public class CashRegisterViewModel: Cash
{
    static void Main(string[] args)
    {
       double amountdue = 100;
        double amountpaid = 1650;
        Cash register = new Cash();

        for( double i = amountpaid; i < 0; i--)
        {
            register.Cash ;
        }
    }
}
</code>```

And here is the code I have written for the Cash class, where I control the "Cash Register" part of the code:

```<code>static void Register()
    {
        double[] cashmoney = { 100, 50, 230, 10, 5, 2, 1 };
        Array.Sort(cashmoney);
        Array.Reverse(cashmoney);

    }

    int index = cashmoney.Length();
</code>```

So far so good? Not quite. Despite it being only a few lines of code, I have encountered several problems already:

I can't use the Array.Length() function in the cash class

I seemingly can't call the array in the program, since it "Doesn't exist"

And that's it, for now. I am pretty new to Csharp, so I think I missed some vital information while creating the class.

答:
You are calling cashmoney.Length() outside of the scope where you declared the array. Also Length is a property so you can't call it like a method. You are declaring the array in the Register method, so the variable is only available there.

Have a look here, to learn more about scopes.

You could create a property in the Cash class called Cashmoney, like this:

```<code>public double[] Cashmoney {get; set;}
</code>```

That way you can access that property from outside. Learn more about properties here

Body:
I am definitely doing something wrong here. I created a program and a class. Here is the program code I have written so far:

public class CashRegisterViewModel: Cash
{
    static void Main(string[] args)
    {
       double amountdue = 100;
        double amountpaid = 1650;
        Cash register = new Cash();

        for( double i = amountpaid; i < 0; i--)
        {
            register.Cash ;
        }
    }
}

And here is the code I have written for the Cash class, where I control the "Cash Register" part of the code:

static void Register()
    {
        double[] cashmoney = { 100, 50, 230, 10, 5, 2, 1 };
        Array.Sort(cashmoney);
        Array.Reverse(cashmoney);

    }

    int index = cashmoney.Length();

So far so good? Not quite. Despite it being only a few lines of code, I have encountered several problems already:

I can't use the Array.Length() function in the cash class

I seemingly can't call the array in the program, since it "Doesn't exist"

And that's it, for now. I am pretty new to Csharp, so I think I missed some vital information while creating the class.

Body:
You are calling cashmoney.Length() outside of the scope where you declared the array. Also Length is a property so you can't call it like a method. You are declaring the array in the Register method, so the variable is only available there.

Have a look here, to learn more about scopes.

You could create a property in the Cash class called Cashmoney, like this:

public double[] Cashmoney {get; set;}

That way you can access that property from outside. Learn more about properties here


问:
Terraform AWS Provider Error: Value for unconfigurable attribute. Can't configure a value for "acl": its value will be decided automatically
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)
```
<p>Following are the errors:</p>
<pre class="lang-sh prettyprint-override"><code>Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1
</code>```

My code is as follows:

```<code>resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}
</code>```

答:
Terraform AWS Provider is upgraded to version 4.0.0 which is published on 10 February 2022.

Major changes in the release include:

Version 4.0.0 of the AWS Provider introduces significant changes to the aws_s3_bucket resource.

Version 4.0.0 of the AWS Provider will be the last major version to support EC2-Classic resources as AWS plans to fully retire EC2-Classic Networking. See the AWS News Blog for additional details.

Version 4.0.0 and 4.x.x versions of the AWS Provider will be the last versions compatible with Terraform 0.12-0.15.

The reason for this change by Terraform is as follows: To help distribute the management of S3 bucket settings via independent resources, various arguments and attributes in the aws_s3_bucket resource have become read-only. Configurations dependent on these arguments should be updated to use the corresponding aws_s3_bucket_* resource. Once updated, new aws_s3_bucket_* resources should be imported into Terraform state.

So, I updated my code accordingly by following the guide here: Terraform AWS Provider Version 4 Upgrade Guide | S3 Bucket Refactor

The new working code looks like this:

```<code>resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}

resource "aws_s3_bucket_acl" "this" {
  bucket = aws_s3_bucket.this.id
  acl    = "private"
}

resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    apply_server_side_encryption_by_default {
      kms_master_key_id = data.aws_kms_key.s3.arn
      sse_algorithm     = "aws:kms"
    }
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    id     = "backups"
    status = "Enabled"

    filter {
      prefix = "backups/"
    }

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }
}
</code>```

If you don't want to upgrade your Terraform AWS Provider version to 4.0.0, you can use the existing or older version by specifying it explicitly in the code as below:

```<code>terraform {
  required_version = "~> 1.0.11"
  required_providers {
    aws  = "~> 3.73.0"
  }
}
</code>```

Body:
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.

It was working yesterday.

Following is the command I run: terraform init && terraform apply

Following is the list of initialized provider plugins:

- Finding latest version of hashicorp/archive...
- Finding latest version of hashicorp/aws...
- Finding latest version of hashicorp/null...
- Installing hashicorp/null v3.1.0...
- Installed hashicorp/null v3.1.0 (signed by HashiCorp)
- Installing hashicorp/archive v2.2.0...
- Installed hashicorp/archive v2.2.0 (signed by HashiCorp)
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)

Following are the errors:

Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "lifecycle_rule": its value will be decided
│ automatically based on the result of applying this configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 1, in resource "aws_s3_bucket" "this":
│    1: resource "aws_s3_bucket" "this" {
│
│ Can't configure a value for "server_side_encryption_configuration": its
│ value will be decided automatically based on the result of applying this
│ configuration.
╵
╷
│ Error: Value for unconfigurable attribute
│
│   with module.ssm-parameter-store-backup.aws_s3_bucket.this,
│   on .terraform/modules/ssm-parameter-store-backup/s3_backup.tf line 3, in resource "aws_s3_bucket" "this":
│    3:   acl    = "private"
│
│ Can't configure a value for "acl": its value will be decided automatically
│ based on the result of applying this configuration.
╵
ERRO[0012] 1 error occurred:
        * exit status 1

My code is as follows:

resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
  acl    = "private"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = data.aws_kms_key.s3.arn
        sse_algorithm     = "aws:kms"
      }
    }
  }

  lifecycle_rule {
    id      = "backups"
    enabled = true

    prefix = "backups/"

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}

Body:
Terraform AWS Provider is upgraded to version 4.0.0 which is published on 10 February 2022.

Major changes in the release include:

Version 4.0.0 of the AWS Provider introduces significant changes to the aws_s3_bucket resource.

Version 4.0.0 of the AWS Provider will be the last major version to support EC2-Classic resources as AWS plans to fully retire EC2-Classic Networking. See the AWS News Blog for additional details.

Version 4.0.0 and 4.x.x versions of the AWS Provider will be the last versions compatible with Terraform 0.12-0.15.

The reason for this change by Terraform is as follows: To help distribute the management of S3 bucket settings via independent resources, various arguments and attributes in the aws_s3_bucket resource have become read-only. Configurations dependent on these arguments should be updated to use the corresponding aws_s3_bucket_* resource. Once updated, new aws_s3_bucket_* resources should be imported into Terraform state.

So, I updated my code accordingly by following the guide here: Terraform AWS Provider Version 4 Upgrade Guide | S3 Bucket Refactor

The new working code looks like this:

resource "aws_s3_bucket" "this" {
  bucket = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"

  tags = {
    Name        = "${var.project}-${var.environment}-ssm-parameter-store-backups-bucket"
    Environment = var.environment
  }
}

resource "aws_s3_bucket_acl" "this" {
  bucket = aws_s3_bucket.this.id
  acl    = "private"
}

resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    apply_server_side_encryption_by_default {
      kms_master_key_id = data.aws_kms_key.s3.arn
      sse_algorithm     = "aws:kms"
    }
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    id     = "backups"
    status = "Enabled"

    filter {
      prefix = "backups/"
    }

    transition {
      days          = 90
      storage_class = "GLACIER_IR"
    }

    transition {
      days          = 180
      storage_class = "DEEP_ARCHIVE"
    }

    expiration {
      days = 365
    }
  }
}

If you don't want to upgrade your Terraform AWS Provider version to 4.0.0, you can use the existing or older version by specifying it explicitly in the code as below:

terraform {
  required_version = "~> 1.0.11"
  required_providers {
    aws  = "~> 3.73.0"
  }
}


问:
Issues Splitting values separated by delimiters and creating columns for each split in snowflake
I am new to snowflake and I am trying to run an sql query that splits values with delimiters(semi-column) and create columns for each of them.

Table name: lexa

ID
Value

001
2021-02-13 18:17:43;83.89.250.196;10.10.11.29

002
2021-02-13 17:47:56;5.33.18.24;10.10.11.28

what I am trying to achieve

ID
register
Ip1
IP2

001
2021-02-13 18:17:43
83.89.250.196
10.10.11.29

002
2021-02-13 17:47:56
5.33.18.24
10.10.11.28

答:
Snowflake split function can split a string into an array.</p>
```<code>SELECT ID,
       split(value, ';')[0] as register,
       split(value, ';')[1] as IP1,
       split(value, ';')[2] as IP2
  FROM data;
</code>```

Body:
Snowflake split function can split a string into an array.

SELECT ID,
       split(value, ';')[0] as register,
       split(value, ';')[1] as IP1,
       split(value, ';')[2] as IP2
  FROM data;


问:
How can I set properties on an EventHub message in a Java Function?
When using C# to write an Azure Function publishing an EventHub message as the output binding one can use the Azure.Messaging.EventHubs.EventData class as the output binding and set properties on the object before handing it over to the output binding:

```<code>var eventData = new EventData(serializedTelemetryData);
eventData.Properties["eventType"] = "com.microsoft.azure.monitoring.EtlEvent";
</code>```

But the Java output binding seems to only allow OutputBinding<T>, where "T is a POJO or any native Java type". Is there an equivalent of the EventData class in Java that could be used for the binding and allow to set properties?

答:
According to the documentation you can using getProperties

https://learn.microsoft.com/en-us/java/api/com.azure.messaging.eventhubs.eventdata.getproperties?view=azure-java-stable#com-azure-messaging-eventhubs-eventdata-getproperties()

Example of Usage:

```<code>EventData eventData = new EventData(message);
eventData.getProperties().put("constant1", yourEntityHere);
eventData.getProperties().put("constant2", "ADD");
</code>```

Body:
When using C# to write an Azure Function publishing an EventHub message as the output binding one can use the Azure.Messaging.EventHubs.EventData class as the output binding and set properties on the object before handing it over to the output binding:

var eventData = new EventData(serializedTelemetryData);
eventData.Properties["eventType"] = "com.microsoft.azure.monitoring.EtlEvent";

But the Java output binding seems to only allow OutputBinding<T>, where "T is a POJO or any native Java type". Is there an equivalent of the EventData class in Java that could be used for the binding and allow to set properties?

Body:
According to the documentation you can using getProperties

https://learn.microsoft.com/en-us/java/api/com.azure.messaging.eventhubs.eventdata.getproperties?view=azure-java-stable#com-azure-messaging-eventhubs-eventdata-getproperties()

Example of Usage:

EventData eventData = new EventData(message);
eventData.getProperties().put("constant1", yourEntityHere);
eventData.getProperties().put("constant2", "ADD");


问:
Require One of a Set of Fields in SQL
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

```<code>machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}
</code>```

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?

答:
Consider this query:

```<code>SELECT *
  FROM machine
 WHERE hostname IS NULL
       AND ip IS NULL
       AND service_tag IS NULL;
</code>```

If this resultset is not the empty set then the business rule has been violated. Therefore, create a constraint or trigger that tests this.

Title: Require One of a Set of Fields in SQL

Body:
I have an entity, let's call 'machine', which has a group of entities from which it takes its name. At least one of these fields is required, but more than one can be set. So in the example below, if the host name and IP is not set, then the service tag should be. I am using Propel 1.5 as an ORM.

machine:
  id: ~
  hostname:    {type: varchar(255)}
  ip:          {type: varchar(255)}
  service_tag: {type: varchar(255)}

An article on multi-column constraints makes me wonder if it would be possible to add something like required(hostname, mac, service_tag). If this is the case, how would I accomplish this in .yml form for Propel?

Body:
Consider this query:

SELECT *
  FROM machine
 WHERE hostname IS NULL
       AND ip IS NULL
       AND service_tag IS NULL;

If this resultset is not the empty set then the business rule has been violated. Therefore, create a constraint or trigger that tests this.


答:
For the js

```<code>const user = '{{$user->id}}'
</code>```

For the html

```<code><a href="{{ route('get_user', ['user' => $user->id]) }}">
</code>```

Title: How to write PHP code containing {} in blade

Body:
Can someone tell me what is wrong with my syntax? I am trying to write this set of php code in the a laravel blade file

  @php  $identifiedIndex = $relevantTicketFlows->search(function($query) use ($data->ticket_flow_id){return $query->id == $data->ticket_flow_id;});
                                                            echo '
 $relevantTicketFlows[$identifiedIndex]
 '
                                                        @endphp

Body:
For the js

const user = '{{$user->id}}'

For the html

<a href="{{ route('get_user', ['user' => $user->id]) }}">


问:
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement in SpringBoot with h2 and JPA
While running spring boot with h2 database and JPA i am getting below error.

```<code>org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
</code>```

It is caused due to below one

```<code>Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE EXCHANGE_VALUE (ID INTEGER NOT NULL, CONVERSION_MULTIPLE DECIMAL(19,2), FROM[*] VARCHAR(255), PORT INTEGER NOT NULL, TO VARCHAR(255), PRIMARY KEY (ID)) "; expected "identifier"; SQL statement:
create table exchange_value (id integer not null, conversion_multiple decimal(19,2), from varchar(255), port integer not null, to varchar(255), primary key (id)) [42001-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.message.DbException.getSyntaxError(DbException.java:217) ~[h2-1.4.197.jar:1.4.197]
</code>```

My hibernate class

```<code>import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Exchange_Value")
public class ExchangeValue {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String from;
    private String to;
    private BigDecimal conversionMultiple;
    private int port;

    public ExchangeValue() {

    }

    public ExchangeValue(String from, String to, BigDecimal conversionMultiple) {
        super();
//      this.id = id;
        this.from = from;
        this.to = to;
        this.conversionMultiple = conversionMultiple;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
</code>```

application.properties is below

```<code>spring.application.name=currency-exchange-service
server.port=8000
spring.jpa.hibernate.ddl-auto= create-drop
</code>```

Just want to know as to what i am missing in the code tried adding spring.jpa.hibernate.ddl-auto= create-drop but it did not helped.

答:
Adding to others observation, I got the same error when a column name contains hyphen.

Error

```<code> @Column(name = "COST-CENTER")
   private String costCenter;
</code>```

Fixed

```<code>  @Column(name = "COST_CENTER")
   private String costCenter;
</code>```

Body:
While running spring boot with h2 database and JPA i am getting below error.

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]

It is caused due to below one

Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE TABLE EXCHANGE_VALUE (ID INTEGER NOT NULL, CONVERSION_MULTIPLE DECIMAL(19,2), FROM[*] VARCHAR(255), PORT INTEGER NOT NULL, TO VARCHAR(255), PRIMARY KEY (ID)) "; expected "identifier"; SQL statement:
create table exchange_value (id integer not null, conversion_multiple decimal(19,2), from varchar(255), port integer not null, to varchar(255), primary key (id)) [42001-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.message.DbException.getSyntaxError(DbException.java:217) ~[h2-1.4.197.jar:1.4.197]

My hibernate class

import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Exchange_Value")
public class ExchangeValue {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String from;
    private String to;
    private BigDecimal conversionMultiple;
    private int port;

    public ExchangeValue() {

    }

    public ExchangeValue(String from, String to, BigDecimal conversionMultiple) {
        super();
//      this.id = id;
        this.from = from;
        this.to = to;
        this.conversionMultiple = conversionMultiple;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

application.properties is below

spring.application.name=currency-exchange-service
server.port=8000
spring.jpa.hibernate.ddl-auto= create-drop

Just want to know as to what i am missing in the code tried adding spring.jpa.hibernate.ddl-auto= create-drop but it did not helped.

Body:
Adding to others observation, I got the same error when a column name contains hyphen.

Error

 @Column(name = "COST-CENTER")
   private String costCenter;

Fixed

  @Column(name = "COST_CENTER")
   private String costCenter;


问:
Problem with SVN in iPhone?
I am using Smart SVN for committed my code to server. I have faced some problem, some of the classes are there in my project work copy and the server also. When i open that project file and i missed some classes and images in the xcode file. But all the files are in the project work copy, when opened that file some files are missing only in Xcode. After that, i have to drag those missing my file from my local copy to Xcode file, then it works fine. In the server all files are there, but i donno why it is not coming to Xcode folder. </p>

答: The thing is, Xcode doesnt show all the files that are in the folder! they have to be inside xcode too! in the main project file there is some XML that XCode use to control those files! so if you have any file just in the folder xcode wont display it! You always have to drag and drop to it! However after u project is with all files inside you just have to commit your project file and should be fine afterwards! </p>

Title: Problem with SVN in iPhone?


问:
react table select rows - programmatically select rows based on input props
I have created a react table with select rows following this example.
I'm trying to modify it so that when the data loads, the corresponding checkbox is either checked or unchecked based on the row data's included value. The value doesn't seem to be recognized and when I check/uncheck a row the onChange console.log event isn't being fired. What am I doing wrong.

Heres my Sandbox Example

DATA

```<code>[
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 6487,
    sourceId: "WS002",
    sourceName: "GROVE SPRING",
    flowRate: 461,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4742,
    sourceId: "WS004",
    sourceName: "WELL #1",
    flowRate: 1100,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4743,
    sourceId: "WS005",
    sourceName: "100 W (WELL #2)                         ",
    flowRate: 800,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4744,
    sourceId: "WS007",
    sourceName: "NORTH (WELL #3)                         ",
    flowRate: 900,
    flowUom: "GPM   ",
    included: true
  }
];
</code>```

INDETERMINATE CHECKBOX

```<code>const IndeterminateCheckbox = React.forwardRef(
  ({ indeterminate, checked, name, ...rest }, ref) => {
    const defaultRef = React.useRef(checked);
    const resolvedRef = ref || defaultRef;

    React.useEffect(() => {
      resolvedRef.current.indeterminate = indeterminate;
      resolvedRef.current.checked = checked;
    }, [resolvedRef, indeterminate, checked]);

    return (
      <>
        <input
          type="checkbox"
          ref={resolvedRef}
          checked={checked}
          name={name}
          id={name}
          {...rest}
        />
      </>
    );
  }
);
</code>```

REACT TABLE

```<code>
function ReactTable({
  columns,
  data,
  handleCheckboxSelection,
  handleCheckboxStateChange
}) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow,
    selectedFlatRows
  } = useTable(
    {
      columns,
      data
    },
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => [
        // Let's make a column for selection
        {
          id: "selection",
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: (
            { getToggleAllRowsSelectedProps },
            handleCheckboxStateChange
          ) => (
            <div>
              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
            </div>
          ),
          // The cell can use the individual row's getToggleRowSelectedProps method
          // to the render a checkbox
          Cell: ({ row }) => (
            <div>
              <IndeterminateCheckbox
                name={row.original.sourceId}
                onChange={(row) => console.log(row.original)} //not firing
                checked={row.original.included}
                {...row.getToggleRowSelectedProps()}
              />
            </div>
          )
        },
        ...columns
      ]);
    }
  );

  // Render the UI for your table
  return (
    <>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.slice(0, 10).map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          {footerGroups.map((group) => (
            <tr {...group.getFooterGroupProps()}>
              {group.headers.map((column) => (
                <td {...column.getFooterProps()}>
                  <b>{column.render("Footer")}</b>
                </td>
              ))}
            </tr>
          ))}
        </tfoot>
      </table>
      <button onClick={() => handleCheckboxSelection(selectedFlatRows)}>
        Save
      </button>
    </>
  );
}
</code>```

TABLE IMPLEMENTATION

```<code>const MyDataTable = ({
  data
}) => {

const handleCheckboxSelection = (array) => {
    console.log(array.map((d) => d.original));
  };

  const columns = React.useMemo(
    () => [
      {
        Header: "Source ID",
        accessor: "sourceId"
      },
      {
        Header: "Source Name",
        accessor: "sourceName"
      },
      {
        Header: "Flow Rate (GPM)",
        accessor: (d) => {
          return d.flowRate ? numberWithCommas(d.flowRate) : "";
        }
      }
    ],
    []
  );
  return (
    <ReactTable
      columns={columns}
      data={data}
      handleCheckboxSelection={handleCheckboxSelection}
    />
  );
};
</code>```

答:
you have to refresh your Table.

you can use useState.

example : you can add onClick={this.mychange} to your save Button.

```<code>mychange = async () => {

    this.setState({
        List: //the new List Data
    })

  }
</code>```

and dont forget the Constructor.

```<code>constructor() {
    super();
    this.state = {
      List: anyList,
    };
  }
</code>```

Body:
I have created a react table with select rows following this example.
I'm trying to modify it so that when the data loads, the corresponding checkbox is either checked or unchecked based on the row data's included value. The value doesn't seem to be recognized and when I check/uncheck a row the onChange console.log event isn't being fired. What am I doing wrong.

Heres my Sandbox Example

DATA

[
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 6487,
    sourceId: "WS002",
    sourceName: "GROVE SPRING",
    flowRate: 461,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4742,
    sourceId: "WS004",
    sourceName: "WELL #1",
    flowRate: 1100,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4743,
    sourceId: "WS005",
    sourceName: "100 W (WELL #2)                         ",
    flowRate: 800,
    flowUom: "GPM   ",
    included: true
  },
  {
    systemId: 13,
    deqId: "25007",
    facilityId: 4744,
    sourceId: "WS007",
    sourceName: "NORTH (WELL #3)                         ",
    flowRate: 900,
    flowUom: "GPM   ",
    included: true
  }
];

INDETERMINATE CHECKBOX

const IndeterminateCheckbox = React.forwardRef(
  ({ indeterminate, checked, name, ...rest }, ref) => {
    const defaultRef = React.useRef(checked);
    const resolvedRef = ref || defaultRef;

    React.useEffect(() => {
      resolvedRef.current.indeterminate = indeterminate;
      resolvedRef.current.checked = checked;
    }, [resolvedRef, indeterminate, checked]);

    return (
      <>
        <input
          type="checkbox"
          ref={resolvedRef}
          checked={checked}
          name={name}
          id={name}
          {...rest}
        />
      </>
    );
  }
);

REACT TABLE

function ReactTable({
  columns,
  data,
  handleCheckboxSelection,
  handleCheckboxStateChange
}) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow,
    selectedFlatRows
  } = useTable(
    {
      columns,
      data
    },
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => [
        // Let's make a column for selection
        {
          id: "selection",
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: (
            { getToggleAllRowsSelectedProps },
            handleCheckboxStateChange
          ) => (

              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />

          ),
          // The cell can use the individual row's getToggleRowSelectedProps method
          // to the render a checkbox
          Cell: ({ row }) => (

              <IndeterminateCheckbox
                name={row.original.sourceId}
                onChange={(row) => console.log(row.original)} //not firing
                checked={row.original.included}
                {...row.getToggleRowSelectedProps()}
              />

          )
        },
        ...columns
      ]);
    }
  );

  // Render the UI for your table
  return (
    <>

          {headerGroups.map((headerGroup) => (

              {headerGroup.headers.map((column) => (
                {column.render("Header")}
              ))}

          ))}

          {rows.slice(0, 10).map((row, i) => {
            prepareRow(row);
            return (

                {row.cells.map((cell) => {
                  return (
                    {cell.render("Cell")}
                  );
                })}

            );
          })}

          {footerGroups.map((group) => (

              {group.headers.map((column) => (

                  {column.render("Footer")}

              ))}

          ))}

      <button onClick={() => handleCheckboxSelection(selectedFlatRows)}>
        Save
      </button>
    </>
  );
}

TABLE IMPLEMENTATION

const MyDataTable = ({
  data
}) => {

const handleCheckboxSelection = (array) => {
    console.log(array.map((d) => d.original));
  };

  const columns = React.useMemo(
    () => [
      {
        Header: "Source ID",
        accessor: "sourceId"
      },
      {
        Header: "Source Name",
        accessor: "sourceName"
      },
      {
        Header: "Flow Rate (GPM)",
        accessor: (d) => {
          return d.flowRate ? numberWithCommas(d.flowRate) : "";
        }
      }
    ],
    []
  );
  return (
    <ReactTable
      columns={columns}
      data={data}
      handleCheckboxSelection={handleCheckboxSelection}
    />
  );
};

Body:
you have to refresh your Table.

you can use useState.

example : you can add onClick={this.mychange} to your save Button.

mychange = async () => {

    this.setState({
        List: //the new List Data
    })

  }

and dont forget the Constructor.

constructor() {
    super();
    this.state = {
      List: anyList,
    };
  }


问:
Cypress does not always executes click on element
I am automating Google Calculator.
And from time to time Cypress is not able to execute click on button.
The tests click on buttons (0 to 9 ) and do some simple math operations.
And in 30% chance it can not click on element and the test will fail.

I also recorded a video when issue appears.

Video here

My Project is located here:
https://github.com/afiliptsov/test-project

```<code>To run the test run : "npm run test:e2e:functional"
</code>```

I tried to use different locator. Initially i was using just ID ex(#cwbt15 ) but after i made more specific locator ( #cwbt15 > .cwbtpl > .cwbts) and still having same issue.

Does anyone knows why it happens and how to avoid such behavior?

The project structure is :

cypress/PageObject.js - place where all elements declared.

cypress/support/commands.js - place where function click created and
verification of value getting updated.

cypress/integration/functional/delete.spec.js - test which was on the
video

答:
In my case I had to make sure the button is visible(or not disabled), then mouseover, then click:

```<code> cy.contains(/activate/i)
  .should('be.visible')
  .trigger('mouseover')
  .click({ force: true });
</code>```

PS. /***/i means ignore letter case.

Body:
I am automating Google Calculator.
And from time to time Cypress is not able to execute click on button.
The tests click on buttons (0 to 9 ) and do some simple math operations.
And in 30% chance it can not click on element and the test will fail.

I also recorded a video when issue appears.

Video here

My Project is located here:
https://github.com/afiliptsov/test-project

To run the test run : "npm run test:e2e:functional"

I tried to use different locator. Initially i was using just ID ex(#cwbt15 ) but after i made more specific locator ( #cwbt15 > .cwbtpl > .cwbts) and still having same issue.

Does anyone knows why it happens and how to avoid such behavior?

The project structure is :

cypress/PageObject.js - place where all elements declared.

cypress/support/commands.js - place where function click created and
verification of value getting updated.

cypress/integration/functional/delete.spec.js - test which was on the
video

Body:
In my case I had to make sure the button is visible(or not disabled), then mouseover, then click:

 cy.contains(/activate/i)
  .should('be.visible')
  .trigger('mouseover')
  .click({ force: true });

PS. /***/i means ignore letter case.


问:
Laravel Fatal Error memory but memory_limit set to 2048MB
I have just set up a new Laravel 8 project. When i try and run it i get the following fatal error:

```<code>PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /media/cal/500GB/cal/backend/vendor/composer/autoload_static.php on line 2297
</code>```

PHP memory_limit is set to 2048MB

if I try and run any command related to Laravel or Composer I get a fatal error so this command

```<code>laravel --version

</code>```

gives me this error:

```<code>PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes) in /home/cal/.config/composer/vendor/symfony/console/Color.php on line 165
</code>```

Even just typing composer give me the memory_error.

This command shows I have 2048MB memory_limit

```<code>php -r "echo ini_get('memory_limit').PHP_EOL;"

</code>```

Where does composer get that value of just 2MB from?

How can I fix this please? Any help is greatly appreciated.

答: If  php -r "echo ini_get('memory_limit').PHP_EOL;" prints a setting of 2048MB, you mis-configured the memory limit. According to the documentation, it should not contain a B at the end. Try to set it to 2048M instead

Body:
I have just set up a new Laravel 8 project. When i try and run it i get the following fatal error:

PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /media/cal/500GB/cal/backend/vendor/composer/autoload_static.php on line 2297

PHP memory_limit is set to 2048MB

if I try and run any command related to Laravel or Composer I get a fatal error so this command

laravel --version

gives me this error:

PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes) in /home/cal/.config/composer/vendor/symfony/console/Color.php on line 165

Even just typing composer give me the memory_error.

This command shows I have 2048MB memory_limit

php -r "echo ini_get('memory_limit').PHP_EOL;"

Where does composer get that value of just 2MB from?

How can I fix this please? Any help is greatly appreciated.