问:
Passing props into external stylesheet in React Native?
I'm new to React and React Native. At the moment for each component I'm breaking the code into 2 separate files:

index.js for all the React code, and;

styles.js for the StyleSheet

Is there a way to pass props into the external StyleSheet?

Example:
index.js:

render() {
  const iconColor = this.props.color || '#000';
  const iconSize = this.props.size || 25;

  return (
    <Icon style={styles.icon} />
  );
}```
</div>
</div>
</p>

<p>Example <code>styles.js</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const styles = StyleSheet.create({
  icon : {
    color: iconColor,
    fontSize: iconSize
  }
});</code>```

The code above does not work, but it's more there just to get the point across of what I'm trying to do. Any help is much appreciated!

答:
If you do not prefer to create a class then simply just create a function followed by a key and return an object from the function, you just have to pass the parameter by which you want to evaluate the condition. here is the exmple

```<code>export const Style = StyleSheet.create({
 locatorTextInputContainer: locatorType => ({
        flexDirection: 'row',
        backgroundColor: locatorType == 'None' || locatorType == '' ? GColors.separatorColor : GColors.white,
        marginBottom: 10,
        paddingBottom: 5,
        marginStart: 10,
        marginEnd: 10,
   })
})
</code>```

and you can use it as follows

```<code> <View style={Style.locatorTextInputContainer(locatorType)}>
    <TextInput
        value={sourceLocator}
        onChangeText={(text) => {
            dispatch(setSourceLocator(text))
        }}/>
 </View>
</code>```

Body:
I'm new to React and React Native. At the moment for each component I'm breaking the code into 2 separate files:

index.js for all the React code, and;

styles.js for the StyleSheet

Is there a way to pass props into the external StyleSheet?

Example:
index.js:

render() {
  const iconColor = this.props.color || '#000';
  const iconSize = this.props.size || 25;

  return (
    <Icon style={styles.icon} />
  );
}

Example styles.js:

const styles = StyleSheet.create({
  icon : {
    color: iconColor,
    fontSize: iconSize
  }
});

The code above does not work, but it's more there just to get the point across of what I'm trying to do. Any help is much appreciated!

Body:
If you do not prefer to create a class then simply just create a function followed by a key and return an object from the function, you just have to pass the parameter by which you want to evaluate the condition. here is the exmple

export const Style = StyleSheet.create({
 locatorTextInputContainer: locatorType => ({
        flexDirection: 'row',
        backgroundColor: locatorType == 'None' || locatorType == '' ? GColors.separatorColor : GColors.white,
        marginBottom: 10,
        paddingBottom: 5,
        marginStart: 10,
        marginEnd: 10,
   })
})

and you can use it as follows

 <View style={Style.locatorTextInputContainer(locatorType)}>
    <TextInput
        value={sourceLocator}
        onChangeText={(text) => {
            dispatch(setSourceLocator(text))
        }}/>
 </View>


来源: stackexchange

问:
Kotlin intent.putExtra for Serializable gives compilation error
I'm trying to pass a Serializable data class from one activity to another via intent, but Android Studio doesn't accept my data class as an argument. The editor says "None of the following functions can be called with the arguments supplied". If I try to cast my data class to Serializable, it says "this cast can never succeed".
My data class:

```<code>    @Serializable
data class MessageModel(
    val timeStamp: String,
    val body: String
)
</code>```

And code for passing the extra to the intent:

```<code>    val intent = Intent(this, MessageActivity::class.java)
    val test = MessageModel("timeStamp", "message body")
    intent.putExtra("A string for referencing", test)
    startActivity(intent)
</code>```

Second method I tried:

```<code>val intent = Intent(this, MessageActivity::class.java)
val test = MessageModel("timeStamp", "message body")
intent.putExtra("A string for referencing", test as Serializable)
startActivity(intent)
</code>```

I've tried building from the terminal with gradle in case it was Android Studio acting up, but the same problem occurs.

Note: passing string extras works fine, it's just some problem with Serializable.
I don't see what I'm doing wrong, every tutorial and thread I can find simply pass a Serializable object and it works.
Any help is greatly appreciated!

答:
You should implement Serializeable, not annotate.

data class MessageModel(
val timeStamp: String,
val body: String
): Serializable

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to pass a Serializable data class from one activity to another via intent, but Android Studio doesn't accept my data class as an argument. The editor says "None of the following functions can be called with the arguments supplied". If I try to cast my data class to Serializable, it says "this cast can never succeed".
My data class:

    @Serializable
data class MessageModel(
    val timeStamp: String,
    val body: String
)

And code for passing the extra to the intent:

    val intent = Intent(this, MessageActivity::class.java)
    val test = MessageModel("timeStamp", "message body")
    intent.putExtra("A string for referencing", test)
    startActivity(intent)

Second method I tried:

val intent = Intent(this, MessageActivity::class.java)
val test = MessageModel("timeStamp", "message body")
intent.putExtra("A string for referencing", test as Serializable)
startActivity(intent)

I've tried building from the terminal with gradle in case it was Android Studio acting up, but the same problem occurs.

Note: passing string extras works fine, it's just some problem with Serializable.
I don't see what I'm doing wrong, every tutorial and thread I can find simply pass a Serializable object and it works.
Any help is greatly appreciated!


问:
check for non ascii characters in matlab
i have a result string that sometimes hold non ascii values. These non ascii values cause trouble so i need to check for their presence in the result string.

i tried with these two methods

```<code>if (regexpi(result , ^\s\x{20}-\x{7e}))
display('non ascii');
end
</code>```

and

```<code>if any(result  < 128)
else
display('non ascii');
end
</code>```

but it didn't work. Any help is greatly appreciated.

答:
regexprep can be used to find and remove the non-ascii characters. For example:

```<code>out = regexprep(result, '[^0-9a-zA-Z.\s]+', '')
</code>```

See the comments by @amro in Remove non ASCII characters in octave

ContentLicense: CC BY-SA 3.0

Body:
i have a result string that sometimes hold non ascii values. These non ascii values cause trouble so i need to check for their presence in the result string.

i tried with these two methods

if (regexpi(result , ^\s\x{20}-\x{7e}))
display('non ascii');
end

and

if any(result  < 128)
else
display('non ascii');
end

but it didn't work. Any help is greatly appreciated.

Body:
regexprep can be used to find and remove the non-ascii characters. For example:

out = regexprep(result, '[^0-9a-zA-Z.\s]+', '')

See the comments by @amro in Remove non ASCII characters in octave


问:
How to automate release notes using GIT merge descriptions
All,

In our organization we are trying to automate generating RELEASE NOTES using GIT Merge requests.
Is there any better way to do this, preferably looking for a solution in NodeJS.

答:
When using something like standard-version and commitizen for standardization of your commits you can make use of a GitLab CI-Pipeline that generates your release notes based on the changelog that is generated by standard-version

Within this Repository the project was set up using nodejs, react and typescript, but the configuration would be the same.
This CI-Configuration is an example of the aforementioned pipeline configuration.

The same thing would also be applicable for Github actions with a little modification for Github-specific action syntax.

Without CI-Pipeline

The same thing would also be applicable for non-CI setups since the commands used in the ci-configuration are as well executable in local machines, but that way you would have some manual effort


问:
Debug window toolbar console missing arrows
I am trying to debug a simple program in Python with PyCharm debugger but when I put a break point and run debugger the arrows such as "Step Into" or "Step Over" doesn't show so I can't move on with debugging. The last time I used PyCharm I didn't have this problem and I don't believe I did anything that can change the debugger.

答: Try to uninstall it from the control panel and download it again</p>


问:
React select onChange value Type

 <Select

        options={options}
        value={selectedBusinessList}
        isMulti
        placeholder="Select Business"
        onChange={(value: any) => setSelectedBusinessList(value)}
        onInputChange={query => {
          if (query) {
            setOptions([]);
            fetchBusiness(query, { limit: 10, offset: 0 });
          }
        }}
      />```

What should be type of onChange event value.

Here each value is of

type OptionType = { label : string; value:string}

setSelectedBusinessList() is taking argument of type OptionType

答:
Try this :</p>
```<code>onChange={(e: any) => setSelectedBusinessList(e.target.value)}
</code>```

Title: React select onChange value Type

Body:
 <Select

        options={options}
        value={selectedBusinessList}
        isMulti
        placeholder="Select Business"
        onChange={(value: any) => setSelectedBusinessList(value)}
        onInputChange={query => {
          if (query) {
            setOptions([]);
            fetchBusiness(query, { limit: 10, offset: 0 });
          }
        }}
      />

What should be type of onChange event value.

Here each value is of

type OptionType = { label : string; value:string}

setSelectedBusinessList() is taking argument of type OptionType

Body:
Try this :

onChange={(e: any) => setSelectedBusinessList(e.target.value)}


问:
Cloudflare Pages - Cloudflare Workers
So i started to get my hands dirty with cloudflare pages and workers

My thought is

get a domain mydomain.com (done)

make a static site @ github myaccount.github.io (done)

make a cloudflare pages page add CNAME to DNS ZONE (done) so myaccount.github.io can be @ my-official-site.com (done)

make a cloudflare worker https://myworker.myclaccount.workers.dev (done)

So when i request my-official-site.com i get the content of myaccount.github.io

Now i want to run from my myaccount.github.io a worker to get some html or json or....

I trying to fetch from my myaccount.github.io (index.html)

```<code><script>
fetch('https://myworker.myclaccount.workers.dev')
  .then(response => response.json())
  .then(data => console.log(data));
</script>
</code>```

I get the request to my worker like this

```<code>const html =
  "<p>This markup was generated by a Cloudflare Worker.</p>"

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})
</code>```

The problem is

```<code>Access to fetch at 'https://myworker.myclaccount.workers.dev/'
from origin 'my-official-site.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code>```

