问:
Disable android home button without onCreate being called multiple times
Before beginning I want to state that I know disabling the home button is typically not a good idea (or generally possible). For the application I am working on though it is 100% necessary.  This app will not be deployed out in the wild and moreover will be the primary/"only" app in use on the device (by design).  Without giving more information I hope that this will be sufficient to address the "this is a really bad idea", "why would you want to do that", "you should use a different technology", etc points/questions.

That said, disabling the home button is not something that you can really do in android but I can somewhat emulate the desired behavior with the following code

```<code>private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    mTextView = binding.textView;
    mTextView.setText("Start");
}

@Override
public void onPause()
{
    super.onPause();
    mTextView.setText("pause called");
}
</code>```

and xml code (with app/package name removed)

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="....">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.REORDER_TASKS" />
    <uses-feature android:name="android.hardware.type.watch" />

    <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@android:style/Theme.DeviceDefault">
        <uses-library
            android:name="com.google.android.wearable"
            android:required="true" />

        <!--
              Set to true if your app is Standalone, that is, it does not require the handheld
               app to run.
        -->
        <meta-data
           android:name="com.google.android.wearable.standalone"
           android:value="true" />

       <activity
           android:name=".MainActivity"
           android:exported="true"
           android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.HOME" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

This code works completely fine with one exception, the first time the home button is pushed onCreate is called a second time after the app is created.  From a UI perspective I will see the mTextView show "Start" until the home button is pressed at which time it goes to "pause" (because onPause was called) followed immediately by "Start again (indicating that onCreate was called a second time).  Further pressing the home button does nothing (as desired).

Is there a way to prevent onCreate being called a second time or another way to emulate disabling the home button that won't result in the UI being reloaded/changed (I could save the state and then load the state after the home button is pressed but the UI will still be reloaded; the screen will go black for a second or two which I don't want)?

I don't think it makes that much of a difference, but I am using the API 30: Android 11.0 (R) sdk for deployment on a Samsung Galaxy Watch4 classic. Also as a final point, I don't want to root the device (which would solve this issue).

答:
"you should use a different technology"

Probably yes. If this were a traditional form factor, you might look into things like kiosk mode or custom firmware. Or, in your case, since this is Wear OS, perhaps you could implement a watchface.

Is there a way to prevent onCreate being called a second time

Presumably, a second instance of your activity is being created. If so, and assuming that this is a single-activity app (as your manifest indicates), try android:launchMode="singleInstance", or possibly singleTask.

I am using the API 30: Android 11.0 (R) sdk for deployment on a Samsung Galaxy Watch4 classic

I would not assume that your app will be able to take over HOME on Wear OS indefinitely. Frankly, I am surprised that it works now.

Body:
Before beginning I want to state that I know disabling the home button is typically not a good idea (or generally possible). For the application I am working on though it is 100% necessary.  This app will not be deployed out in the wild and moreover will be the primary/"only" app in use on the device (by design).  Without giving more information I hope that this will be sufficient to address the "this is a really bad idea", "why would you want to do that", "you should use a different technology", etc points/questions.

That said, disabling the home button is not something that you can really do in android but I can somewhat emulate the desired behavior with the following code

private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    mTextView = binding.textView;
    mTextView.setText("Start");
}

@Override
public void onPause()
{
    super.onPause();
    mTextView.setText("pause called");
}

and xml code (with app/package name removed)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="....">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.REORDER_TASKS" />
    <uses-feature android:name="android.hardware.type.watch" />

    <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@android:style/Theme.DeviceDefault">
        <uses-library
            android:name="com.google.android.wearable"
            android:required="true" />

        <meta-data
           android:name="com.google.android.wearable.standalone"
           android:value="true" />

       <activity
           android:name=".MainActivity"
           android:exported="true"
           android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.HOME" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
        </activity>
    </application>
</manifest>

This code works completely fine with one exception, the first time the home button is pushed onCreate is called a second time after the app is created.  From a UI perspective I will see the mTextView show "Start" until the home button is pressed at which time it goes to "pause" (because onPause was called) followed immediately by "Start again (indicating that onCreate was called a second time).  Further pressing the home button does nothing (as desired).

Is there a way to prevent onCreate being called a second time or another way to emulate disabling the home button that won't result in the UI being reloaded/changed (I could save the state and then load the state after the home button is pressed but the UI will still be reloaded; the screen will go black for a second or two which I don't want)?

I don't think it makes that much of a difference, but I am using the API 30: Android 11.0 (R) sdk for deployment on a Samsung Galaxy Watch4 classic. Also as a final point, I don't want to root the device (which would solve this issue).


来源: stackexchange

问:
Keeping forward slashes in cookie PHP
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

```<code>$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);
</code>```

Any help would be appreciated, I am completely lost.

答:
I don't know where your login page is found, but if Deployment is a subdirectory (so one level beneath the main folder) you should add a forward slash infront of it, like so:

```<code>$url_name = "/Deployment/deployment.php";
setcookie("url", $url_name);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Keeping forward slashes in cookie PHP

Body:
I am building a log in page.  Right now, there is an expiration on the page that I use a cookie for.  I want the site to redirect back to the page they were on after they log in again.

For this, I use a cookie that has the name of the page stored in it (example, queue.php) and it will take them back.

This method works great if I'm going to a page that is in the same directory, but if I want to go back to a sub-directory, (for example, Deployment/deployment.php) it does not work.

I have tried urlencode(), backslashes, addslashes(), %2F in place of the forward slash, and nothing seems to be working.

This is how I am setting the cookie:

$url_name = "Deployment/deployment.php";
setcookie("url",$url_name);

Any help would be appreciated, I am completely lost.

Body:
I don't know where your login page is found, but if Deployment is a subdirectory (so one level beneath the main folder) you should add a forward slash infront of it, like so:

$url_name = "/Deployment/deployment.php";
setcookie("url", $url_name);


问:
Breaking google sheet table into separate tables based on a column (Google App Script)
Is there a way that we can break the table based on 'Bank with' column (already sorted)?

Client name
Age
Bank with

Client 1
19
Bank 1

Client 2
32
Bank 1

Client 3
22
Bank 1

Client 4
34
Bank 2

Client 5
22
Bank 2

Client 5
28
Bank 3

Basically breaking into:

Client name
Age
Bank with

Client 1
19
Bank 1

Client 2
32
Bank 1

Client 3
22
Bank 1

Client name
Age
Bank with

Client 4
34
Bank 2

Client 5
22
Bank 2

Client name
Age
Bank with

Client 5
28
Bank 3

Thank you!

答:
Break up into smaller tables

```<code>function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"]);//running headers
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clearContents();//clear output sheet
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));//insert space
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  })
}
</code>```

This version bolds each new header row.

```<code>function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"])
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clear();
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));
    osh.getRange(osh.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  })
}
</code>```

3 Separate Sections and 3 separate sheets

```<code>function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"]);//running headers
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  // all on one sheet
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clear();//clear output sheet
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));//insert space
    osh.getRange(osh.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  });
  //3 separate sheets
  const ishts = ["Sheet2","Sheet3","Sheet4"];
  arr.forEach((e,i) => {
    let ish = ss.getSheetByName(ishts[i]);
    ish.clear();
    ish.getRange(ish.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    ish.getRange(ish.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Break up into smaller tables

function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"]);//running headers
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clearContents();//clear output sheet
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));//insert space
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  })
}

This version bolds each new header row.

function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"])
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clear();
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));
    osh.getRange(osh.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  })
}

3 Separate Sections and 3 separate sheets