I create a

_headers.txt   (https://developers.cloudflare.com/pages/platform/headers) at the root of my github "site" with this

```<code>/*
  Access-Control-Allow-Origin: *
</code>```

but the same...

I'm new to serverless and jamstack (i now js, css, html) but new to this concept

knowledge (android, c#, php, wp, unity, some node.js)

Thank you for your help.

答:
At the top of the Cloudflare documentation, it states

Custom headers defined in the _headers file are not currently applied to responses from Functions

I believe this is the issue you are encountering. You need to apply the headers directly in your worker function, as specified here -

https://developers.cloudflare.com/pages/how-to/add-custom-http-headers

On a side note, I'd recommend updating your question title to reflect what is being asked.

Title: Cloudflare Pages - Cloudflare Workers

Body:
So i started to get my hands dirty with cloudflare pages and workers

My thought is

get a domain mydomain.com (done)

make a static site @ github myaccount.github.io (done)

make a cloudflare pages page add CNAME to DNS ZONE (done) so myaccount.github.io can be @ my-official-site.com (done)

make a cloudflare worker https://myworker.myclaccount.workers.dev (done)

So when i request my-official-site.com i get the content of myaccount.github.io

Now i want to run from my myaccount.github.io a worker to get some html or json or....

I trying to fetch from my myaccount.github.io (index.html)

I get the request to my worker like this

const html =
  "
This markup was generated by a Cloudflare Worker.
"

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})

The problem is

Access to fetch at 'https://myworker.myclaccount.workers.dev/'
from origin 'my-official-site.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I create a

_headers.txt   (https://developers.cloudflare.com/pages/platform/headers) at the root of my github "site" with this

/*
  Access-Control-Allow-Origin: *

but the same...

I'm new to serverless and jamstack (i now js, css, html) but new to this concept

knowledge (android, c#, php, wp, unity, some node.js)

Thank you for your help.


问:
Sort a list of object w.r.t to a particular member/state
I have a list of java object that have 4 members.

```<code>int id;
String name;
String age;
int order;
</code>```

I want to sort the list of this object w.r.t name

答:
Either you implement a Comparator like this:

```<code>public static void main(String[] args) throws IOException {

    List<MyObject> list = new ArrayList<MyObject>();

    // add your objects to the list

    Collections.sort(list, new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.name.compareTo(o2.name);
        }
    });
}
</code>```

Or you can implement the Comparable interface on MyObject:

```<code>class MyObject implements Comparable<MyObject> {
    int id;
    String name;
    String age;
    int order;

    @Override
    public int compareTo(MyObject o) {
        return name.compareTo(o.name);
    }
}

public static void main(String[] args) throws IOException {
    ....
    Collections.sort(list); // with the comparable interface
}
</code>```

Body:
I have a list of java object that have 4 members.

int id;
String name;
String age;
int order;

I want to sort the list of this object w.r.t name

Body:
Either you implement a Comparator like this:

public static void main(String[] args) throws IOException {

    List<MyObject> list = new ArrayList<MyObject>();

    // add your objects to the list

    Collections.sort(list, new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.name.compareTo(o2.name);
        }
    });
}

Or you can implement the Comparable interface on MyObject:

class MyObject implements Comparable<MyObject> {
    int id;
    String name;
    String age;
    int order;

    @Override
    public int compareTo(MyObject o) {
        return name.compareTo(o.name);
    }
}

public static void main(String[] args) throws IOException {
    ....
    Collections.sort(list); // with the comparable interface
}


问:
how to use chrome api in redux-saga
I'm trying to make 'get_current_url' func with redux-saga
Btw, I've been making chrome extension with react js.
So, I gotta have to use chrome.tabs.query api to get current uri
Here is my code

```<code>import { Action } from "redux";
import { call, fork, put, takeEvery, takeLatest } from "redux-saga/effects";
import { all } from "redux-saga/effects";
import { timeActions } from "./timeSlice";

function getUrlApi() {
  const queryInfo = { active: true, currentWindow: true };
  let currentUrl: string = '';

  chrome.tabs.query(queryInfo, (tabs: chrome.tabs.Tab[]) => {
    const id = tabs[0].id;

    chrome.tabs.sendMessage(id || 0, "GET_URL", (res: any) => {
        console.log(res);           // ---> res.url will be receive data
        currentUrl = res.url;       // I wanna allocate this data to currentUrl and return but there is something kind of lexical problem
    })
  });
  return currentUrl;
}

function* getUrl() {
  try {
    const test: string = yield getUrlApi();         // ---> always get undefined
    // yield timeActions.getUrlSuccess();
  } catch (err) {
    yield put(timeActions.getUrlFail(err));
  }
}

function* watchGetUrl() {
  yield takeLatest(timeActions.getUrl, getUrl);
}

export function* timeSaga() {
  yield all([fork(watchGetUrl)]);
}
</code>```

As you can see, I am trying to allocate res.url data to currentUrl;
But, there is something lexical problem.
As a consequence, it always return undefined;
How can i solve this problem. Thank you

答:
The problem is that the chrome api functions are asynchronous, so you are returning from the function before they are processed.

The chrome api supports promises, which are much easier to handle with sagas, so I'd suggest to use those instead.

async function getUrlApi() {
  const queryInfo = { active: true, currentWindow: true };

  const tabs = await chrome.tabs.query(queryInfo);
  const id = tabs[0].id;

  const res = await chrome.tabs.sendMessage(id || 0, "GET_URL");
  console.log(res);
  return res.url;
}
```

Title: how to use chrome api in redux-saga

Body:
I'm trying to make 'get_current_url' func with redux-saga
Btw, I've been making chrome extension with react js.
So, I gotta have to use chrome.tabs.query api to get current uri
Here is my code

import { Action } from "redux";
import { call, fork, put, takeEvery, takeLatest } from "redux-saga/effects";
import { all } from "redux-saga/effects";
import { timeActions } from "./timeSlice";

function getUrlApi() {
  const queryInfo = { active: true, currentWindow: true };
  let currentUrl: string = '';

  chrome.tabs.query(queryInfo, (tabs: chrome.tabs.Tab[]) => {
    const id = tabs[0].id;

    chrome.tabs.sendMessage(id || 0, "GET_URL", (res: any) => {
        console.log(res);           // ---> res.url will be receive data
        currentUrl = res.url;       // I wanna allocate this data to currentUrl and return but there is something kind of lexical problem
    })
  });
  return currentUrl;
}

function* getUrl() {
  try {
    const test: string = yield getUrlApi();         // ---> always get undefined
    // yield timeActions.getUrlSuccess();
  } catch (err) {
    yield put(timeActions.getUrlFail(err));
  }
}

function* watchGetUrl() {
  yield takeLatest(timeActions.getUrl, getUrl);
}

export function* timeSaga() {
  yield all([fork(watchGetUrl)]);
}

As you can see, I am trying to allocate res.url data to currentUrl;
But, there is something lexical problem.
As a consequence, it always return undefined;
How can i solve this problem. Thank you


问:
Flask AssertionError: View function mapping is overwriting an existing endpoint function: home
I'm trying to code a social network with flask on python anywhere
, everything was working fine before and without touching the imports I started to receive this error when I run routes.py

```<code>Traceback (most recent call last):
 File "/home/OurHub/mysite/routes.py", line 13, in <module>
    def home():
  File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 433, in decorator
    self.add_url_rule(rule, endpoint, f, **options)
  File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 54, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1084, in add_url_rule
    raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: home
</code>```

I tried to put everything in a single file and I don't have two functions that have the same name
here is the start of my routes.py code

```<code>import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from __init__ import app, db, bcrypt
from forms import FormCreerCompte, FormConnecter, ModifierCompte, FormPoste
from modelsdb import Profil, Poste
from flask_login import login_user, current_user, logout_user, login_required

@app.route("/")
@app.route("/home")
def home():
    page = request.args.get('page',1, type=int)
    posts = Poste.query.paginate(page=page, per_page=5)
    return render_template('page1.html', posts=posts)
</code>```

and the code from the innit file:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = '6dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://OurHub:ninjQ@OurHub.mysql.pythonanywhere-services.com/OurHub$default'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view= 'connecter'
login_manager.login_message_category = 'primary'

import routes
</code>```

Body:
I'm trying to code a social network with flask on python anywhere
, everything was working fine before and without touching the imports I started to receive this error when I run routes.py

Traceback (most recent call last):
 File "/home/OurHub/mysite/routes.py", line 13, in <module>
    def home():
  File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 433, in decorator
    self.add_url_rule(rule, endpoint, f, **options)
  File "/usr/local/lib/python3.9/site-packages/flask/scaffold.py", line 54, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1084, in add_url_rule
    raise AssertionError(
AssertionError: View function mapping is overwriting an existing endpoint function: home

I tried to put everything in a single file and I don't have two functions that have the same name
here is the start of my routes.py code

import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort
from __init__ import app, db, bcrypt
from forms import FormCreerCompte, FormConnecter, ModifierCompte, FormPoste
from modelsdb import Profil, Poste
from flask_login import login_user, current_user, logout_user, login_required

@app.route("/")
@app.route("/home")
def home():
    page = request.args.get('page',1, type=int)
    posts = Poste.query.paginate(page=page, per_page=5)
    return render_template('page1.html', posts=posts)

and the code from the innit file:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = '6dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://OurHub:ninjQ@OurHub.mysql.pythonanywhere-services.com/OurHub$default'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view= 'connecter'
login_manager.login_message_category = 'primary'

import routes

Body: After a lot of research, I tried to delete a piece of code that I had commented in my html file and it worked! Maybe because the html comment "<!-->" doesn't work with python code inserts "{%%}". The error still appears when I run route, but the application works fine, I was looking for the error in the wrong place after all.


问:
How to create a function in PHP
I'm trying to create a function called saveorder. This is my code so far:

```<code><?php
//function foo($arg_1, $arg_2, /* ..., */ $arg_n)
function saveorder($orderid,$txnid,$date,$amount)
{
    $a_str = array(
        "orderid"=>"175",
        "txnid"=>"RC456456456",
        "date"=>"54156456465",
        "amount"=>"109$"
    );

    $file = 'order.dat';

    $contents = implode("|", $a_str);

    $contents .= PHP_EOL . PHP_EOL;
    file_put_contents($file, $contents);
}
echo "function will return=".saveorder($orderid);
?>
</code>```

I think I'm doing it wrong because I never created my own function. Still, however, I want to create this function to save the order in the order.dat file. Can anyone please help me create this function? I'm trying very hard but I'm unable to create it.

答:
Actually, you didn't return any value in your function, so it did run correctly.

You need add like following statment at the end of function

```<code><?php
function saveorder($orderid,$txnid,$date,$amount) //function foo($arg_1, $arg_2, /* ..., */ $arg_n) {
    $a_str = array(    "orderid"=>"175",    "txnid"=>"RC456456456",    "date"=>"54156456465",    "amount"=>"109$"  );
    $file = 'order.dat';
    $contents = implode("|", $a_str);
    $contents .= PHP_EOL . PHP_EOL;
    res = file_put_contents($file, $contents);
    if(res){
        return true;
    } else {
        return false;
    }
}
echo "function will return=".saveorder($orderid);
?>
</code>```

Title: How to create a function in PHP

Body:
I'm trying to create a function called saveorder. This is my code so far:

<?php
//function foo($arg_1, $arg_2, /* ..., */ $arg_n)
function saveorder($orderid,$txnid,$date,$amount)
{
    $a_str = array(
        "orderid"=>"175",
        "txnid"=>"RC456456456",
        "date"=>"54156456465",
        "amount"=>"109$"
    );

    $file = 'order.dat';

    $contents = implode("|", $a_str);

    $contents .= PHP_EOL . PHP_EOL;
    file_put_contents($file, $contents);
}
echo "function will return=".saveorder($orderid);
?>

I think I'm doing it wrong because I never created my own function. Still, however, I want to create this function to save the order in the order.dat file. Can anyone please help me create this function? I'm trying very hard but I'm unable to create it.

Body:
Actually, you didn't return any value in your function, so it did run correctly.

You need add like following statment at the end of function

<?php
function saveorder($orderid,$txnid,$date,$amount) //function foo($arg_1, $arg_2, /* ..., */ $arg_n) {
    $a_str = array(    "orderid"=>"175",    "txnid"=>"RC456456456",    "date"=>"54156456465",    "amount"=>"109$"  );
    $file = 'order.dat';
    $contents = implode("|", $a_str);
    $contents .= PHP_EOL . PHP_EOL;
    res = file_put_contents($file, $contents);
    if(res){
        return true;
    } else {
        return false;
    }
}
echo "function will return=".saveorder($orderid);
?>


问:
Display CSV with Tkinter
For my assessment I am attempting to create a password manager and display a list of information into different columns and rows with tkinter. The issue is that the information doesn't stay in line and gets put lower than the pervious. This is making it so the information is not aligned correctly. I have attempted increasing per line and padding but this makes the issue worse.

Code:

```<code>from tkinter import *
import csv