function breakthebank() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
  const obj = {pA:[]};
  vs.forEach(r => {
    if(!obj.hasOwnProperty(r[2])) {
      obj[r[2]] = [];
      obj[r[2]].push(["Client Name","Age","Bank with"]);//running headers
      obj[r[2]].push(r);
      obj.pA.push(r[2]);
    } else {
      obj[r[2]].push(r);
    }
  });
  // all on one sheet
  let arr = obj.pA.map(p => obj[p]);
  console.log(JSON.stringify(arr));
  osh.clear();//clear output sheet
  arr.forEach(e => {
    e.push(new Array(e[0].length).fill(' '));//insert space
    osh.getRange(osh.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    osh.getRange(osh.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  });
  //3 separate sheets
  const ishts = ["Sheet2","Sheet3","Sheet4"];
  arr.forEach((e,i) => {
    let ish = ss.getSheetByName(ishts[i]);
    ish.clear();
    ish.getRange(ish.getLastRow() + 1, 1, 1, e[0].length).setFontWeight("bold");
    ish.getRange(ish.getLastRow() + 1, 1, e.length,e[0].length).setValues(e);
  });
}


问:
Adding values in a new column conditionally in pandas dataframe
I have a DataFrame like below:

```<code>ds = pd.DataFrame({'Name' : ['A','A','B','B','C', 'C', 'C', 'C'],
    'Year': ['2021','2020','2020','2019','2021','2020','2020','2019' ]})
</code>```

I want to add a new column 'Breached'. The value of "Breached" for column Name 'A' should be 1 if the year is less than the year of previous records of A and set to '0' otherwise.
Similarly, the value of "Breached" for column Name 'B' should be 1 if the year is less than the year of previous records of B and set to '0' otherwise.
Same goes for C.

So, my output should look like :

Here, the value of breached again is 0 only if the year was 2021 because that is the latest year for the name 'C'.

Any suggestion on how can I do that?

答:
Seems like you could groupby + transform max + ne to get a boolean Series that is True if the year is the not latest year for each group, False otherwise. Then convert this Series to int dtype:

```<code>ds['Breached'] = ds.groupby('Name')['Year'].transform('max').ne(ds['Year']).astype(int)
</code>```

Output:

```<code>  Name  Year  Breached
0    A  2021         0
1    A  2020         1
2    B  2020         0
3    B  2019         1
4    C  2021         0
5    C  2020         1
6    C  2020         1
7    C  2019         1
</code>```

Body:
I have a DataFrame like below:

ds = pd.DataFrame({'Name' : ['A','A','B','B','C', 'C', 'C', 'C'],
    'Year': ['2021','2020','2020','2019','2021','2020','2020','2019' ]})

I want to add a new column 'Breached'. The value of "Breached" for column Name 'A' should be 1 if the year is less than the year of previous records of A and set to '0' otherwise.
Similarly, the value of "Breached" for column Name 'B' should be 1 if the year is less than the year of previous records of B and set to '0' otherwise.
Same goes for C.

So, my output should look like :

Here, the value of breached again is 0 only if the year was 2021 because that is the latest year for the name 'C'.

Any suggestion on how can I do that?

Body:
Seems like you could groupby + transform max + ne to get a boolean Series that is True if the year is the not latest year for each group, False otherwise. Then convert this Series to int dtype:

ds['Breached'] = ds.groupby('Name')['Year'].transform('max').ne(ds['Year']).astype(int)

Output:

  Name  Year  Breached
0    A  2021         0
1    A  2020         1
2    B  2020         0
3    B  2019         1
4    C  2021         0
5    C  2020         1
6    C  2020         1
7    C  2019         1


问:
Suggestion on how to deal with different user right
I have a page which have different version, one is member, one is admin, and one is guest.
You may know what is the different, if the user, they have:
login button
register button

if the user is a member, they have:
logout button
edit button in they content

and the admin, will have:
logout button
banned button for all content

So, my question is, they are similar content, show I make 3 separate page? or one page to do all this stuff? Thank you.

答:
I suggest you use one page and use ACL to define what every user can do. I heard ZEND_Acl is a good start.

Definition of ACL:

http://en.wikipedia.org/wiki/Access_control_list

CodeIgniter + Zend ACL:

http://www.lucdebrouwer.nl/adding-zend-acl-to-codeigniter/

http://www.revolves.net/2008/12/18/using-zend-acl-with-codeigniter/


问:
Sign-in with Apple from device using NextAuth.js
When using the Apple provider with NextAuth.js on the web server and signing in on a native device app (written in Swift using ASAuthorizationAppleIDButton and ASAuthorizationAppleIDProvider) using Sign In With Apple, how do you add a new user and account to the NextAuth.js database tables?

Besides signing into the iOS app, the user also needs to be able to sign into a website with Sign In With Apple and link his user account to other OAuth providers like Google (e.g. if signing in on Android). This question focuses on just Sign In With Apple on an iOS device and how to record that account info so that it plays nicely with sign-ins on other platforms.

Does NextAuth.js have a REST API that the iOS device can call to do this? Otherwise, if custom code on the Next.js server is needed to add the rows manually, is there documentation on what goes into each of the columns in NextAuth.js user and account tables?

答:
if you just setup the AppleProvider, NextAuth.js won't keep a database of your users.

It lets Apple handle that and then just gets a signed message back saying, im paraphrasing, "Yup, thats Edward, and here are some more details about him.." and includes some basic info like your email address, profile picture URL, etc.

This is the basics of their OAuth-only strategy.

If you'd like to persist user data yourself and maybe add additional fields to the ones Apple returns to you, you'll have to setup an adapter. An adapter in NextAuth.js world is just a database where it will automatically save any new users and check against for existing users.

You can see the details of the various available adapters, including the default model/schema here: https://next-auth.js.org/adapters/models


问:
What is the difference between assert and static_assert?
I know that static_assert makes assertions at compile time, and assert - at run time, but what is the difference in practice? As far as I understand, deep down they are pieces of code, like

```<code>if (condition == false) exit();
</code>```

Can someone give me an example of where only static_assert will work, or only assert?

Do they do anything a simple if statement can't do?

Is it bad practice to use them?

答:
It should be mentioned that it is important to find out about bugs as early as possible. A programmer wants to know when something first goes wrong, instead of the hundreds of problems caused by the original problem. If the code calculates a bad value and then uses it in subsequent calculations, all those calculations are wrong. Finding the earlies cause of the problem prevents the programmer from having to trace the bug back in time.

This is true for both run-time and compilation. Assert helps with this for run-time and static_assert helps with this for compilation. An example of where static_assert is useful for compile time checking to make sure the version of some header is perhaps equal to the version the rest of the code requires or was tested against. If the static_assert tells you the header version changed, it is much more useful than trying to figure out why you have all these compilation errors triggered by the changed header. It detects the problem as early as possible in the compilation process.

Another use for static_assert is to check whether the compilation was done with the right compiler switches. Microsoft's compilers, for example, use /J to signal that char be unsigned 8-bit value rather than signed. If the code requires it, it can be checked at compile time.

Body:
I know that static_assert makes assertions at compile time, and assert - at run time, but what is the difference in practice? As far as I understand, deep down they are pieces of code, like

if (condition == false) exit();

Can someone give me an example of where only static_assert will work, or only assert?

Do they do anything a simple if statement can't do?

Is it bad practice to use them?


问:
Monaco Editor reveal all lines
I'm using Microsoft's Monaco Editor library to create a code editor on a webpage and it's great, but as it seems, for performance reasons, only the visible lines are actually rendered, which does not sound like a problem it actually is when you want to print the contents of the editor.

Is there a way I could force the rendering of all lines?

My best guess was

```<code>editor.revealRange
</code>```

and other editor.reveal* methods, but none of that seem to work.

答:
Scroll to the top, run

HTMLDivElement.prototype.removeChild=function(){}
```
<p>then scroll to the bottom. Voilà, all the lines are rendered.
Some even twice, but that's ok since they're positioned absolute.</p>
<p>You could try to avoid duplicates via</p>
<pre class="lang-js prettyprint-override"><code>HTMLDivElement.prototype.reallyRemoveChild=HTMLDivElement.prototype.removeChild;
HTMLDivElement.prototype.removeChild=function(el){
    if(el.parentElement.querySelectorAll(`[style="${el.getAttribute('style')}"]`).length === 2)
    this.reallyRemoveChild.apply(this, arguments)
};
</code>```

Title: Monaco Editor reveal all lines

Body:
I'm using Microsoft's Monaco Editor library to create a code editor on a webpage and it's great, but as it seems, for performance reasons, only the visible lines are actually rendered, which does not sound like a problem it actually is when you want to print the contents of the editor.

Is there a way I could force the rendering of all lines?

My best guess was

editor.revealRange

and other editor.reveal* methods, but none of that seem to work.

Body:
Scroll to the top, run

HTMLDivElement.prototype.removeChild=function(){}

then scroll to the bottom. Voilà, all the lines are rendered.
Some even twice, but that's ok since they're positioned absolute.

You could try to avoid duplicates via

HTMLDivElement.prototype.reallyRemoveChild=HTMLDivElement.prototype.removeChild;
HTMLDivElement.prototype.removeChild=function(el){
    if(el.parentElement.querySelectorAll(`[style="${el.getAttribute('style')}"]`).length === 2)
    this.reallyRemoveChild.apply(this, arguments)
};


问:
converting a string to int in kotlin There is a problem
why result is mines?
my problem is converting a string to int in kotlin .

```<code>class Test{
    val x="200000000"
    val y="11"
}

fun main(){
    val test=Test()
    println(test.x.toInt())
    println(test.y.toInt())
    val z=(Integer.parseInt(test.x))*(Integer.parseInt(test.y))
//or :val z=(test.x.toInt())*(test.y.toInt())
    println(z)

}
</code>```

result :

200000000

11

-2094967296

答:
You're witnessing an integer overflow.

Int in Kotlin (like in Java) represents 32-bit signed integers, so their maximum value is 2,147,483,647.

What you're trying to do is multiply 200,000,000 by 11, which would yield 2,200,000,000 - more than the maximum value. So only the least significant bits of that number can be stored in the 32-bit of the integer, and you end up somewhere in the negative numbers.

If you want to reach this kind of values, you should either use UInt (unsigned integers, which can go twice higher), Long (which are 64-bit and thus can reach much much higher), or other more complex types like BigInteger.

Here is an example with Long:

val x = "200000000"
val y = "11"
val z = x.toLong() * y.toLong()
println(z) // 2200000000
```

Body:
why result is mines?
my problem is converting a string to int in kotlin .

class Test{
    val x="200000000"
    val y="11"
}

fun main(){
    val test=Test()
    println(test.x.toInt())
    println(test.y.toInt())
    val z=(Integer.parseInt(test.x))*(Integer.parseInt(test.y))
//or :val z=(test.x.toInt())*(test.y.toInt())
    println(z)

}

result :

200000000

11

-2094967296


问:
How to use different cell in one table view?
How to use 3 different cells on one uitableview? I have 3 buttons now When i press any button then cell of table view should be changed. Please help</p>

答:
In the button's action method, save which button was tapped & reload the row in which you want to change the cell.

```<code>-(void)button1Tapped:(id)sender
{

    self.buttonIndex = 1;
    NSArray* arr = [[NSArray alloc] initWithObjects:self.indexPathOfConcernedCell, nil];
    [self.tableView reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationNone];
    [arr release];

}
</code>```

Then, in cellForRowAtIndexPath: return the cell one the basis of which button was pressed-

```<code> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {

    if(indexPath == self.indexPathOfConcernedCell)
    {

    if(self.buttonIndex == 1)
             {
                  Cell1* cell = (Cell1*) [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier1"];

                  if(cell == nil)
                  {
                 cell = [[[Cell1 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CellIdentifier1"] autorelease];
                  }
             }

        else if(self.buttonIndex == 2)
        {
            //do similar stuff
        }

        //do similar stuff for buttonIndex 3 here

        }
    }

    else
    {
        //your regular stuff
    }

    return cell;

    }
</code>```

Body:
In the button's action method, save which button was tapped & reload the row in which you want to change the cell.

-(void)button1Tapped:(id)sender
{

    self.buttonIndex = 1;
    NSArray* arr = [[NSArray alloc] initWithObjects:self.indexPathOfConcernedCell, nil];
    [self.tableView reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationNone];
    [arr release];

}

Then, in cellForRowAtIndexPath: return the cell one the basis of which button was pressed-

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {

    if(indexPath == self.indexPathOfConcernedCell)
    {

    if(self.buttonIndex == 1)
             {
                  Cell1* cell = (Cell1*) [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier1"];

                  if(cell == nil)
                  {
                 cell = [[[Cell1 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CellIdentifier1"] autorelease];
                  }
             }

        else if(self.buttonIndex == 2)
        {
            //do similar stuff
        }

        //do similar stuff for buttonIndex 3 here

        }
    }

    else
    {
        //your regular stuff
    }

    return cell;

    }


问:
How to return a react component with the for in statement?
I'm trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

```<code>const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}
</code>```

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I'm pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

答:
I am assuming you wrote whole thing wrong.

This is my 2 cents

1st you want array not an object animals

```<code>const animals = [
  {  "name" : "cat",
    "number": 0,
  },
  { "name": "dog"
    "number": 1,
  }
]
</code>```

than you want your component

```<code>const AnimalsListComponenet = () => {

return (

 <React.Fragment>
  {
   animals.map((item)=>  Object.entries(item).map((entrie)=> <Text>{entrie}</Text>
   )

  }

 <React.Fragment>

)
}
</code>```

If you really want to iterat over object, you have to use : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Body:
I'm trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I'm pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

Body:
I am assuming you wrote whole thing wrong.

This is my 2 cents

1st you want array not an object animals

const animals = [
  {  "name" : "cat",
    "number": 0,
  },
  { "name": "dog"
    "number": 1,
  }
]

than you want your component

const AnimalsListComponenet = () => {

return (

 <React.Fragment>
  {
   animals.map((item)=>  Object.entries(item).map((entrie)=> <Text>{entrie}</Text>
   )

  }

 <React.Fragment>

)
}

If you really want to iterat over object, you have to use : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries


问:
Randomly split sorted array into smaller sorted arrays
I have a big sorted array of unique numbers. I do want to split it into n smaller disjoint sorted arrays with unique values. For example, I have an array [1, 2, 3, 4, 5, 6, 7, 8, 9] and the algorithm I am looking for gives one of the following results (n=3):

[1, 4, 7], [5, 6, 9], [2, 3, 8]

[3, 8, 9], [1, 5, 7], [2, 4, 6]

[3, 4, 7], [1, 5, 8], [2, 6, 9], etc

Why I need it: I have a very big array (about 1 billion values) and I need to distribute values randomly between nodes in a simulated network, which together compute some aggregated value. They work more efficiently if they have sorted values. Since I am testing this system I need to run the simulation many times with the different amount of nodes, network topology, etc. Obviously simply splitting the data into several consecutive chunks is not suitable here.

答:
Create n smaller arrays and an array of n indices. There is one index for each of the small arrays; they are all initialized to zero. Iterate over the large sorted array, at each step choosing one of the small arrays to put the value into. If the small array is already 'full' (its index is already equal to the length of the array), pick the next small array that is not yet full. Insert the value from the large array into the small array at the current value of its index, and then increment the index.

This will require a fast random number generator and perhaps a clever way of taking the completed subarrays out of the rotation, but it is linear in the large sorted array and requires no sorting.

In Java a two-dimensional array is an array of arrays, and we can leverage that to alter which subarrays each row is pointing to on the fly. The idea here is that subarrays is an array containing all the subarrays, and the references to them never change, but candidate starts out with references to all of them and gradually adjusts itself so that only the arrays that are still not full are referenced.

```<code>int[][] splitSorted(int[] array, int n) {
    if (array.length % n != 0) {
        throw new IllegalArgumentException(
            n + " does not divide " + array.length + " evenly");
    }
    int size = array.length / n;  // size of each subarray
    int[][] subarrays = new int[n][size];
    int[][] candidate = Arrays.copyOf(subarrays, subarrays.length);
    int[] index = new int[n];

    Random rand = new Random();
    for (int i : array) {
        int which = rand.nextInt(n);
        candidate[which][index[which]] = i;  // insert into a subarray
        ++index[which];
        if (index[which] == size) {  // one has maxed out
            --n;  // remove it from consideration
            candidate[which] = candidate[n];
            index[which] = index[n];
        }
    }
    return subarrays;
}
</code>```

When an array is full, we swap the one at the end of candidate into its place, so that the first rows contain the ones we're still trying to fill. Note that candidate completely loses track of the filled arrays. That's fine because they're still referenced by subarrays, which never changes. (We avoid having it alias candidate by taking a shallow copy with Arrays::copyOf when we create candidate.) We also have to swap the index for the array we're swapping.

Note also that the on the two lines that do the swap, which and n could be identical. An if could avoid setting them in this case, but setting them is redundant, so I prefer to keep the code simpler. n is decremented so the next time around the loop, we will pick a random number in a smaller range; only arrays that still need to be filled are considered. Finally, we return an array of all the filled subarrays.

It should be clear, but I will just underscore that because we put each value from the original large sorted array into one and only one subarray, and because we put them there in order, that the uniqueness and sorted constraints of the original array will be maintained on the subarrays.

Body:
Create n smaller arrays and an array of n indices. There is one index for each of the small arrays; they are all initialized to zero. Iterate over the large sorted array, at each step choosing one of the small arrays to put the value into. If the small array is already 'full' (its index is already equal to the length of the array), pick the next small array that is not yet full. Insert the value from the large array into the small array at the current value of its index, and then increment the index.

This will require a fast random number generator and perhaps a clever way of taking the completed subarrays out of the rotation, but it is linear in the large sorted array and requires no sorting.

In Java a two-dimensional array is an array of arrays, and we can leverage that to alter which subarrays each row is pointing to on the fly. The idea here is that subarrays is an array containing all the subarrays, and the references to them never change, but candidate starts out with references to all of them and gradually adjusts itself so that only the arrays that are still not full are referenced.

int[][] splitSorted(int[] array, int n) {
    if (array.length % n != 0) {
        throw new IllegalArgumentException(
            n + " does not divide " + array.length + " evenly");
    }
    int size = array.length / n;  // size of each subarray
    int[][] subarrays = new int[n][size];
    int[][] candidate = Arrays.copyOf(subarrays, subarrays.length);
    int[] index = new int[n];

    Random rand = new Random();
    for (int i : array) {
        int which = rand.nextInt(n);
        candidate[which][index[which]] = i;  // insert into a subarray
        ++index[which];
        if (index[which] == size) {  // one has maxed out
            --n;  // remove it from consideration
            candidate[which] = candidate[n];
            index[which] = index[n];
        }
    }
    return subarrays;
}

When an array is full, we swap the one at the end of candidate into its place, so that the first rows contain the ones we're still trying to fill. Note that candidate completely loses track of the filled arrays. That's fine because they're still referenced by subarrays, which never changes. (We avoid having it alias candidate by taking a shallow copy with Arrays::copyOf when we create candidate.) We also have to swap the index for the array we're swapping.

Note also that the on the two lines that do the swap, which and n could be identical. An if could avoid setting them in this case, but setting them is redundant, so I prefer to keep the code simpler. n is decremented so the next time around the loop, we will pick a random number in a smaller range; only arrays that still need to be filled are considered. Finally, we return an array of all the filled subarrays.

It should be clear, but I will just underscore that because we put each value from the original large sorted array into one and only one subarray, and because we put them there in order, that the uniqueness and sorted constraints of the original array will be maintained on the subarrays.


问:
SQL determine business days passed since beginning of month using calendar table
I have a calendar table with all dates and a column indicating whether its a business day.

For example

Date
Business_Day

1/1/2021
False

1/2/2021
False

1/3/2021
True

...
I have another table with dates and would like to determine how many business days have elapsed since the beginning of that month.
For example:

Date
Business_Days_Passed

1/1/2022
0

1/2/2022
0

1/3/2022
1

1/4/2022
2

1/15/2022
10

2/2/2022
2

2/11/2022
9

2/12/2022
9

Is there a way to do this using standard sql?  I was thinking of creating some kind of UDF but there may be an easier way?  This using snowflake so there is access to all common date functions and window/udf functions

答:
So if your dates has "all dates" you can use a JOIN like:

```<code>SELECT d.date,
    count_if(w.business_day) AS business_days_passed
FROM dates_of_interest AS d
JOIN work_days AS w
    ON date_trunc(month, d.date) = date_trunc(month, w.date)
        AND d.date >= w.date
GROUP BY 1
ORDER BY 1;
</code>```

But if you Dates have gaps in them, like my example data does... you would want the LEFT JOIN form..

```<code>SELECT d.date,
    count_if(w.business_day) AS business_days_passed
FROM dates_of_interest AS d
LEFT JOIN work_days AS w
    ON date_trunc(month, d.date) = date_trunc(month, w.date)
        AND d.date >= w.date
GROUP BY 1
ORDER BY 1;
</code>```

And using this wonderful fake data:

```<code>WITH work_days(date, business_day) AS (
    SELECT
        DATEADD('day', ROW_NUMBER() OVER (ORDER BY NULL)-1, TO_DATE('1/1/2022', 'mm/dd/yyyy')) AS date
        ,DAYOFWEEKISO(date) < 6 AS business_day
    FROM TABLE(generator(ROWCOUNT => 65))
), dates_of_interest(date) AS (
    SELECT TO_DATE(column1, 'mm/dd/yyyy')
    FROM VALUES
        ('1/1/2022'),
        ('1/2/2022'),
        ('1/3/2022'),
        ('1/4/2022'),
        ('1/15/2022'),
        ('2/2/2022'),
        ('2/11/2022'),
        ('2/12/2022')
)
</code>```

we get:

DATE
BUSINESS_DAYS_PASSED

2022-01-01
0

2022-01-02
0

2022-01-03
1

2022-01-04
2

2022-01-15
10

2022-02-02
2

2022-02-11
9

2022-02-12
9

Body:
So if your dates has "all dates" you can use a JOIN like:

SELECT d.date,
    count_if(w.business_day) AS business_days_passed
FROM dates_of_interest AS d
JOIN work_days AS w
    ON date_trunc(month, d.date) = date_trunc(month, w.date)
        AND d.date >= w.date
GROUP BY 1
ORDER BY 1;

But if you Dates have gaps in them, like my example data does... you would want the LEFT JOIN form..

SELECT d.date,
    count_if(w.business_day) AS business_days_passed
FROM dates_of_interest AS d
LEFT JOIN work_days AS w
    ON date_trunc(month, d.date) = date_trunc(month, w.date)
        AND d.date >= w.date
GROUP BY 1
ORDER BY 1;

And using this wonderful fake data:

WITH work_days(date, business_day) AS (
    SELECT
        DATEADD('day', ROW_NUMBER() OVER (ORDER BY NULL)-1, TO_DATE('1/1/2022', 'mm/dd/yyyy')) AS date
        ,DAYOFWEEKISO(date) < 6 AS business_day
    FROM TABLE(generator(ROWCOUNT => 65))
), dates_of_interest(date) AS (
    SELECT TO_DATE(column1, 'mm/dd/yyyy')
    FROM VALUES
        ('1/1/2022'),
        ('1/2/2022'),
        ('1/3/2022'),
        ('1/4/2022'),
        ('1/15/2022'),
        ('2/2/2022'),
        ('2/11/2022'),
        ('2/12/2022')
)

we get:

DATE
BUSINESS_DAYS_PASSED

2022-01-01
0

2022-01-02
0

2022-01-03
1

2022-01-04
2

2022-01-15
10

2022-02-02
2

2022-02-11
9

2022-02-12
9


问:
How to detect in perl if the client is using a mobile browser?
I'm using a CGI script to generate a dynamic webpage. I want the page to load elements differently depending on whether or not the user is using a phone (such as a blackberry) to access the website or a normal browser. Is there an environment detail I can grab to make this decision? What would be the best method of doing this (even if its using javascript and not CGI.) </p>

答:
Use the Perl variable $ENV{'HTTP_USER_AGENT'} and the HTTP::BrowserDetect module.

Once you have the determined what browser the client is using (e.g. is it a mobile browser) - then you can make the decision on what to send back to the client (mobile version or desktop version etc)


问:
What is best way to connect React to Nodejs backend
Hey guys I recently finished learning React and Nodejs. The thing is I don't know how to connect the two to have a fullstack app. Can you guys help me with that please? What libraries are the best in which you've used.</p>

答:
To connect the backend with the front through ReactJS, you can use axios to consume an external API, for that you install it in your application:

```<code>npm install axios
</code>```

or

```<code>yarn install axios
</code>```

with the backend application running locally on port 3333, for example, you can create an api.js file in your application and put the code:

```<code>import axios from "axios";

const api = axios.create({
  baseURL: "http://localhost:3333/",
});

export default api;

</code>```

So you can go to your React app's main file and consume using the useEffect hook like this:

```<code>import React, { useEffect, useState } from "react";
import api from "./api";

export default function App() {

  useEffect(() => {
    api
      .get("/YOUR ENDPOINT")
      .then((response) => console.log(response.data))
      .catch((err) => {
        console.error("error" + err);
      });
  }, []);

  return (
    <div className="App">

    </div>
  );
}

</code>```

Body:
To connect the backend with the front through ReactJS, you can use axios to consume an external API, for that you install it in your application:

npm install axios

or

yarn install axios

with the backend application running locally on port 3333, for example, you can create an api.js file in your application and put the code:

import axios from "axios";

const api = axios.create({
  baseURL: "http://localhost:3333/",
});

export default api;

So you can go to your React app's main file and consume using the useEffect hook like this:

import React, { useEffect, useState } from "react";
import api from "./api";

export default function App() {

  useEffect(() => {
    api
      .get("/YOUR ENDPOINT")
      .then((response) => console.log(response.data))
      .catch((err) => {
        console.error("error" + err);
      });
  }, []);

  return (
    <div className="App">

    </div>
  );
}


问:
How can I check if a file exists on a remote server using PHP?
How can I check if a specific file exists on a remote server using PHP via FTP connections?</p>

答:
The code has been written by: @Drmzindec should be change a little:

```<code>if (in_array($check_file_exist, $contents_on_server))
</code>```

to

```<code>if (in_array($file, $contents_on_server))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The code has been written by: @Drmzindec should be change a little:

if (in_array($check_file_exist, $contents_on_server))

to

if (in_array($file, $contents_on_server))


问:
User-friendly time zone names corresponding to IANA names
I am attempting to find a user-friendly list of time zones for users to
select their current time zone. It would have common names that time zones that are referred to such as
Pacific Time (US and Canada).

This list should map the text to an IANA standard name such as America/Los_Angeles.

It would also remove listings that the user thinks of as the "same" time zone. For example the listing for Pacific Time (US and Canada) would correspond to America/Los_Angeles and America/Tijuana, which are the "same" time.

I've tried looking in the IANA Time Zone Database, ECMA Script internationalization API, and libraries like Moment.js. They can parse the IANA name into the common name, for example America/Los_Angeles ==> "Pacific Standard Time" but don't have a built-in function for listing all the common names and their corresponding IANA names.

答:
Building on Kimamula's answer, I took the current list of IANA time zone names and ran it through my browser's Intl formatter to obtain long and short names for all of them. The result is a gist with a mapping of IANA names to human readable names. I've taken the 'generic' forms of these names, which omits mention of daylight saving time. Otherwise we would need to know whether DST is in effect to select the name. (e.g. Pacific Time instead of Pacific Standard Time or Pacific Daylight Time).

Not every timezone has an ideal name in this database, as with most things time related this will be an imperfect solution. But it will hopefully cover the time zones that are most popular with your users, and displaying an IANA name as a fallback is an option.

In case you want to generate these names yourself, you can run this in your browser. These names came from Firefox, I would guess that they are implementation dependent and might be a bit different in other browsers.

const iana_names = [
  "Africa/Abidjan",
  "Africa/Accra",
  "Africa/Addis_Ababa",
  // ...
  "W-SU",
  "WET",
  "Zulu"
]

const mapping = {}

iana_names.forEach( name => {

   const long = new Intl.DateTimeFormat('default', { timeZone: name, timeZoneName: 'longGeneric' }).formatToParts().find(({ type }) => type === 'timeZoneName').value
   const short = new Intl.DateTimeFormat('default', { timeZone: name, timeZoneName: 'shortGeneric' }).formatToParts().find(({ type }) => type === 'timeZoneName').value

   mapping[name] = {
     long, short
   }

})
```


问:
How to obtain the enable admission controller list in kubernetes?
AFAIK, the admission controller is the last pass before the submission to the database.

However I cannot know which one is enabled, Is there a way to know which one is taking effect?

Thanks.

答:
Not sure why it was not stated before, but it's even in the kubernetes docs:

```<code>kubectl exec -it kube-apiserver-<your-machine-name> -n kube-system -- kube-apiserver -h | grep enable-admission-plugins
</code>```

It does exactly what you want.

Body:
Not sure why it was not stated before, but it's even in the kubernetes docs:

kubectl exec -it kube-apiserver-<your-machine-name> -n kube-system -- kube-apiserver -h | grep enable-admission-plugins

It does exactly what you want.


问:
Looping through elements with Selenium and ChromeDriver
Im having trouble working through the following problem.
Im trying to collect the data from the following webpage:https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM

My method is to use the Selenium chrome driver to collect the data, for each healthcare agent, off this webpage, but dont know how I would loop through each record and add the data to each created list. So far, I can collect the data for a single record, but my problem is with my loop. How would I identify each record as an agent, and add that to my data frame for output? here is my code:

```<code>from selenium import webdriver  # connect python with webbrowser-chrome
import time
import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome('C:/Users/picka/Documents/chromedriver.exe')
driver.maximize_window()

url = 'https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM'

name = []
phone = []
email = []

def go_to_network():
    driver.get(url)

    for agent in driver.find_elements_by_xpath('class.qa-flh-results-list'):

        get_name = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.qa-flh-resource-name"))).text)
        get_phone = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.qa-flh-resource-phone"))).text)
        get_email = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.ds-u-overflow--hidden.ds-u-truncate.ds-u-display--inline-block"))).text)

        name.append(get_name)
        phone.append(get_phone)
        email.append(get_email)

go_to_network()

record_output = {'Agent Name': name, 'Phone': phone, 'Email':  email}
df = pd.DataFrame(record_output)
df.to_csv(r'C:\Users\picka\Documents\Dev\Reports\Agent-data.csv', header=True, index=False)
print(df)
</code>```

答:
To extract and print all the Agent Name, Phone and Email using Selenium you can use List Comprehension inducing WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Code Block:

```<code>driver.get('https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM')
get_name = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.qa-flh-resource-name")))]
get_phone = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a.qa-flh-resource-phone")))]
get_email = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a.ds-u-overflow--hidden.ds-u-truncate.ds-u-display--inline-block")))]
for i,j,k in zip(get_name, get_phone, get_email):
  print(f"{i}'s' phone number is {j} and email is {k}")
driver.quit()
</code>```

Console Output:

```<code>Wesley Elton's' phone number is (801) 404 - 2424 and email is wes@wallbrokers.com
Raquel Bell's' phone number is (801) 842 - 2870 and email is raquel.bell@enroll365.org
Brandon Berglund's' phone number is (801) 981 - 9414 and email is Brandon@BerglundIns.com
Steven Cochran's' phone number is (801) 800 - 8360 and email is steve.cochran@gbsbenefits.com
victoria dang's' phone number is (801) 462 - 5190 and email is victoriawfg@yahoo.com
Dan Jessop's' phone number is (435) 232 - 8833 and email is dejessop@hotmail.com
Billy Gerdts's' phone number is (801) 280 - 1162 and email is bgerdts@gginsurancegroup.com
Michael Saldana's' phone number is (801) 879 - 1032 and email is saldana.michael25@gmail.com
Brandon Johnson's' phone number is (435) 249 - 0725 and email is brandon@msiagency.com
Matthew Selph's' phone number is (801) 918 - 3945 and email is selph7@gmail.com
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
Im having trouble working through the following problem.
Im trying to collect the data from the following webpage:https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM

My method is to use the Selenium chrome driver to collect the data, for each healthcare agent, off this webpage, but dont know how I would loop through each record and add the data to each created list. So far, I can collect the data for a single record, but my problem is with my loop. How would I identify each record as an agent, and add that to my data frame for output? here is my code:

from selenium import webdriver  # connect python with webbrowser-chrome
import time
import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome('C:/Users/picka/Documents/chromedriver.exe')
driver.maximize_window()

url = 'https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM'

name = []
phone = []
email = []

def go_to_network():
    driver.get(url)

    for agent in driver.find_elements_by_xpath('class.qa-flh-results-list'):

        get_name = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.qa-flh-resource-name"))).text)
        get_phone = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.qa-flh-resource-phone"))).text)
        get_email = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.ds-u-overflow--hidden.ds-u-truncate.ds-u-display--inline-block"))).text)

        name.append(get_name)
        phone.append(get_phone)
        email.append(get_email)

go_to_network()

record_output = {'Agent Name': name, 'Phone': phone, 'Email':  email}
df = pd.DataFrame(record_output)
df.to_csv(r'C:\Users\picka\Documents\Dev\Reports\Agent-data.csv', header=True, index=False)
print(df)

Body:
To extract and print all the Agent Name, Phone and Email using Selenium you can use List Comprehension inducing WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

Code Block:

driver.get('https://localhelp.healthcare.gov/#/results?q=UTAH&lat=0&lng=0&city=&state=UT&zip_code=&mp=FFM')
get_name = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "span.qa-flh-resource-name")))]
get_phone = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a.qa-flh-resource-phone")))]
get_email = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a.ds-u-overflow--hidden.ds-u-truncate.ds-u-display--inline-block")))]
for i,j,k in zip(get_name, get_phone, get_email):
  print(f"{i}'s' phone number is {j} and email is {k}")
driver.quit()

Console Output:

Wesley Elton's' phone number is (801) 404 - 2424 and email is wes@wallbrokers.com
Raquel Bell's' phone number is (801) 842 - 2870 and email is raquel.bell@enroll365.org
Brandon Berglund's' phone number is (801) 981 - 9414 and email is Brandon@BerglundIns.com
Steven Cochran's' phone number is (801) 800 - 8360 and email is steve.cochran@gbsbenefits.com
victoria dang's' phone number is (801) 462 - 5190 and email is victoriawfg@yahoo.com
Dan Jessop's' phone number is (435) 232 - 8833 and email is dejessop@hotmail.com
Billy Gerdts's' phone number is (801) 280 - 1162 and email is bgerdts@gginsurancegroup.com
Michael Saldana's' phone number is (801) 879 - 1032 and email is saldana.michael25@gmail.com
Brandon Johnson's' phone number is (435) 249 - 0725 and email is brandon@msiagency.com
Matthew Selph's' phone number is (801) 918 - 3945 and email is selph7@gmail.com

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
.htaccess drupal 7 RedirectMatch or RewriteRule nothing seams to work
I'm having some real issues getting a redirect to work in .htaccess with drupal 7.

I have links like this:

```<code>example.com/vid/category/filter?subcat_filter_depth=125
</code>```