global passScreen

# Create and set the GUI for the passScreen of the Password Manager.
passScreen = Tk()
passScreen.geometry("1200x800")
passScreen.resizable(width=False, height=False)
passScreen.title("Password")

Label(passScreen, text="Type").grid(row=3, column=1, padx=40)
Label(passScreen, text="Username").grid(row=3, column=2, padx=40)
Label(passScreen, text="Password").grid(row=3, column=3, padx=40)
Label(passScreen, text="Name").grid(row=3, column=4, padx=40)
Label(passScreen, text="Specific").grid(row=3, column=5, padx=40)
Label(passScreen, text="Date Created").grid(row=3, column=6, padx=40)
Label(passScreen, text="Date Updated").grid(row=3, column=7, padx=40)

passfile = open("PassManager.txt", "r")
read = csv.reader(passfile)
data = list(read)

entrieslist = []

i = 0
for entries in list(range(0, len(data))):
    entrieslist.append(data[entries][0])

    Label(passScreen, text=data[entries][1]).grid(rowspan=i + 4, column=1)
    Label(passScreen, text=data[entries][2]).grid(rowspan=i + 4, column=2)
    Label(passScreen, text=data[entries][3]).grid(rowspan=i + 4, column=3)
    Label(passScreen, text=data[entries][4]).grid(rowspan=i + 4, column=4)
    Label(passScreen, text=data[entries][5]).grid(rowspan=i + 4, column=5)
    Label(passScreen, text=data[entries][6]).grid(rowspan=i + 4, column=6)
    Label(passScreen, text=data[entries][7]).grid(rowspan=i + 4, column=7)

passScreen.mainloop()
</code>```

PasswordManager.txt:

```<code>Matt,Application,111111111,1111111,11111,N/A,2022-02-07 14:21:28.481304,2022-02-07 14:21:28.481304
Matt,Application,222,1111111,111122,N/A,2022-02-07 14:24:20.892781,2022-02-07 14:24:20.892781
Matt,Application,222,1111111,111122,N/A,2022-02-07 14:24:21.596781,2022-02-07 14:24:21.596781
Matt,Website,gsdgsd,1212,1243dsg,gsdgsd,2022-02-07 14:24:26.385282,2022-02-07 14:24:26.385282
Matt,Website,gsdgsd,1212,1243dsg,gsdgsd,2022-02-07 14:24:27.053781,2022-02-07 14:24:27.053781
Matt,Application,gsdgsdg,sdgsdg,gsdgsd,N/A,2022-02-07 14:24:31.437782,2022-02-07 14:24:31.437782
Matt,Game,sdgsdgsdgsd,sgsd,sdgsd,gsdgds,2022-02-07 14:24:36.802780,2022-02-07 14:24:36.802780
Matt,Game,sdgsdgsdgsd,sgsd,sdgsd,gsdgds,2022-02-07 14:24:36.802780,2022-02-07 14:24:36.802780
</code>```

(I am sorry if my formatting for Stack overflow is incorrect!)

答:
You seem to be accessing the data "the hard way" because it can done simply in Python. I've fixed that and also fixed your display problems (I think). Don't know why you were using rowspan, since I don't think it is necessary — but again, I may not have understood what you how the display to look like (could only guess from from your somewhat convoluted code).

```<code>import csv
import tkinter as tk  # PEP 8 recommends against `import *`.

# Create and set the GUI for the passScreen of the Password Manager.
passScreen = tk.Tk()
passScreen.geometry("1200x800")
passScreen.resizable(width=False, height=False)
passScreen.title("Password")

col_names = ("Type", "Username", "Password", "Name", "Specific", "Date Created",
             "Date Updated")
for i, col_name in enumerate(col_names, start=1):
    tk.Label(passScreen, text=col_name).grid(row=3, column=i, padx=40)

with open("PassManager.txt", "r", newline="") as passfile:
    reader = csv.reader(passfile)
    data = list(reader)

entrieslist = []
for i, row in enumerate(data, start=4):
    entrieslist.append(row[0])
    for col in range(1, 8):
        tk.Label(passScreen, text=row[col]).grid(row=i, column=col)

passScreen.mainloop()
</code>```

Result:

Title: Display CSV with Tkinter

Body:
For my assessment I am attempting to create a password manager and display a list of information into different columns and rows with tkinter. The issue is that the information doesn't stay in line and gets put lower than the pervious. This is making it so the information is not aligned correctly. I have attempted increasing per line and padding but this makes the issue worse.

Code:

from tkinter import *
import csv

global passScreen

# Create and set the GUI for the passScreen of the Password Manager.
passScreen = Tk()
passScreen.geometry("1200x800")
passScreen.resizable(width=False, height=False)
passScreen.title("Password")

Label(passScreen, text="Type").grid(row=3, column=1, padx=40)
Label(passScreen, text="Username").grid(row=3, column=2, padx=40)
Label(passScreen, text="Password").grid(row=3, column=3, padx=40)
Label(passScreen, text="Name").grid(row=3, column=4, padx=40)
Label(passScreen, text="Specific").grid(row=3, column=5, padx=40)
Label(passScreen, text="Date Created").grid(row=3, column=6, padx=40)
Label(passScreen, text="Date Updated").grid(row=3, column=7, padx=40)

passfile = open("PassManager.txt", "r")
read = csv.reader(passfile)
data = list(read)

entrieslist = []

i = 0
for entries in list(range(0, len(data))):
    entrieslist.append(data[entries][0])

    Label(passScreen, text=data[entries][1]).grid(rowspan=i + 4, column=1)
    Label(passScreen, text=data[entries][2]).grid(rowspan=i + 4, column=2)
    Label(passScreen, text=data[entries][3]).grid(rowspan=i + 4, column=3)
    Label(passScreen, text=data[entries][4]).grid(rowspan=i + 4, column=4)
    Label(passScreen, text=data[entries][5]).grid(rowspan=i + 4, column=5)
    Label(passScreen, text=data[entries][6]).grid(rowspan=i + 4, column=6)
    Label(passScreen, text=data[entries][7]).grid(rowspan=i + 4, column=7)

passScreen.mainloop()

PasswordManager.txt:

Matt,Application,111111111,1111111,11111,N/A,2022-02-07 14:21:28.481304,2022-02-07 14:21:28.481304
Matt,Application,222,1111111,111122,N/A,2022-02-07 14:24:20.892781,2022-02-07 14:24:20.892781
Matt,Application,222,1111111,111122,N/A,2022-02-07 14:24:21.596781,2022-02-07 14:24:21.596781
Matt,Website,gsdgsd,1212,1243dsg,gsdgsd,2022-02-07 14:24:26.385282,2022-02-07 14:24:26.385282
Matt,Website,gsdgsd,1212,1243dsg,gsdgsd,2022-02-07 14:24:27.053781,2022-02-07 14:24:27.053781
Matt,Application,gsdgsdg,sdgsdg,gsdgsd,N/A,2022-02-07 14:24:31.437782,2022-02-07 14:24:31.437782
Matt,Game,sdgsdgsdgsd,sgsd,sdgsd,gsdgds,2022-02-07 14:24:36.802780,2022-02-07 14:24:36.802780
Matt,Game,sdgsdgsdgsd,sgsd,sdgsd,gsdgds,2022-02-07 14:24:36.802780,2022-02-07 14:24:36.802780

(I am sorry if my formatting for Stack overflow is incorrect!)

Body:
You seem to be accessing the data "the hard way" because it can done simply in Python. I've fixed that and also fixed your display problems (I think). Don't know why you were using rowspan, since I don't think it is necessary — but again, I may not have understood what you how the display to look like (could only guess from from your somewhat convoluted code).

import csv
import tkinter as tk  # PEP 8 recommends against `import *`.

# Create and set the GUI for the passScreen of the Password Manager.
passScreen = tk.Tk()
passScreen.geometry("1200x800")
passScreen.resizable(width=False, height=False)
passScreen.title("Password")

col_names = ("Type", "Username", "Password", "Name", "Specific", "Date Created",
             "Date Updated")
for i, col_name in enumerate(col_names, start=1):
    tk.Label(passScreen, text=col_name).grid(row=3, column=i, padx=40)

with open("PassManager.txt", "r", newline="") as passfile:
    reader = csv.reader(passfile)
    data = list(reader)

entrieslist = []
for i, row in enumerate(data, start=4):
    entrieslist.append(row[0])
    for col in range(1, 8):
        tk.Label(passScreen, text=row[col]).grid(row=i, column=col)

passScreen.mainloop()

Result:


问:
Pyspark: isDeltaTable running forever
I want to check if a delta table in an s3 bucket is actually a delta table. I am trying do this by

```<code>    from delta import *
    from delta.tables import DeltaTable
    from pyspark.sql import SparkSession
    from pyspark.sql.functions import *

    spark = SparkSession.builder\
                        .appName('test')\
                        .getOrCreate()

    if DeltaTable.isDeltaTable(spark, "s3a://landing-zone/table_name/year=2022/month=2/part-0000-xyz.snappy.parquet"):
      print("bla")
    else:
      print("blabla")
</code>```

This code runs forever without returning any result. I tested it with a local delta table and there it works. When I trim the path url so it stops after the actual table name, the code shows the same behavior. I also generated a boto3 client and I can see the bucket list when calling s3.list_bucket(). Do I need to parse the client somehow into the if statement?

Thanks a lot in advance!

答:
I am an idiot, I forgot that it is not enough to just create a boto3 client, but I also have to make the actual connection to S3 via</p>
```<code>spark._jsc.hadoopConfiguration().set(...)
</code>```

Title: Pyspark: isDeltaTable running forever

Body:
I want to check if a delta table in an s3 bucket is actually a delta table. I am trying do this by

    from delta import *
    from delta.tables import DeltaTable
    from pyspark.sql import SparkSession
    from pyspark.sql.functions import *

    spark = SparkSession.builder\
                        .appName('test')\
                        .getOrCreate()

    if DeltaTable.isDeltaTable(spark, "s3a://landing-zone/table_name/year=2022/month=2/part-0000-xyz.snappy.parquet"):
      print("bla")
    else:
      print("blabla")

This code runs forever without returning any result. I tested it with a local delta table and there it works. When I trim the path url so it stops after the actual table name, the code shows the same behavior. I also generated a boto3 client and I can see the bucket list when calling s3.list_bucket(). Do I need to parse the client somehow into the if statement?

Thanks a lot in advance!

Body:
I am an idiot, I forgot that it is not enough to just create a boto3 client, but I also have to make the actual connection to S3 via

spark._jsc.hadoopConfiguration().set(...)


问:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
I have the following code:

```<code>class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}
</code>```

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

I have system level problems (either in DrJava or my Java install) or

I have some basic misunderstanding of how to construct a working program in java.

Any ideas?

答:
```<code>class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {

        PlayGround obj = new PlayGround();

        Thing obj2 = obj.new Thing();

        System.out.println("Hello, World!");
    }
}
</code>```

Body:
I have the following code:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

I have system level problems (either in DrJava or my Java install) or

I have some basic misunderstanding of how to construct a working program in java.

Any ideas?


问:
How to send a multi line sms with adb
After researching a while on how to send SMS's through ADB, I found a post that led me to this command:

adb shell service call isms 7 i32 0 s16 "com.android.mms.service" s16 "+mynumberhere" s16 "null" s16 'Text Goes Here' s16 "null" s16 "null"

This command works just fine to send single line text, but I want to be able to format the SMS to be multiple lines, for example:

```<code>This is line 1 of the SMS
This is line 2 of the SMS
And this is line 3
</code>```

I have tried to change the 'Text Goes Here' part to the following with no success:

```<code>"Test \n Test"
"Test /n Test"
"Test %n Test"
'Test \n Test'
'Test /n Test'
'Test %n Test'
"'Test\nTest'"
"'Test \n Test'"
"'Test/nTest'"
"'Test /n Test'"
"'Test'\n'Test'"
</code>```

Absolutely none of them work and I can't find any method to solve this problem, what can I do?

答:
try this

adb shell "NL=$'\n' ; am start -a android.intent.action.SENDTO -d sms:CCXXXXXXXXXX --es sms_body "SMS BODY ${NL} GOES HERE" --ez exit_on_sent true"

Title: How to send a multi line sms with adb

Body:
After researching a while on how to send SMS's through ADB, I found a post that led me to this command:

adb shell service call isms 7 i32 0 s16 "com.android.mms.service" s16 "+mynumberhere" s16 "null" s16 'Text Goes Here' s16 "null" s16 "null"

This command works just fine to send single line text, but I want to be able to format the SMS to be multiple lines, for example:

This is line 1 of the SMS
This is line 2 of the SMS
And this is line 3

I have tried to change the 'Text Goes Here' part to the following with no success:

"Test \n Test"
"Test /n Test"
"Test %n Test"
'Test \n Test'
'Test /n Test'
'Test %n Test'
"'Test\nTest'"
"'Test \n Test'"
"'Test/nTest'"
"'Test /n Test'"
"'Test'\n'Test'"

Absolutely none of them work and I can't find any method to solve this problem, what can I do?


问:
Generate const array of pointers to callback functions
I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here).
I use C++17.

Here is what I have:

```<code>using Callback = void(*)();
auto constexpr N = 2;

const Callback callbacks[N] = {
 [](){ auto i = 0; std::cout<<"callback " << i << "\n";},
 [](){ auto i = 1; std::cout<<"callback " << i << "\n";}
};

callbacks[0]();
callbacks[N-1]();
</code>```

Here is what I want:

```<code>const auto callbacks = generate_callbacks<N>();  // or generate_callbacks(N)
callbacks[i](); // cout<<"callback " << i << "\n";
</code>```

I tried various ways, but I keep running into the problems with constant parameters even when they are from a constexpr function or variadic template.

If I try this:

```<code>Callback callbacks[N] = { };

for(int i=0;i<N;++i)
{
callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
}

for(int i=0;i<N;++i)
{
callbacks[i]();
}
</code>```

I get the following error:

```<code>main.cpp:91:66: error: cannot convert ‘main()::’ to ‘Callback {aka void (*)()}’ in assignment
        callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
</code>```

If I make i static and leave out the capture it only uses the last value of i:

```<code>callback 2
callback 2
</code>```

This is odd to me as capturing should be done at construction. Are the lambdas constructed after the loop exits?

As for the purpose. I want to apply this technique to generating interrupt handlers for microcontrollers. I can put the function pointers in the interrupt vector table directly. These functions have no parameters and I don't know a clean way to detect which interrupt source called the handler. I can write a handler for each interrupt, but I don't like repeating this code 6 times:

```<code>void handler0()
{
  do_something(0);
}
</code>```

Typing it as a lambda and/or using a template makes it a little cleaner, but I still have to type something N times. And if N changes I have to change multiple lines of code. This is not elegant.

答:
The following compiles fine in both gcc and clang in C++17 mode. It uses some simple template metaprogramming to generate the sequence of callbacks.

#include <array>
#include <iostream>

using cb = void (*)();

template<int N>
inline auto fun()
{
    std::cout << "callback: " << N << '\n';
}

template<int N>
void init(cb * arr)
{
    arr[N] = &fun<N>;
    init<N-1>(arr);
}

template<>
void init<0>(cb * arr)
{
    arr[0] = &fun<0>;
}

template<int N>
struct callbacks
{
    callbacks()
    {
        init<N>(cbs.data());
    }

    std::array<cb, N> cbs;
};

int main()
{
    auto foo = callbacks<4>();
    for (auto x = 0; x < 4; ++x)
    {
        foo.cbs[x]();
    }
}
```

Body:
I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here).
I use C++17.

Here is what I have:

using Callback = void(*)();
auto constexpr N = 2;

const Callback callbacks[N] = {
 [](){ auto i = 0; std::cout<<"callback " << i << "\n";},
 [](){ auto i = 1; std::cout<<"callback " << i << "\n";}
};

callbacks[0]();
callbacks[N-1]();

Here is what I want:

const auto callbacks = generate_callbacks<N>();  // or generate_callbacks(N)
callbacks[i](); // cout<<"callback " << i << "\n";

I tried various ways, but I keep running into the problems with constant parameters even when they are from a constexpr function or variadic template.

If I try this:

Callback callbacks[N] = { };