and I need them to go to: (on same domain)

```<code>example.com/vid/category/filter?type=All&subcat_filter_depth=125
</code>```

after = the number may be different like 67 or 32 etc. meaning that can be any number and whatever number is at the end of the original link needs to also be at the end of the new link.

I think the fact that the link is pretty much the same path just different filter is what is causing the issue as even the Drupal redirect url module will not allow it at an attempt to add them one at a time as they occur.

here is everything I've tried:

```<code>RedirectMatch 301 ^/vid/category/filter?subcat_filter_depth=(.*) /vid/category/filter?type=All&subcat_filter_depth=$1

RewriteRule ^(.*)/vid/category/filter?subcat_filter_depth=(.*) $1/vid/category/filter?type=All&subcat_filter_depth=$2 [R=301]

RedirectMatch ^/vid/category/filter?subcat_filter_depth=(.*) ^/vid/category/filter?type=All&subcat_filter_depth=$1

RedirectMatch 301 ^(.*)/filter?subcat_filter_depth=(.*) ^$1/filter?type=All&subcat_filter_depth=$2

RedirectMatch ^/(.*)/filter?subcat_filter_depth=(.*) ^/$1/filter?type=All&subcat_filter_depth=$2

RewriteRule "^/(.*)/filter?subcat_filter_depth=(.*)" "^/$1/filter?type=All&subcat_filter_depth=$2"
</code>```

mod_rewrite is on and there is an AllowOverride pathed/to/the/.htaccess file under <Directory> inside <VirtualHost> in the 000-default.conf running on Debian Apache ..pretty much latest versions.

I know mod_rewrite is working because if I add a bad rule or rewrite with a syntax error I get error 500 response page.

I've searched and tried just about everything I can think of and nothing seems to work.

Any help getting this sorted and functioning would be greatly appreciated!

答:
Both the RedirectMatch (mod_alias) and RewriteRule (mod_rewrite) directives match against the URL-path only, which notably excludes the query string.

To match against the query string you need to use RewriteRule with an additional condition (RewriteCond directive) that checks against the QUERY_STRING server variable.

This rule also needs to go near the top of the .htaccess file, before any existing rewrites.

For example:

```<code>RewriteCond %{QUERY_STRING} ^subcat_filter_depth=\d+$
RewriteRule ^vid/category/filter$ /$0?type=All [QSA,R=302,L]
</code>```

This redirects example.com/vid/category/filter?subcat_filter_depth=<number> to example.com/vid/category/filter?type=All&subcat_filter_depth=<number>.

In .htaccess there is no slash prefix on the URL-path matched by the RewriteRule pattern. ie. ^vid/category (not ^/vid/category).

$0 is a backreference that contains the matched URL-path from the RewriteRule pattern.

QSA causes the original query string (eg. subcat_filter_depth=125) to be appended to the query string stated in the substitution string, ie. type=All becomes type=All&subcat_filter_depth=125.

Test with 302 (temporary) redirect to avoid potential caching issues. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed it works as intended.

You will likely need to clear your browser cache before testing.

Body:
I'm having some real issues getting a redirect to work in .htaccess with drupal 7.

I have links like this:

example.com/vid/category/filter?subcat_filter_depth=125

and I need them to go to: (on same domain)

example.com/vid/category/filter?type=All&subcat_filter_depth=125

after = the number may be different like 67 or 32 etc. meaning that can be any number and whatever number is at the end of the original link needs to also be at the end of the new link.

I think the fact that the link is pretty much the same path just different filter is what is causing the issue as even the Drupal redirect url module will not allow it at an attempt to add them one at a time as they occur.

here is everything I've tried:

RedirectMatch 301 ^/vid/category/filter?subcat_filter_depth=(.*) /vid/category/filter?type=All&subcat_filter_depth=$1

RewriteRule ^(.*)/vid/category/filter?subcat_filter_depth=(.*) $1/vid/category/filter?type=All&subcat_filter_depth=$2 [R=301]

RedirectMatch ^/vid/category/filter?subcat_filter_depth=(.*) ^/vid/category/filter?type=All&subcat_filter_depth=$1

RedirectMatch 301 ^(.*)/filter?subcat_filter_depth=(.*) ^$1/filter?type=All&subcat_filter_depth=$2

RedirectMatch ^/(.*)/filter?subcat_filter_depth=(.*) ^/$1/filter?type=All&subcat_filter_depth=$2

RewriteRule "^/(.*)/filter?subcat_filter_depth=(.*)" "^/$1/filter?type=All&subcat_filter_depth=$2"

mod_rewrite is on and there is an AllowOverride pathed/to/the/.htaccess file under <Directory> inside <VirtualHost> in the 000-default.conf running on Debian Apache ..pretty much latest versions.

I know mod_rewrite is working because if I add a bad rule or rewrite with a syntax error I get error 500 response page.

I've searched and tried just about everything I can think of and nothing seems to work.

Any help getting this sorted and functioning would be greatly appreciated!

Body:
Both the RedirectMatch (mod_alias) and RewriteRule (mod_rewrite) directives match against the URL-path only, which notably excludes the query string.

To match against the query string you need to use RewriteRule with an additional condition (RewriteCond directive) that checks against the QUERY_STRING server variable.

This rule also needs to go near the top of the .htaccess file, before any existing rewrites.

For example:

RewriteCond %{QUERY_STRING} ^subcat_filter_depth=\d+$
RewriteRule ^vid/category/filter$ /$0?type=All [QSA,R=302,L]

This redirects example.com/vid/category/filter?subcat_filter_depth=<number> to example.com/vid/category/filter?type=All&subcat_filter_depth=<number>.

In .htaccess there is no slash prefix on the URL-path matched by the RewriteRule pattern. ie. ^vid/category (not ^/vid/category).

$0 is a backreference that contains the matched URL-path from the RewriteRule pattern.

QSA causes the original query string (eg. subcat_filter_depth=125) to be appended to the query string stated in the substitution string, ie. type=All becomes type=All&subcat_filter_depth=125.

Test with 302 (temporary) redirect to avoid potential caching issues. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed it works as intended.

You will likely need to clear your browser cache before testing.


问:
Adding the prevalence of an outcome to a gtsummary::tbl_uvregression univariable regression table
I would like to add the prevalence of an outcome to a univariable regression table generated with gtsummary::tbl_uvregression. Is there a way to do this without converting the tbl_uvregression object to a table and calculating it with the dplyr::mutate function as in the example below?

PS: Daniel Sjoberg, thank you for a very helpful package!

options(digits = 3)
library(gtsummary)
#> #BlackLivesMatter
library(tidyverse)
library(knitr)
library(geepack)

packageVersion("gtsummary")
#> [1] '1.5.1'

data(dietox, package = "geepack")

dietox %>%
  mutate(big_pig = if_else(Weight > 50, 1, 0)) %>%
  select(big_pig, Pig, Evit, Cu, Litter) %>%

  tbl_uvregression(
    y = big_pig,
    method = geeglm,
    method.args = list(id = Pig, family = poisson, corstr = "independence"),
    include = -Pig,
    exponentiate = TRUE
  ) %>%
  add_n(location = c("level", "label")) %>%
  add_nevent(location = c("level", "label")) %>%
  as_tibble() %>%
  mutate(Prevalence = (`**Event N**` / as.integer(`**N**`))*100) %>%
  select(`**Characteristic**`,`**N**`,`**Event N**`,Prevalence, everything()) %>%
  kable()