for(int i=0;i<N;++i)
{
callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
}

for(int i=0;i<N;++i)
{
callbacks[i]();
}

I get the following error:

main.cpp:91:66: error: cannot convert ‘main()::’ to ‘Callback {aka void (*)()}’ in assignment
        callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};

If I make i static and leave out the capture it only uses the last value of i:

callback 2
callback 2

This is odd to me as capturing should be done at construction. Are the lambdas constructed after the loop exits?

As for the purpose. I want to apply this technique to generating interrupt handlers for microcontrollers. I can put the function pointers in the interrupt vector table directly. These functions have no parameters and I don't know a clean way to detect which interrupt source called the handler. I can write a handler for each interrupt, but I don't like repeating this code 6 times:

void handler0()
{
  do_something(0);
}

Typing it as a lambda and/or using a template makes it a little cleaner, but I still have to type something N times. And if N changes I have to change multiple lines of code. This is not elegant.


问:
how do i create a variable from the output of another in bash
Here's an example script that doesn't work the way I expect:

```<code>#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done
</code>```

I want the output would be:

```<code>hi

a

hi

b

hi

c
</code>```

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

答:
The following is the fix for your program. There are two things you got wrong:
The first is you don't need '$' when declaring variables.
The second is that calling eval will treat the content of myvar as a shell script. However you don't have "hi" defined anywhere as a command.</p>

```<code> for dynamic in a b c; do
     myvar=$dynamic

-    export $myvar="hi"
+    export myvar="hi"

-    echo $(eval "$myvar")
+    echo "$myvar"
     echo $dynamic
 done
</code>```

Body:
Here's an example script that doesn't work the way I expect:

#!/bin/bash
for dynamic in a b c; do
  myvar=$dynamic

  export $myvar="hi"

  echo $(eval "$myvar")
  echo $dynamic
done

I want the output would be:

hi

a

hi

b

hi

c

Any ideas?  I'm willing to stray away from this method, but I definitely want to be able to create a variable named from the output of an algorithm.  In this case it's just a for loop.

Body:
The following is the fix for your program. There are two things you got wrong:
The first is you don't need '$' when declaring variables.
The second is that calling eval will treat the content of myvar as a shell script. However you don't have "hi" defined anywhere as a command.

 for dynamic in a b c; do
     myvar=$dynamic

-    export $myvar="hi"
+    export myvar="hi"

-    echo $(eval "$myvar")
+    echo "$myvar"
     echo $dynamic
 done