```

Characteristic
N
Event N
Prevalence
IRR
95% CI
p-value

Evit
861
519
60.3
NA
NA
NA

Evit000
276
167
60.5
NA
NA
NA

Evit100
286
178
62.2
1.03
0.95, 1.12
0.5

Evit200
299
174
58.2
0.96
0.88, 1.05
0.4

Cu
861
519
60.3
NA
NA
NA

Cu000
274
164
59.9
NA
NA
NA

Cu035
300
176
58.7
0.98
0.91, 1.06
0.6

Cu175
287
179
62.4
1.04
0.96, 1.13
0.3

Litter
861
519
60.3
NA
NA
NA

1
48
31
64.6
NA
NA
NA

2
36
25
69.4
1.08
0.99, 1.17
0.091

3
48
25
52.1
0.81
0.64, 1.02
0.077

4
48
29
60.4
0.94
0.86, 1.01
0.10

5
36
25
69.4
1.08
0.90, 1.28
0.4

6
48
31
64.6
1.00
0.93, 1.08
>0.9

7
24
12
50.0
0.77
0.61, 0.98
0.035

8
48
28
58.3
0.90
0.75, 1.08
0.3

9
33
18
54.5
0.84
0.72, 0.99
0.043

10
36
24
66.7
1.03
0.98, 1.09
0.3

11
36
20
55.6
0.86
0.78, 0.95
0.002

12
36
21
58.3
0.90
0.78, 1.04
0.2

13
36
21
58.3
0.90
0.86, 0.95
<0.001

16
48
32
66.7
1.03
0.93, 1.14
0.5

17
36
24
66.7
1.03
0.98, 1.09
0.3

18
36
21
58.3
0.90
0.86, 0.95
<0.001

20
48
30
62.5
0.97
0.89, 1.05
0.5

21
48
30
62.5
0.97
0.79, 1.19
0.8

22
48
27
56.2
0.87
0.74, 1.03
0.11

23
48
24
50.0
0.77
0.63, 0.95
0.016

24
36
21
58.3
0.90
0.86, 0.95
<0.001

Created on 2022-02-11 by the reprex package (v2.0.1)

答:
A gtsummary table contains an internal data frame called .$table_body, and you can modify that data frame directly using the modify_table_body() function. In the example below, I calculate the prevalence and format the results to display in the table. I also expose the already existing column exposure, which is the sum of the exposure/followup time. Happy Programming!

library(gtsummary)
library(tidyverse)
library(geepack)

packageVersion("gtsummary")
#> [1] '1.5.2'

data(dietox, package = "geepack")

tbl <-
  dietox %>%
  mutate(big_pig = if_else(Weight > 50, 1, 0)) %>%
  select(big_pig, Pig, Evit, Cu) %>%
  tbl_uvregression(
    y = big_pig,
    method = geeglm,
    method.args = list(id = Pig, family = poisson, corstr = "independence"),
    include = -Pig,
    exponentiate = TRUE
  ) %>%
  add_n(location = c("level", "label")) %>%
  add_nevent(location = c("level", "label")) %>%
  # calculate prev
  modify_table_body(
    ~.x %>%
      mutate(
        prev = stat_nevent / stat_n * 100
      ) %>%
      relocate(prev, exposure, .after = stat_nevent)
  ) %>%
  # format the newly added stats
  modify_header(prev = "**Prevalence**", exposure = "**Total Exposure Time**") %>%
  modify_fmt_fun(list(prev = function(x) paste0(style_sigfig(x), "%"),
                      exposure = style_sigfig))
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
I would like to add the prevalence of an outcome to a univariable regression table generated with gtsummary::tbl_uvregression. Is there a way to do this without converting the tbl_uvregression object to a table and calculating it with the dplyr::mutate function as in the example below?

PS: Daniel Sjoberg, thank you for a very helpful package!

options(digits = 3)
library(gtsummary)
#> #BlackLivesMatter
library(tidyverse)
library(knitr)
library(geepack)

packageVersion("gtsummary")
#> [1] '1.5.1'

data(dietox, package = "geepack")

dietox %>%
  mutate(big_pig = if_else(Weight > 50, 1, 0)) %>%
  select(big_pig, Pig, Evit, Cu, Litter) %>%

  tbl_uvregression(
    y = big_pig,
    method = geeglm,
    method.args = list(id = Pig, family = poisson, corstr = "independence"),
    include = -Pig,
    exponentiate = TRUE
  ) %>%
  add_n(location = c("level", "label")) %>%
  add_nevent(location = c("level", "label")) %>%
  as_tibble() %>%
  mutate(Prevalence = (`**Event N**` / as.integer(`**N**`))*100) %>%
  select(`**Characteristic**`,`**N**`,`**Event N**`,Prevalence, everything()) %>%
  kable()

Characteristic
N
Event N
Prevalence
IRR
95% CI
p-value

Evit
861
519
60.3
NA
NA
NA

Evit000
276
167
60.5
NA
NA
NA

Evit100
286
178
62.2
1.03
0.95, 1.12
0.5

Evit200
299
174
58.2
0.96
0.88, 1.05
0.4

Cu
861
519
60.3
NA
NA
NA

Cu000
274
164
59.9
NA
NA
NA

Cu035
300
176
58.7
0.98
0.91, 1.06
0.6

Cu175
287
179
62.4
1.04
0.96, 1.13
0.3

Litter
861
519
60.3
NA
NA
NA

1
48
31
64.6
NA
NA
NA

2
36
25
69.4
1.08
0.99, 1.17
0.091

3
48
25
52.1
0.81
0.64, 1.02
0.077

4
48
29
60.4
0.94
0.86, 1.01
0.10

5
36
25
69.4
1.08
0.90, 1.28
0.4

6
48
31
64.6
1.00
0.93, 1.08
>0.9

7
24
12
50.0
0.77
0.61, 0.98
0.035

8
48
28
58.3
0.90
0.75, 1.08
0.3

9
33
18
54.5
0.84
0.72, 0.99
0.043

10
36
24
66.7
1.03
0.98, 1.09
0.3

11
36
20
55.6
0.86
0.78, 0.95
0.002

12
36
21
58.3
0.90
0.78, 1.04
0.2

13
36
21
58.3
0.90
0.86, 0.95
<0.001

16
48
32
66.7
1.03
0.93, 1.14
0.5

17
36
24
66.7
1.03
0.98, 1.09
0.3

18
36
21
58.3
0.90
0.86, 0.95
<0.001

20
48
30
62.5
0.97
0.89, 1.05
0.5

21
48
30
62.5
0.97
0.79, 1.19
0.8

22
48
27
56.2
0.87
0.74, 1.03
0.11

23
48
24
50.0
0.77
0.63, 0.95
0.016

24
36
21
58.3
0.90
0.86, 0.95
<0.001

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
A gtsummary table contains an internal data frame called .$table_body, and you can modify that data frame directly using the modify_table_body() function. In the example below, I calculate the prevalence and format the results to display in the table. I also expose the already existing column exposure, which is the sum of the exposure/followup time. Happy Programming!

library(gtsummary)
library(tidyverse)
library(geepack)

packageVersion("gtsummary")
#> [1] '1.5.2'

data(dietox, package = "geepack")

tbl <-
  dietox %>%
  mutate(big_pig = if_else(Weight > 50, 1, 0)) %>%
  select(big_pig, Pig, Evit, Cu) %>%
  tbl_uvregression(
    y = big_pig,
    method = geeglm,
    method.args = list(id = Pig, family = poisson, corstr = "independence"),
    include = -Pig,
    exponentiate = TRUE
  ) %>%
  add_n(location = c("level", "label")) %>%
  add_nevent(location = c("level", "label")) %>%
  # calculate prev
  modify_table_body(
    ~.x %>%
      mutate(
        prev = stat_nevent / stat_n * 100
      ) %>%
      relocate(prev, exposure, .after = stat_nevent)
  ) %>%
  # format the newly added stats
  modify_header(prev = "**Prevalence**", exposure = "**Total Exposure Time**") %>%
  modify_fmt_fun(list(prev = function(x) paste0(style_sigfig(x), "%"),
                      exposure = style_sigfig))

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
(DB first)I have added one more tables in database after Scaffold. Now trying to add those tables into my model in Entity Framework Core
I have tried it, but it create a master context do not add any new tables into model.

```<code>Scaffold-DbContext "Server=localhost;Database=master;Trusted_Connection=True;"
         Microsoft.EntityFrameworkCore.SqlServer
         -OutputDir Models -Tables OrderDetails -f
</code>```

Please help.

答:
In the scaffold command you show, you're scaffolding the Master database. That's probably not your application database, or at least it shouldn't be. Master is a system database, and your application should have its own database.

You could add the new tables manually as EF core model classes.

Body:
I have tried it, but it create a master context do not add any new tables into model.

Scaffold-DbContext "Server=localhost;Database=master;Trusted_Connection=True;"
         Microsoft.EntityFrameworkCore.SqlServer
         -OutputDir Models -Tables OrderDetails -f

Please help.


问:
Is it safe to store access token in next-auth session?
What I want is to access the customer details in the client side in next.js and I need to pass the customer access token to the backend API. Using next-auth, I was able to store the access token to the session but is it safe or is it better to use the next.js api route and use getToken function? I'm still a beginner in frontend security, I don't know if I'm just being a paranoid but I can't find a topic/post that states it is completely safe.

答:
So by default the session strategy is set to jwt, which means your session is encoded / signed and safe to store sensitive info in.

However, NextAuth.js can be used to automatically put that accessToken you get from your OAuth provider in the JWT token via the jwt callback. Therefore you can pull it out anywhere with the getToken() method you mentioned and authenticate against Google APIs for further use (get drive contents, contacts, etc, etc, etc).

Check out this example for how to do that in the jwt callback: https://github.com/nextauthjs/next-auth-refresh-token-example/blob/57f84dbc50f30233d4ee389c7239212858ecae14/pages/api/auth/%5B...nextauth%5D.js#L67


问:
Regex - add new field between semicolon separators - notepad++
I have data like this (some of the fields have values, some of them don't)

```<code>J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE
</code>```

I need to add a new field right before the 5th semicolon, like this (the F value):

```<code>J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE
</code>```

So far I have this:

```<code>^(([A-Z]);([0-9A-Z]+);([?:0-9]);([0-9\-]+);([A-Z0-9]+));(.*)$
</code>```

And as replacement:

```<code>$1;$2;F;$7
</code>```

As far as I know the ?: before is to mark optional, but in my case I need to represent empty fields between every semicolon

How can I solve this?

答:
const regex = /^([A-Z]);([0-9]*);([0-9]*);([0-9-]*);([0-9]*);(.*)$/

let str = 'J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
str = str.replace(regex, '$1;$2;$3;$4;$5;F;$6')
let expected = 'J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
console.log(str === expected)

str = 'J;;3;1990-02-19;;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
str = str.replace(regex, '$1;$2;$3;$4;$5;F;$6')
expected = 'J;;3;1990-02-19;;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
console.log(str === expected)```
</div>
</div>
</p>
<p>You can find an explanation on Regex101</p>
<p>Basically, I made use of <code>*</code> which matches from zero to unlimited times to account for instances with missing values.</p>
```^([A-Z]);([0-9]*);([0-9]*);([0-9-]*);([0-9]*);(.*)$
```