问:
Missing CORS on the response header
Basically I'd like to know if it's up to the company(https://documenu.com/) to "fix" one of their endpoints or if it has something to do with my code.

I tried almost all of the other endpoints(https://documenu.com/docs) with the same code below and all of them worked fine except the one being discussed here.

The error message I get is:

Ensure CORS response header values are valid

A cross-origin resource sharing (CORS) request was blocked because of
invalid or missing response headers of the request or the associated
preflight request.

To fix this issue, ensure the response to the CORS request and/or the
associated preflight request are not missing headers and use valid
header values.

Note that if an opaque response is sufficient, the request's mode can
be set to no-cors to fetch the resource with CORS disabled; that way
CORS headers are not required but the response content is inaccessible
(opaque).

I've tried using through Node,Live-reload but nothing.

I read about CORS and from what I understood, it would be up to the company to add CORS to their responses' headers.

What do you guys think?

Thank you for the help

```<code>const api = apiKey;
const myHeaders = new Headers();

myHeaders.append('x-api-key', api);

const requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow',
  mode: 'cors',
};
const endpoint = 'https://api.documenu.com/v2/menuitems/search/geo?lat=40.688072&lon=-73.997385&distance=1&search=buffalo%20chicken';

fetch(`${endpoint}`, requestOptions)
  .then((res) => res.json())
  .then((data) => console.log(data));

</code>```

答:
Yes you are right, the company is the one to fix the issue, because they are opposed to sending the CORS header.

Using the API preview on their website, you are also right about all of the endpoints working but the one you mention.

Edit:

I have removed the link to the documentation because the domain is not active anymore.

Title: Missing CORS on the response header

Body:
Basically I'd like to know if it's up to the company(https://documenu.com/) to "fix" one of their endpoints or if it has something to do with my code.

I tried almost all of the other endpoints(https://documenu.com/docs) with the same code below and all of them worked fine except the one being discussed here.

The error message I get is:

Ensure CORS response header values are valid

A cross-origin resource sharing (CORS) request was blocked because of
invalid or missing response headers of the request or the associated
preflight request.

To fix this issue, ensure the response to the CORS request and/or the
associated preflight request are not missing headers and use valid
header values.

Note that if an opaque response is sufficient, the request's mode can
be set to no-cors to fetch the resource with CORS disabled; that way
CORS headers are not required but the response content is inaccessible
(opaque).

I've tried using through Node,Live-reload but nothing.

I read about CORS and from what I understood, it would be up to the company to add CORS to their responses' headers.

What do you guys think?

Thank you for the help

const api = apiKey;
const myHeaders = new Headers();

myHeaders.append('x-api-key', api);

const requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow',
  mode: 'cors',
};
const endpoint = 'https://api.documenu.com/v2/menuitems/search/geo?lat=40.688072&lon=-73.997385&distance=1&search=buffalo%20chicken';

fetch(`${endpoint}`, requestOptions)
  .then((res) => res.json())
  .then((data) => console.log(data));


问:
Using backslash (\) inside a String variable in java
I am not able to get the message value in the desired format.

```<code>String url = "sample"
String message ="/test{\"url\":"' + url + '\"}
</code>```

The desired value of message is "/test{\"url\":\"sample\"}"

Any idea on this?

答:
Try the following syntax:

```<code>String url = "sample";
String message ="/test{\\\"url\\\":\"" + url + "\\\"}";
</code>```

Please note that back-slash \ and double-quote " are specialized character and hence they need to be escaped using back-slash \.
Hence, \\ is used for \ and \" is used for " in String literal.

Output:

```<code>/test{\"url\":"sample\"}
</code>```

Body:
I am not able to get the message value in the desired format.

String url = "sample"
String message ="/test{\"url\":"' + url + '\"}

The desired value of message is "/test{\"url\":\"sample\"}"

Any idea on this?

Body:
Try the following syntax:

String url = "sample";
String message ="/test{\\\"url\\\":\"" + url + "\\\"}";

Please note that back-slash \ and double-quote " are specialized character and hence they need to be escaped using back-slash \.
Hence, \\ is used for \ and \" is used for " in String literal.

Output:

/test{\"url\":"sample\"}


答:
Try with this:

```<code>    String url = "sample";
    String message ="/test{\\\"url\\\":\""+url+"\\\"}";
</code>```

Or you can use String.format:

```<code>    String url = "sample";
    String message = String.format("/test{\\\"url\\\":\"%s\\\"}",url);
</code>```

Title: Using backslash (\) inside a String variable in java

Body:
Try with this:

    String url = "sample";
    String message ="/test{\\\"url\\\":\""+url+"\\\"}";

Or you can use String.format:

    String url = "sample";
    String message = String.format("/test{\\\"url\\\":\"%s\\\"}",url);


答:
After several tried, I found the solution:</p>
```<code>    StringBuilder sb=new StringBuilder();
    sb.append("\"/test{");
    sb.append("\"\\");
    sb.append("\"");
    sb.append("url\\\"");
    sb.append(":");
    sb.append("\\\"");
    sb.append(url);
    sb.append("\"\\}\"");
    System.out.println(sb.toString());
</code>```

Body:
After several tried, I found the solution:

    StringBuilder sb=new StringBuilder();
    sb.append("\"/test{");
    sb.append("\"\\");
    sb.append("\"");
    sb.append("url\\\"");
    sb.append(":");
    sb.append("\\\"");
    sb.append(url);
    sb.append("\"\\}\"");
    System.out.println(sb.toString());


问:
POSTMAN set variable within a XML request Body
I'm trying to make SOAP request with xml using postman, but some of the parameters I want to send must be environment variables I have already stored in other request.

The request Body is something like that:

```<code><soapenv:Envelope xmlns:soapenv="blablabla" xmlns:XXX="http:blablabla/">
    <soapenv:Header/>
    <soapenv:Body>
        <XXX:Function>
            <CODE>878734ijHgs</CODE>
            <DISTRIBUTOR>myDistributor</DISTRIBUTOR>
            <MAGICNUMBER>21</MAGICNUMBER>
        </XXX:Function>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

The point is that as MAGICNUMBER I would like to send a value that I have previously stored as a environment variable, but the syntax {{variable}} doesn't work with XML

Please suggest.

答: I've got the same issue for a few minutes. In my case I added a new environment variable but I didn't save the environment. It was still opened in a tab nearby with orange circle at the right side. After saving the environment by pressing [Ctrl+S] on environment tab, variable started to resolve properly.

Body:
I'm trying to make SOAP request with xml using postman, but some of the parameters I want to send must be environment variables I have already stored in other request.

The request Body is something like that:

<soapenv:Envelope xmlns:soapenv="blablabla" xmlns:XXX="http:blablabla/">
    <soapenv:Header/>
    <soapenv:Body>
        <XXX:Function>
            878734ijHgs
            <DISTRIBUTOR>myDistributor</DISTRIBUTOR>
            <MAGICNUMBER>21</MAGICNUMBER>
        </XXX:Function>
    </soapenv:Body>
</soapenv:Envelope>

The point is that as MAGICNUMBER I would like to send a value that I have previously stored as a environment variable, but the syntax {{variable}} doesn't work with XML

Please suggest.


问:
JSON Tree structure with the key Folder on each level
I will make requests to an API that have a folder structure.

Some request may respons with one level, others with 20 levels but I don't want this ugly structure.

Is there any good explanation for doing this recursive without knowing level depth?

```<code>for parent_folder in server_folders['folders']:
    print(parent_folder['name'] + ' (PARENT)')

    for children in parent_folder['folders']:
        print("- " + children['name'])

        for sub_children in children['folders']:
            print("- - " + sub_children['name'])

            for sub_sub_children in sub_children['folders']:
                print("- - - " + sub_sub_children['name'])

                for sub_sub_sub_children in sub_sub_children['folders']:
                    print("- - - " + sub_sub_sub_children['name'])
</code>```

答:
Thanks Asger, smart!

I did end up with this rewrite of you excellent job!

```<code>def nested_list_print(init_folder, init_depth):
for i in init_folder['folders']:
    print('- '*(init_depth) + i['name'])
    if 'folders' in i:
        nested_list_print(i, init_depth+1)

nested_list_print(jsonfeed_w_folders, 0)
</code>```

Body:
I will make requests to an API that have a folder structure.

Some request may respons with one level, others with 20 levels but I don't want this ugly structure.

Is there any good explanation for doing this recursive without knowing level depth?

for parent_folder in server_folders['folders']:
    print(parent_folder['name'] + ' (PARENT)')

    for children in parent_folder['folders']:
        print("- " + children['name'])

        for sub_children in children['folders']:
            print("- - " + sub_children['name'])

            for sub_sub_children in sub_children['folders']:
                print("- - - " + sub_sub_children['name'])

                for sub_sub_sub_children in sub_sub_children['folders']:
                    print("- - - " + sub_sub_sub_children['name'])

Body:
Thanks Asger, smart!

I did end up with this rewrite of you excellent job!

def nested_list_print(init_folder, init_depth):
for i in init_folder['folders']:
    print('- '*(init_depth) + i['name'])
    if 'folders' in i:
        nested_list_print(i, init_depth+1)

nested_list_print(jsonfeed_w_folders, 0)


问:
Sorting heterogeneous elements in arraylist
How to sort heterogeneous elements in a array-list? For example,

```<code>ArrayList l1 = new ArrayList();
l1.add(1);
l1.add("hi");
l1.add(1.0f);
</code>```

Now how to sort this array-list?``

答:
It depends on how you want them sorted. You could split the list up into new ArrayLists with a defined type, sort each one of them then concatenate them?

Something like: (pseudocode)

```<code>ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Integer> stringList = new ArrayList<Integer>();
// ...etc

for (Object o : list) {
  if (o.getClass().equals(Integer.TYPE))
    intList.add(o);
  else if (o.getClass().equals(String.class))
    stringList.add(o);
  // ...etc
}

sort(intList);
sort(stringList);
// ...etc

concatenate(intList, stringList, ...);
</code>```

That's what I'd think you do anyway.

Body:
How to sort heterogeneous elements in a array-list? For example,

ArrayList l1 = new ArrayList();
l1.add(1);
l1.add("hi");
l1.add(1.0f);

Now how to sort this array-list?``

Body:
It depends on how you want them sorted. You could split the list up into new ArrayLists with a defined type, sort each one of them then concatenate them?

Something like: (pseudocode)

ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<Integer> stringList = new ArrayList<Integer>();
// ...etc

for (Object o : list) {
  if (o.getClass().equals(Integer.TYPE))
    intList.add(o);
  else if (o.getClass().equals(String.class))
    stringList.add(o);
  // ...etc
}

sort(intList);
sort(stringList);
// ...etc

concatenate(intList, stringList, ...);

That's what I'd think you do anyway.


问:
Verifying Stripe webhook in SvelteKit endpoint: how to get the raw body of a RequestEvent?
Similar to this question, using a more recent version of SvelteKit.

Context: SvelteKit PR #3384 started passing standard Request objects to endpoints and removed rawBody.

The question linked above has a good answer for how to use rawBody to call Stripe's constructEvent to verify the signature of an incoming webhook request, but now that the unmodified body is no longer exposed (as far as I can tell), I'm left wondering how to update my webhook handler.

I've tried calling constructEvent with the results of request.text(), request.json(), request.arrayBuffer() (converted to a string), request.blob().text(), and the plain request.body converted to a string, yet none of them worked. It always throws the same error:

```<code>No signatures found matching the expected signature for payload.
Are you passing the raw request body you received from Stripe?
https://github.com/stripe/stripe-node#webhook-signing
</code>```

答:
So I've looked into the node-fetch source code because that's what svelte-kit uses to shim the dev server with and all environments that don't support Fetch and there is a method that the standard Request class doesn't have and that's Request.buffer(). With this method I was able to solve that issue. This will only be available in node or serverless environments that don't support fetch natively (nearly every environment except cloudflare).

```<code>export async function post({ request }: RequestEvent) {
    try {
        const body = await request.buffer();
        const sig = request.headers.get('stripe-signature') as string;
        const e = stripe.webhooks.constructEvent(body, sig, secret);
        console.log(e.type);
    } catch (_e) {
        console.error(_e);
    }
}
</code>```

Result:

```<code>charge.succeeded
payment_intent.succeeded
payment_intent.created
</code>```

Body:
Similar to this question, using a more recent version of SvelteKit.

Context: SvelteKit PR #3384 started passing standard Request objects to endpoints and removed rawBody.

The question linked above has a good answer for how to use rawBody to call Stripe's constructEvent to verify the signature of an incoming webhook request, but now that the unmodified body is no longer exposed (as far as I can tell), I'm left wondering how to update my webhook handler.

I've tried calling constructEvent with the results of request.text(), request.json(), request.arrayBuffer() (converted to a string), request.blob().text(), and the plain request.body converted to a string, yet none of them worked. It always throws the same error:

No signatures found matching the expected signature for payload.
Are you passing the raw request body you received from Stripe?
https://github.com/stripe/stripe-node#webhook-signing

Body:
So I've looked into the node-fetch source code because that's what svelte-kit uses to shim the dev server with and all environments that don't support Fetch and there is a method that the standard Request class doesn't have and that's Request.buffer(). With this method I was able to solve that issue. This will only be available in node or serverless environments that don't support fetch natively (nearly every environment except cloudflare).

export async function post({ request }: RequestEvent) {
    try {
        const body = await request.buffer();
        const sig = request.headers.get('stripe-signature') as string;
        const e = stripe.webhooks.constructEvent(body, sig, secret);
        console.log(e.type);
    } catch (_e) {
        console.error(_e);
    }
}

Result:

charge.succeeded
payment_intent.succeeded
payment_intent.created


问:
Axios Request Aborted
I have an axios post request which gets triggered when we click on button. But as soon as button is clicked it shows this error and page reloads

The function on which the request is getting triggered

```<code>const handleForm = async (e) => {
//Check username is unique
e.preventDefault();
const oldUserName = await doesUserNameExist(userName);
if (oldUserName) {
  activeUser.displayName = userName;
  const imgUrl = await uploadPhoto(activeUser?.displayName, profilePicture);
  const userFormData = {
    userName,
    bio,
    gender,
    age,
    uid: activeUser.uid,
    emailAddress: activeUser.email,
    accountCreatedOn: serverTimestamp(),
    lastSeen: serverTimestamp(),
    following: [''],
    followers: [''],
    role: 'user',
    status: '',
    photoURL: imgUrl ? imgUrl : activeUser?.photoURL,
  };

  //  await addUser(userFormData);
  const nodeData = {
    id: activeUser.uid,
    emailAddress: activeUser.email,
    userName,
  };
  await axios.post('path_to_api/api/user', nodeData, {
    headers: nodeData,
  });
}
</code>```

Please Help. Thanks in advance!!

答:
Try this :</p>
```<code> await axios.post('path_to_api/api/user', nodeData);
</code>```

Title: Axios Request Aborted

Body:
I have an axios post request which gets triggered when we click on button. But as soon as button is clicked it shows this error and page reloads

The function on which the request is getting triggered

const handleForm = async (e) => {
//Check username is unique
e.preventDefault();
const oldUserName = await doesUserNameExist(userName);
if (oldUserName) {
  activeUser.displayName = userName;
  const imgUrl = await uploadPhoto(activeUser?.displayName, profilePicture);
  const userFormData = {
    userName,
    bio,
    gender,
    age,
    uid: activeUser.uid,
    emailAddress: activeUser.email,
    accountCreatedOn: serverTimestamp(),
    lastSeen: serverTimestamp(),
    following: [''],
    followers: [''],
    role: 'user',
    status: '',
    photoURL: imgUrl ? imgUrl : activeUser?.photoURL,
  };

  //  await addUser(userFormData);
  const nodeData = {
    id: activeUser.uid,
    emailAddress: activeUser.email,
    userName,
  };
  await axios.post('path_to_api/api/user', nodeData, {
    headers: nodeData,
  });
}

Please Help. Thanks in advance!!

Body:
Try this :

 await axios.post('path_to_api/api/user', nodeData);


问:
poster image not displaying with add_movie() in python-pptx
I am trying to insert some sound files into a presentation, and the sound file seems to save fine, but the display image is always the default play button logo. Is there something wrong with my code, or is it another issue. I am currently working in a linux environment, if that makes any difference. I have tried with both mp4 and mp3 and the image issue is the same. The small play bar also seems not to appear although the sound file is in the presentation.

    from pptx import Presentation
    from pptx.util import Inches

    prs = Presentation()
    title_slide_layout = prs.slide_layouts[0]
    slide = prs.slides.add_slide(title_slide_layout)

    prs.slides[0].shapes.add_movie("sample2.mp3",
                               left = Inches(1), top = Inches(1), width = Inches(1), height = Inches(1),
                               poster_frame_image = "cat.jpeg"
                               )

    prs.save('sound_image.pptx')
```

答:
You can easily add any sound files to presentations and set poster images for them by using Aspose.Slides for Python as shown below:

import aspose.slides as slides

presentation_path = "example.pptx"
audio_path = "sample2.mp3"
image_path = "cat.jpeg"

with slides.Presentation() as presentation:

    slide = presentation.slides[0]

    # Add an audio frame to the slide with a specified position and size.
    with open(audio_path, 'rb') as audio_stream:
        audio_frame = slide.shapes.add_audio_frame_embedded(150, 100, 50, 50, audio_stream)

    # Add the image to presentation resources.
    with open(image_path, 'rb') as image_stream:
        audio_image = presentation.images.add_image(image_stream)

    # Set the image as the audio poster.
    audio_frame.picture_format.picture.image = audio_image

    presentation.save(presentation_path, slides.export.SaveFormat.PPTX)
```

I work as a Support Developer at Aspose.

Body:
You can easily add any sound files to presentations and set poster images for them by using Aspose.Slides for Python as shown below:

import aspose.slides as slides

presentation_path = "example.pptx"
audio_path = "sample2.mp3"
image_path = "cat.jpeg"

with slides.Presentation() as presentation:

    slide = presentation.slides[0]

    # Add an audio frame to the slide with a specified position and size.
    with open(audio_path, 'rb') as audio_stream:
        audio_frame = slide.shapes.add_audio_frame_embedded(150, 100, 50, 50, audio_stream)

    # Add the image to presentation resources.
    with open(image_path, 'rb') as image_stream:
        audio_image = presentation.images.add_image(image_stream)

    # Set the image as the audio poster.
    audio_frame.picture_format.picture.image = audio_image

    presentation.save(presentation_path, slides.export.SaveFormat.PPTX)

I work as a Support Developer at Aspose.


问:
SharedPreferences behaviour on Update/Uninstall
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

```<code>public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
</code>```

答:
If you get don't set dontShowagin you will get false by default .So you want to show dialog and next time not.So just change the value in preference to true so that next time it works.Also you are incrementing the counter without actually incrementing it.Use +1 with the previous one.</p>

```<code>SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
            if (prefs.getBoolean("dontshowagain", false)) {
                return;
            }

            SharedPreferences.Editor editor = prefs.edit();

            // Increment launch counter

            editor.putBoolean("dontShowagain",true);
            launch_count = prefs.getLong("launch_count", 0)+1;
            editor.putLong("launch_count", launch_count);
</code>```

Body:
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

Body:
If you get don't set dontShowagin you will get false by default .So you want to show dialog and next time not.So just change the value in preference to true so that next time it works.Also you are incrementing the counter without actually incrementing it.Use +1 with the previous one.

SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
            if (prefs.getBoolean("dontshowagain", false)) {
                return;
            }

            SharedPreferences.Editor editor = prefs.edit();

            // Increment launch counter

            editor.putBoolean("dontShowagain",true);
            launch_count = prefs.getLong("launch_count", 0)+1;
            editor.putLong("launch_count", launch_count);


Title: Join DataFrames based on multiple columns

Body:
I want to join two tables. The one is a DataTable DT_1 and the other a DataFrame DF_2. The columns name and value in DT_1 are related to the rows and columns of the DF_2. The output would be the DT_1 with a new column expr consists of the corresponding values sourced from the DF_2.

View(DT_1)
CHR        POS           ID         name   value
<dbl>     <chr>        <chr>       <chr>   <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1
 2     1 31439_T_A ENSG00000232325 indv2     1
 3     1 31439_T_A ENSG00000232325 indv3     2
 4     1 31504_G_A ENSG00000242474 indv1     2
 5     1 31504_G_A ENSG00000242474 indv2     1
 6     1 31504_G_A ENSG00000242474 indv3     1
 7     1 34713_A_C ENSG00000242474 indv1     1
 8     1 34713_A_C ENSG00000242474 indv2     0
 9     1 34713_A_C ENSG00000242474 indv3     1
10     1 34918_C_T ENSG00000242474 indv1     1
11     1 34918_C_T ENSG00000242474 indv2     0
12     1 34918_C_T ENSG00000242474 indv3     1
13     1 35119_G_A ENSG00000239715 indv1     0
14     1 35119_G_A ENSG00000239715 indv2     0
15     1 35119_G_A ENSG00000239715 indv3     1

view(DF_2)
name    ENSG00000232325  ENSG00000242474  ENSG00000239715
indv1       0.1                0.4              0.22
indv2       0.3              -0.003            0.0001
indv3      -0.02               0.1              0.1

The desired output:

> OUTPUT
CHR       POS            ID         name   value  expr
<dbl>    <chr>          <chr>      <chr>   <dbl> <dbl>
 1     1 31439_T_A ENSG00000232325 indv1     1    0.1
 2     1 31439_T_A ENSG00000232325 indv2     1    0.3
 3     1 31439_T_A ENSG00000232325 indv3     2   -0.02
 4     1 31504_G_A ENSG00000242474 indv1     2    0.4
 5     1 31504_G_A ENSG00000242474 indv2     1   -0.003
 6     1 31504_G_A ENSG00000242474 indv3     1    0.1
 7     1 34713_A_C ENSG00000242474 indv1     1    0.4
 8     1 34713_A_C ENSG00000242474 indv2     0   -0.003
 9     1 34713_A_C ENSG00000242474 indv3     1    0.1
10     1 34918_C_T ENSG00000242474 indv1     1    0.4
11     1 34918_C_T ENSG00000242474 indv2     0   -0.003
12     1 34918_C_T ENSG00000242474 indv3     1    0.1
13     1 35119_G_A ENSG00000239715 indv1     0    0.22
14     1 35119_G_A ENSG00000239715 indv2     0   0.0001
15     1 35119_G_A ENSG00000239715 indv3     1    0.1

thanks!

Body:
data.table approach

library(data.table)
setDT(df1)[melt(setDT(df2), id="name",value.name = "expr"), on=.(name, ID=variable)]

OUTPUT

    CHR         POS              ID  name value    expr
 1:   1 1 31439_T_A ENSG00000232325 indv1     1  0.1000
 2:   2 1 31439_T_A ENSG00000232325 indv2     1  0.3000
 3:   3 1 31439_T_A ENSG00000232325 indv3     2 -0.0200
 4:   4 1 31504_G_A ENSG00000242474 indv1     2  0.4000
 5:   7 1 34713_A_C ENSG00000242474 indv1     1  0.4000
 6:  10 1 34918_C_T ENSG00000242474 indv1     1  0.4000
 7:   5 1 31504_G_A ENSG00000242474 indv2     1 -0.0030
 8:   8 1 34713_A_C ENSG00000242474 indv2     0 -0.0030
 9:  11 1 34918_C_T ENSG00000242474 indv2     0 -0.0030
10:   6 1 31504_G_A ENSG00000242474 indv3     1  0.1000
11:   9 1 34713_A_C ENSG00000242474 indv3     1  0.1000
12:  12 1 34918_C_T ENSG00000242474 indv3     1  0.1000
13:  13 1 35119_G_A ENSG00000239715 indv1     0  0.2200
14:  14 1 35119_G_A ENSG00000239715 indv2     0  0.0001
15:  15 1 35119_G_A ENSG00000239715 indv3     1  0.1000


问:
How do can I use the setvalue() in a foreach() loop?[Google sheet Script]
It's my first post and I am a newbee in google sheets script programing.

I want to my script when I run it, to go first through a list of clients(row[0]). when the client has been found, test for the row[2] if it is a "yes" or "no" string object and when it is a "yes" option, rewrite it as a "no".

another question that i have is how can I know which ligne (row) i am testing when i am using the foreach function.

```<code>function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  dataIS.forEach(function(row)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= setValue("oui");
      }
    }
  });
}
</code>```

PS : the script doesn't give me an error to understand where did I messed up.

thank you

答:
Assuming you call this function only once the use of setValue() is okay.  If you are calling this many times you should investigate using setValues() instead.</p>
```<code>function cleanpassagepage(NomClient) {
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  var i = 0;
  for( i=0; i<dataIS.length; i++ ) {
    if( dataIS[i][0] === NomClient ) {
      if( dataIS[i][2] === "non" ) {
        passageclientsheet.getRange(i+1,3).setValue("oui");
      }
      return;
    }
  }
}
</code>```

Body:
It's my first post and I am a newbee in google sheets script programing.

I want to my script when I run it, to go first through a list of clients(row[0]). when the client has been found, test for the row[2] if it is a "yes" or "no" string object and when it is a "yes" option, rewrite it as a "no".

another question that i have is how can I know which ligne (row) i am testing when i am using the foreach function.

function cleanpassagepage(NomClient)
{
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  dataIS.forEach(function(row)
  {
    if (row[0]==NomClient)
    {
      if(row[2]=="non")
      {
        row[2]= setValue("oui");
      }
    }
  });
}

PS : the script doesn't give me an error to understand where did I messed up.

thank you

Body:
Assuming you call this function only once the use of setValue() is okay.  If you are calling this many times you should investigate using setValues() instead.

function cleanpassagepage(NomClient) {
  const passageclientsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("relevé chez client");
  const numlastrowIS = passageclientsheet.getLastRow();
  const dataIS = passageclientsheet.getRange(2,1,numlastrowIS,3).getValues();
  var i = 0;
  for( i=0; i<dataIS.length; i++ ) {
    if( dataIS[i][0] === NomClient ) {
      if( dataIS[i][2] === "non" ) {
        passageclientsheet.getRange(i+1,3).setValue("oui");
      }
      return;
    }
  }
}


问:
How do I separate an array depending on values in a column?
Say I have an Mx4 array A where the values in the first column are a number 1 to 12. Now I want to gather the rest of the columns in 12 separate Mx3 arrays depending on which number is in column 1.
How would I go about doing that?</p>

答:
You can use unique and splitapply as follows. The result is a cell array of arrays.

```<code>M = [2 11 41 51;
     1 10 20 30;
     1 62 83 22;
     4 73 53 53;
     2 84 94 14]; % example data
L = 5; % Group labels are 1:L (L=12 in your case)
[u,~,w] = unique(M(:,1));
result = cell(L,1);
result(u) = splitapply(@(x){x}, M(:,2:end), w);
</code>```

This gives

```<code>>> celldisp(result)
result{1} =
    10    20    30
    62    83    22
result{2} =
    11    41    51
    84    94    14
result{3} =
     []
result{4} =
    73    53    53
result{5} =
     []
</code>```

Body:
You can use unique and splitapply as follows. The result is a cell array of arrays.

M = [2 11 41 51;
     1 10 20 30;
     1 62 83 22;
     4 73 53 53;
     2 84 94 14]; % example data
L = 5; % Group labels are 1:L (L=12 in your case)
[u,~,w] = unique(M(:,1));
result = cell(L,1);
result(u) = splitapply(@(x){x}, M(:,2:end), w);

This gives

>> celldisp(result)
result{1} =
    10    20    30
    62    83    22
result{2} =
    11    41    51
    84    94    14
result{3} =
     []
result{4} =
    73    53    53
result{5} =
     []


问:
How to load images and cache in ready function
I have developed LCD display like widget, I have 10 digits images and for every digit on display ( max 6 ) I have  and on click I change picture on div ( jquery attr('src','url'). My question is how to load all this 10 images in ready function ? I need to avoid flickering if connection is slow ( It flicker first time ) ?</p>

答:
The best way would be to create a "sprite".

A sprite is a single image that has all those digits stacked, and you'll then apply different background-position's according to which digit you want.

You can use spriteme.org to help you with creating the sprites.

Here's one I've made some time ago for one of my projects:


问:
Hiding a button in Javascript
In my latest program, there is a button that displays some input popup boxes when clicked. After these boxes go away, how do I hide the button?</p>

答:
function popAlert(){
        alert("Button will be hidden on click");
        document.getElementById("getMessage").style.visibility="hidden";

    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   h1 {
            color: #0000ff;
        }</code>```

KIAAT

    Hiding a button in Javascript after click

<input type="button" id="getMessage"  value="Hide Button OnClick" onclick="popAlert()"/>```

Title: Hiding a button in Javascript

Body:
function popAlert(){
        alert("Button will be hidden on click");
        document.getElementById("getMessage").style.visibility="hidden";

    }

   h1 {
            color: #0000ff;
        }

<h1>KIAAT</h1>
    <b>Hiding a button in Javascript after click</b>
    <br><br>
<input type="button" id="getMessage"  value="Hide Button OnClick" onclick="popAlert()"/>


问:
How to remove one value from a key in localstorage that has many values?
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

```<code>data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
</code>```

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

```<code>const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }
</code>```

and to remove the value from localstorage I am using this function.

```<code>function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }
</code>```

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

```<code>array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]
</code>```

But if I select another item to be added to localstorage, then the previous item gets removed.

```<code>UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]
</code>```

I hope this makes sense, I tried to add detail to it as best as possible.

答: The easiest way is to just overwrite the item in localStorage. Once you remove the item from the favs array, call localStorage.setItem("name", JSON.stringify(favs)); again and you're done.

Body:
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }

and to remove the value from localstorage I am using this function.

function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]

But if I select another item to be added to localstorage, then the previous item gets removed.

UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]

I hope this makes sense, I tried to add detail to it as best as possible.


答: jQuery preload will do. Of course a sprite (see @Joseph Silber's answer) is a "more professional" option, but will require a bit more work.</p>

Title: How to load images and cache in ready function

Body: I have developed LCD display like widget, I have 10 digits images and for every digit on display ( max 6 ) I have  and on click I change picture on div ( jquery attr('src','url'). My question is how to load all this 10 images in ready function ? I need to avoid flickering if connection is slow ( It flicker first time ) ?


问:
How a Web API knows the client Culture/Language
We have a new GET service endpoint which expects DateTime and Decimal data, among other parameters.
For simplicity, this represent our request without any fix yet:

```<code>        app.MapGet("saleEvent", async (string amount, string date) =>
        {
            long.TryParse(amount, out var requestAmount);  //Use *culture* parameter
            DateTime.TryParse(date, out var requestDate);  //Use *culture* parameter
            await DoSomething(requestAmount, requestDate);
        });