Description

([A-Z]) Match any A-Z character

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

(.*) Matches any character between zero and unlimited times

Body:
I have data like this (some of the fields have values, some of them don't)

J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE

I need to add a new field right before the 5th semicolon, like this (the F value):

J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE

So far I have this:

^(([A-Z]);([0-9A-Z]+);([?:0-9]);([0-9\-]+);([A-Z0-9]+));(.*)$

And as replacement:

$1;$2;F;$7

As far as I know the ?: before is to mark optional, but in my case I need to represent empty fields between every semicolon

How can I solve this?

Body:
const regex = /^([A-Z]);([0-9]*);([0-9]*);([0-9-]*);([0-9]*);(.*)$/

let str = 'J;555;3;1990-02-19;1234;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
str = str.replace(regex, '$1;$2;$3;$4;$5;F;$6')
let expected = 'J;555;3;1990-02-19;1234;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
console.log(str === expected)

str = 'J;;3;1990-02-19;;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
str = str.replace(regex, '$1;$2;$3;$4;$5;F;$6')
expected = 'J;;3;1990-02-19;;F;S;2020-10-17;;;;;value;3;ANOTHERVALUE'
console.log(str === expected)

You can find an explanation on Regex101

Basically, I made use of * which matches from zero to unlimited times to account for instances with missing values.

^([A-Z]);([0-9]*);([0-9]*);([0-9-]*);([0-9]*);(.*)$

Description

([A-Z]) Match any A-Z character

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

([0-9]*) Match any number between zero and unlimited times

; Matches a semi-colon literally

(.*) Matches any character between zero and unlimited times


问:
ASP.NET MVC 3.0 Razor Twitter helper slowing down pageload
I am using Twitter helper from Microsoft.Web.Helpers http://twitterhelper.codeplex.com/

But it is a bit delaying page load, so i am wondering is it possible to load the scripts of that helper after page is ready?

For example Twitter.Search("Hot Tweets") produce this scripts:

SCRIPTS:

```<code><script type="text/javascript" src="http://widgets.twimg.com/j/2/widget.js"/>
<script type="text/javascript">
new TWTR.Widget({
  version: 2,
  type: 'search',
  search: 'Hot Tweets',
  interval: 6000,
  title: '',
  subject: '',
  width: 250,
  height: 300,
  theme: {
    shell: {
      background: '#8ec1da',
      color: '#ffffff'
    },
    tweets: {
      background: '#ffffff',
      color: '#444444',
      links: '#1985b5'
    }
  },
  features: {
    scrollbar: false,
    loop: true,
    live: true,
    hashtags: true,
    timestamp: true,
    avatars: true,
    toptweets: true,
    behavior: 'default'
  }
}).render().start();
</script>
</code>```

And than that scripts producing this html:

HTML:

```<code><div class="twtr-widget twtr-paused" id="twtr-widget-1">
<div class="twtr-doc" style="width: 250px;">
<div class="twtr-hd">
<div class="twtr-bd">
<div class="twtr-ft">
</div>
</div>
</div>
</code>```

But it is not allowing to generate scripts separate so i would wrap them in to $(document).ready()

I can just split that code copy paste scripts and html separately....sounds a bit silly. So i am just wondering may be some one may suggest something more clever?

答:
Using defer  will cause your scripts to be run after the document has been parsed and loaded.

```<code><script type="text/javascript" src="http://widgets.twimg.com/j/2/widget.js" defer></script>
<script type="text/javascript" defer>
    new TWTR.Widget({
        version: 2,
...
</code>```

http://www.hunlock.com/blogs/Deferred_Javascript

Body:
I am using Twitter helper from Microsoft.Web.Helpers http://twitterhelper.codeplex.com/

But it is a bit delaying page load, so i am wondering is it possible to load the scripts of that helper after page is ready?

For example Twitter.Search("Hot Tweets") produce this scripts:

SCRIPTS:

And than that scripts producing this html:

HTML:

But it is not allowing to generate scripts separate so i would wrap them in to $(document).ready()

I can just split that code copy paste scripts and html separately....sounds a bit silly. So i am just wondering may be some one may suggest something more clever?

Body:
Using defer <script type='text/javascript' defer src=''></script> will cause your scripts to be run after the document has been parsed and loaded.

<script type="text/javascript" src="http://widgets.twimg.com/j/2/widget.js" defer></script>
<script type="text/javascript" defer>
    new TWTR.Widget({
        version: 2,
...

http://www.hunlock.com/blogs/Deferred_Javascript


问:
Nextauth requires a SECRET property
After checking the documentation it says that .env or [..nextAuth.js] file you should set a secret property in the configuration.

Error documentation to nextAuth

.env

```<code>NEXTAUTH_URL = "http://localhost:3000"
NEXTAUTH_SECRET_KEY="test"
</code>```

[...nextAuth.js]

```<code>  secret: "test",
  jwt: {
    secret: "test",
    encryption: true,
    maxAge: 5 * 60,
  },
  pages: {
    signIn: "/auth/login",
  },
</code>```

However, this is a requirement only if you are in production, but I am not.
How to fix this error and set it on development, not in production?

答:
Yeah the new environment variable is called simply NEXTAUTH_SECRET.

Also when this is set, you can avoid setting the secret and jwt.secret values separately in the configuration.

Title: Nextauth requires a SECRET property

Body:
After checking the documentation it says that .env or [..nextAuth.js] file you should set a secret property in the configuration.

Error documentation to nextAuth

.env

NEXTAUTH_URL = "http://localhost:3000"
NEXTAUTH_SECRET_KEY="test"

[...nextAuth.js]

  secret: "test",
  jwt: {
    secret: "test",
    encryption: true,
    maxAge: 5 * 60,
  },
  pages: {
    signIn: "/auth/login",
  },

However, this is a requirement only if you are in production, but I am not.
How to fix this error and set it on development, not in production?


问:
Wrong Images loading in some of tableView.dequeueReusableCell
I have the following code for my tableView:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        // Reset the image in the cell
        cell.coverImageView.image = nil

        // Get the recipe that the tableView is asking about
        let recipeInTable = recipe[indexPath.row]

        cell.displayRecipe(recipe: recipeInTable, indexPathRow: indexPath.row)

        return cell
    }
</code>```

This is my custom cell class, where I am caching the image data to pull from:

```<code>class CustomCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var coverImageView: UIImageView!

    var recipeToDisplay:Recipe?
    var recipeToPullFrom:Recipe!

    func displayRecipe(recipe:Recipe, indexPathRow:Int) {

        recipeToPullFrom = recipe

        DispatchQueue.main.async {
            self.titleLabel.text = self.recipeToPullFrom.title

            if self.recipeToPullFrom.image == nil {
                return
            }
            else {
                let urlString = self.recipeToPullFrom.image

                if let imageData = CacheManager.retrieveData(urlString!) {

                    self.coverImageView.image = UIImage(data: imageData)
                    return
                }

                let url = URL(string: urlString!)

                guard url != nil else {
                    print("Could not create url object")
                    return
                }

                let session = URLSession.shared

                let dataTask = session.dataTask(with: url!) { (data, response, error) in

                    if error == nil && data != nil  {

                        CacheManager.saveData(urlString!, data!)

                        if self.recipeToPullFrom.image == urlString {
                            DispatchQueue.main.async {
                                // Display the image data in the imageView
                                self.coverImageView.image = UIImage(data: data!)
                            }
                        }
                        DispatchQueue.main.async {
                            self.coverImageView.image = UIImage(data: data!)
                        }
                    } // End if

                } // End dataTask

                // Kick off the dataTask
                dataTask.resume()
            }
        }
    }
}
</code>```

And finally my Cache Manager:

```<code>class CacheManager {

    static var imageDictionary = [String:Data]()

    static func saveData(_ url:String, _ imageData:Data) {
        // Save the image data along with the url
        imageDictionary[url] = imageData
    }

    static func retrieveData(_ url:String) -> Data? {
        // Return the saved imageData or nil
        return imageDictionary[url]
    }
}
</code>```

From what I've researched, adding the following in my tableView function should have reset the image in my cell before inputting a new one: cell.coverImageView.image = nil.

Is there something I'm missing? I've also noticed that only my images are showing in the wrong cells. Could I be doing something incorrect with retrieving the image data from cache?

Any direction or support is much appreciated!

答:
I don't think that you need here an asynchronously call especially, when you using .main in other .main. But If you what so you what so make some thing like

```<code>DispatchQueue.global(qos: .userInteractive).async {
    // Never do here ui code - label, view, images.. anything; or would crash
    DispatchQueue.main.async {
        // To do here you ui updates
    }
}
</code>```

here is some refactored code with reuse method. I agree with
Hach3m. U need to cancel requests if you don't it anymore, when next cell is about to shown

```<code>class CustomCell: UITableViewCell {
        @IBOutlet private weak var titleLabel: UILabel!
        @IBOutlet private weak var coverImageView: UIImageView!

        private var dataTask: URLSessionDataTask?

        func displayRecipe(recipe: Recipe, indexPathRow: Int) {
            titleLabel.text = recipe.title enter code here
            guard let urlString = recipe.image else { return }

            if let imageData = CacheManager.retrieveData(urlString) {
                coverImageView.image = UIImage(data: imageData)
                return
            }

            guard let url = URL(string: urlString) else { return print("Could not create url object") }

            dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in
                guard let data = data else { return self.clear() }
                CacheManager.saveData(urlString, data)
                self.coverImageView.image = UIImage(data: data)
            }

            dataTask?.resume()
        }

        override func prepareForReuse() {
            super.prepareForReuse()
            clear()
        }

        private func clear() {
            dataTask?.cancel()
            dataTask = nil
        }
    }
}
</code>```

Body:
I have the following code for my tableView:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        // Reset the image in the cell
        cell.coverImageView.image = nil

        // Get the recipe that the tableView is asking about
        let recipeInTable = recipe[indexPath.row]

        cell.displayRecipe(recipe: recipeInTable, indexPathRow: indexPath.row)

        return cell
    }

This is my custom cell class, where I am caching the image data to pull from:

class CustomCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var coverImageView: UIImageView!

    var recipeToDisplay:Recipe?
    var recipeToPullFrom:Recipe!

    func displayRecipe(recipe:Recipe, indexPathRow:Int) {

        recipeToPullFrom = recipe

        DispatchQueue.main.async {
            self.titleLabel.text = self.recipeToPullFrom.title

            if self.recipeToPullFrom.image == nil {
                return
            }
            else {
                let urlString = self.recipeToPullFrom.image

                if let imageData = CacheManager.retrieveData(urlString!) {

                    self.coverImageView.image = UIImage(data: imageData)
                    return
                }

                let url = URL(string: urlString!)

                guard url != nil else {
                    print("Could not create url object")
                    return
                }

                let session = URLSession.shared

                let dataTask = session.dataTask(with: url!) { (data, response, error) in

                    if error == nil && data != nil  {

                        CacheManager.saveData(urlString!, data!)

                        if self.recipeToPullFrom.image == urlString {
                            DispatchQueue.main.async {
                                // Display the image data in the imageView
                                self.coverImageView.image = UIImage(data: data!)
                            }
                        }
                        DispatchQueue.main.async {
                            self.coverImageView.image = UIImage(data: data!)
                        }
                    } // End if

                } // End dataTask

                // Kick off the dataTask
                dataTask.resume()
            }
        }
    }
}

And finally my Cache Manager:

class CacheManager {

    static var imageDictionary = [String:Data]()

    static func saveData(_ url:String, _ imageData:Data) {
        // Save the image data along with the url
        imageDictionary[url] = imageData
    }

    static func retrieveData(_ url:String) -> Data? {
        // Return the saved imageData or nil
        return imageDictionary[url]
    }
}

From what I've researched, adding the following in my tableView function should have reset the image in my cell before inputting a new one: cell.coverImageView.image = nil.

Is there something I'm missing? I've also noticed that only my images are showing in the wrong cells. Could I be doing something incorrect with retrieving the image data from cache?

Any direction or support is much appreciated!

Body:
I don't think that you need here an asynchronously call especially, when you using .main in other .main. But If you what so you what so make some thing like

DispatchQueue.global(qos: .userInteractive).async {
    // Never do here ui code - label, view, images.. anything; or would crash
    DispatchQueue.main.async {
        // To do here you ui updates
    }
}

here is some refactored code with reuse method. I agree with
Hach3m. U need to cancel requests if you don't it anymore, when next cell is about to shown

class CustomCell: UITableViewCell {
        @IBOutlet private weak var titleLabel: UILabel!
        @IBOutlet private weak var coverImageView: UIImageView!

        private var dataTask: URLSessionDataTask?

        func displayRecipe(recipe: Recipe, indexPathRow: Int) {
            titleLabel.text = recipe.title enter code here
            guard let urlString = recipe.image else { return }

            if let imageData = CacheManager.retrieveData(urlString) {
                coverImageView.image = UIImage(data: imageData)
                return
            }

            guard let url = URL(string: urlString) else { return print("Could not create url object") }

            dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in
                guard let data = data else { return self.clear() }
                CacheManager.saveData(urlString, data)
                self.coverImageView.image = UIImage(data: data)
            }

            dataTask?.resume()
        }

        override func prepareForReuse() {
            super.prepareForReuse()
            clear()
        }

        private func clear() {
            dataTask?.cancel()
            dataTask = nil
        }
    }
}


问:
Simple Small Multiplication table program in Python
```<code>rows = int(input("Enter number: "))

print('1\t2\t3')
print('********************')
for i in range(1,rows+1):
    print(i*1,end='')
    print('\t',i*2,end='')
    print('\t',i*3)
</code>```

Usually end=""    makes not jumping in a new line. But with under print('\t',i*2,end=''). Everything is in vertical line . And I want it to be this way . But i dont get it if end="" makes it al    horizonal why is it vertical?

Body:
rows = int(input("Enter number: "))

print('1\t2\t3')
print('********************')
for i in range(1,rows+1):
    print(i*1,end='')
    print('\t',i*2,end='')
    print('\t',i*3)

Usually end=""    makes not jumping in a new line. But with under print('\t',i*2,end=''). Everything is in vertical line . And I want it to be this way . But i dont get it if end="" makes it al    horizonal why is it vertical?

Body:
Consider using f-strings to align the columns dynamically:

num_rows = int(input('Enter number: '))
num_cols = 3
align = '<'
col_gap = 1
col_width = len(str(num_rows * num_cols)) + col_gap
print(''.join(f'{c:{align}{col_width}}' for c in range(1, num_cols+1)))
print('*' * (col_width * num_cols - col_gap))
for r in range(1, num_rows+1):
    print(''.join(f'{r*c:{align}{col_width}}' for c in range(1, num_cols+1)))

Example Usage 1:

Enter number: 12
1  2  3
********
1  2  3
2  4  6
3  6  9
4  8  12
5  10 15
6  12 18
7  14 21
8  16 24
9  18 27
10 20 30
11 22 33
12 24 36

Example Usage 2:

Enter number: 123
1   2   3
***********
1   2   3
2   4   6
3   6   9
4   8   12
5   10  15
6   12  18
7   14  21
8   16  24
9   18  27
10  20  30
11  22  33
12  24  36
13  26  39
14  28  42
15  30  45
16  32  48
17  34  51
18  36  54
19  38  57
20  40  60
21  42  63
22  44  66
23  46  69
24  48  72
25  50  75
26  52  78
27  54  81
28  56  84
29  58  87
30  60  90
31  62  93
32  64  96
33  66  99
34  68  102
35  70  105
36  72  108
37  74  111
38  76  114
39  78  117
40  80  120
41  82  123
42  84  126
43  86  129
44  88  132
45  90  135
46  92  138
47  94  141
48  96  144
49  98  147
50  100 150
51  102 153
52  104 156
53  106 159
54  108 162
55  110 165
56  112 168
57  114 171
58  116 174
59  118 177
60  120 180
61  122 183
62  124 186
63  126 189
64  128 192
65  130 195
66  132 198
67  134 201
68  136 204
69  138 207
70  140 210
71  142 213
72  144 216
73  146 219
74  148 222
75  150 225
76  152 228
77  154 231
78  156 234
79  158 237
80  160 240
81  162 243
82  164 246
83  166 249
84  168 252
85  170 255
86  172 258
87  174 261
88  176 264
89  178 267
90  180 270
91  182 273
92  184 276
93  186 279
94  188 282
95  190 285
96  192 288
97  194 291
98  196 294
99  198 297
100 200 300
101 202 303
102 204 306
103 206 309
104 208 312
105 210 315
106 212 318
107 214 321
108 216 324
109 218 327
110 220 330
111 222 333
112 224 336
113 226 339
114 228 342
115 230 345
116 232 348
117 234 351
118 236 354
119 238 357
120 240 360
121 242 363
122 244 366
123 246 369


问:
Node.js child_process module with git command
First, Please understand that it's not smooth because I use a translator.

I want to create an API server using the child_process module in node.js to send git command.
ex) git clone ..., git pull, git push , ...

And i succeeded!

But there's a big problem here. ;(

```<code>execSync(cmd, {stdio: 'inherit', cwd: cwd});
</code>```

This is my code.

'npm start' And use this API.

Logs are displayed in the cmd window.

It is displayed in the log like this, but I can't allocate it as a variable in my node code. Like stdout, stderr.

If you don't use '{stdio: 'inherit'}' this option, you're successfully assigned to the variable.

But I want to show the log of the server and assign it to the variables.

How can we catch two rabbits?

答:
This would print the log (stdout), and the log is assigned to data.</p>
```<code>const childProcess = require("child_process");
const git = childProcess.exec("git pull");

git.stdout.on("data", data => {
   console.log(`Git replied: ${data}`);
});
// Git replied: Already up to date.
</code>```

Body:
First, Please understand that it's not smooth because I use a translator.

I want to create an API server using the child_process module in node.js to send git command.
ex) git clone ..., git pull, git push , ...

And i succeeded!

But there's a big problem here. ;(

execSync(cmd, {stdio: 'inherit', cwd: cwd});

This is my code.

'npm start' And use this API.

Logs are displayed in the cmd window.

It is displayed in the log like this, but I can't allocate it as a variable in my node code. Like stdout, stderr.

If you don't use '{stdio: 'inherit'}' this option, you're successfully assigned to the variable.

But I want to show the log of the server and assign it to the variables.

How can we catch two rabbits?

Body:
This would print the log (stdout), and the log is assigned to data.

const childProcess = require("child_process");
const git = childProcess.exec("git pull");

git.stdout.on("data", data => {
   console.log(`Git replied: ${data}`);
});
// Git replied: Already up to date.


问:
How to solve this Arabic language problem in Sybase PowerBuilder 6 and 7?
How to view arabic characters correctly in Sybase PowerBuilder 6 or 7 as I use Arial(Arabic) or any arabic language in the properties of the table and the database but it shows the characters as strange symbols that has no meaning like ÓíÇÑÉ ÕÛíÑÉ ?</p>

答: This problem is called Mojibake and it's due to the PowerBuilder client and the database using different character encodings. This problem is frequently encountered on the web, and also in email. As Terry suggested, you would get the best results using Unicode in the database and PowerBuilder. If that's not possible, you have to use the same code page on the PowerBuilder client as in the database. A complicating issue is that it sounds like you have existing data. If you want to switch encoding you would have to convert the existing data to the new encoding.</p>