</code>```

We are receiving the data as strings, because a couple of our customers are based in different countries, with different formats, according to their culture.

We want to ask the customer to send their culture somewhere in the request, in order to be able to properly process the received data.

Well, here we have found many alternatives for our customers to include in their request, but I'm not sure which is the best or proper fit to do this:

accept-language header: Seems to indicate which culture they expect in the response, nothing to do with the parameters. Not our case as our response is just 200 (OK).

content-language header: Seems to indicate the language of the body. As we are not receiving a body, but a query string, I doubt we should use it.

One additional parameter in the query, like:

```<code>        app.MapGet("saleEvent", async (string date, string amount, string culture)
</code>```

A custom header for the same purpose.

Other recommendation was to receive the Date as UTC+0, but I think the customer should not be worried with removing the offset thing.

Is there any standar way to do this?

答:
We have a new GET service endpoint which expects DateTime and Decimal data,

No, you don't. Just correct your endpoint:

```<code>app.MapGet("saleEvent", async (decimal amount, DateTime date) =>
</code>```

There you go. Since this endpoint is called by another computer program, it is that programs' job to make sure their user input is correctly transferred into those datatypes. Who knows if they even have user input. That program might read it from a file or database, too.

C# is a strongly typed language. Don't transform it into a stringly typed language by using coding anti-patterns.

Body:
We have a new GET service endpoint which expects DateTime and Decimal data, among other parameters.
For simplicity, this represent our request without any fix yet:

        app.MapGet("saleEvent", async (string amount, string date) =>
        {
            long.TryParse(amount, out var requestAmount);  //Use *culture* parameter
            DateTime.TryParse(date, out var requestDate);  //Use *culture* parameter
            await DoSomething(requestAmount, requestDate);
        });

We are receiving the data as strings, because a couple of our customers are based in different countries, with different formats, according to their culture.

We want to ask the customer to send their culture somewhere in the request, in order to be able to properly process the received data.

Well, here we have found many alternatives for our customers to include in their request, but I'm not sure which is the best or proper fit to do this:

accept-language header: Seems to indicate which culture they expect in the response, nothing to do with the parameters. Not our case as our response is just 200 (OK).

content-language header: Seems to indicate the language of the body. As we are not receiving a body, but a query string, I doubt we should use it.

One additional parameter in the query, like:

        app.MapGet("saleEvent", async (string date, string amount, string culture)

A custom header for the same purpose.

Other recommendation was to receive the Date as UTC+0, but I think the customer should not be worried with removing the offset thing.

Is there any standar way to do this?

Body:
We have a new GET service endpoint which expects DateTime and Decimal data,

No, you don't. Just correct your endpoint:

app.MapGet("saleEvent", async (decimal amount, DateTime date) =>

There you go. Since this endpoint is called by another computer program, it is that programs' job to make sure their user input is correctly transferred into those datatypes. Who knows if they even have user input. That program might read it from a file or database, too.

C# is a strongly typed language. Don't transform it into a stringly typed language by using coding anti-patterns.


问:
Can't wrap a Menu.Item with Link
I'm currently using a Menu for my main header navigation, with Menu.Item components for the individual menu items.

At the moment, the code looks like so:

<Menu>
    <Menu.Item>

            <Link href="/login">
                Login
            </Link>

    </Menu.Item>
    <Menu.Item>

            <Link href="/register">
                Register
            </Link>

    </Menu.Item>
</Menu>
```

<p>Which makes the <code>Login</code> and <code>Register</code> spans clickable, but not the menu items themselves. When trying to move the <code>Link</code> and <code>a</code> tags upwards to include the entire <code>Menu.Item</code> -</p>

<pre class="lang-js prettyprint-override"><code><Menu>
    <Link href="/login">
        <a>
            <MenuItem>
                <span className="nav-text">
                    Login
                </span>
            </MenuItem>
        </a>
    </Link>
    <Link href="/register">
        <a>
            <MenuItem>
                <span className="nav-text">
                    Register
                </span>
            </MenuItem>
        </a>
    </Link>
</Menu>
</code>```

The entire menu gets hidden and replaced with ···:

I'm not sure how to fix this and make the menu render correctly with the menu items clickable, and so I'd love to get some help with this.

答:
If you're using React than you can wrap the Menu.Item Component around the Link tag.</p>
```<code>import {Link} from "react-router-dom";
...
  <Link to="#">
    <Menu.Item>Your Content</Menu.Item>
  </Link>
</code>```

Title: Can't wrap a Menu.Item with Link

Body:
I'm currently using a Menu for my main header navigation, with Menu.Item components for the individual menu items.

At the moment, the code looks like so:

<Menu>
    <Menu.Item>

            <Link href="/login">
                Login
            </Link>

    </Menu.Item>
    <Menu.Item>

            <Link href="/register">
                Register
            </Link>

    </Menu.Item>
</Menu>

Which makes the Login and Register spans clickable, but not the menu items themselves. When trying to move the Link and a tags upwards to include the entire Menu.Item -

<Menu>
    <Link href="/login">

            <MenuItem>

                    Login

            </MenuItem>

    </Link>
    <Link href="/register">

            <MenuItem>

                    Register

            </MenuItem>

    </Link>
</Menu>

The entire menu gets hidden and replaced with ···:

I'm not sure how to fix this and make the menu render correctly with the menu items clickable, and so I'd love to get some help with this.

Body:
If you're using React than you can wrap the Menu.Item Component around the Link tag.

import {Link} from "react-router-dom";
...
  <Link to="#">
    <Menu.Item>Your Content</Menu.Item>
  </Link>