问:
GitHub commits aren't recorded in the 'Your Contributions` calendar
I've been making continuous commits to my GitHub repos from my linux shell and they show up nicely on the website just as they should. The only problem is that "Your Contributions" section doesn't show any recent activity. I have one green square from some day in November which I don't know how I got but all the other contributions don't show up in the calendar (but again, they do  show up in their repos.

What am I missing here?

My github site

答:
The "Contributions Calendar" or "Activity overview" on github is only recording the commits that are related to the mail address that is recorded in the github account.

Change the mail address for all future commits

As already noted by many others in this thread, look up the current locally saved email address by:

```<code>git config user.email
</code>```

If it doesn't match the mail on github, change using:

```<code>git config --global user.email my_email@gmail.com
</code>```

This will globally change the mail address for all future commits but will not affect the "Contributions Overview" for the past ones. You can follow the official docs for an extended description.

Change the mail address to update the overview for the past commits

You realize that many of your past commits have not been recorded correctly in the Github "Contributions Overview":

To change that, you can change the author info for the repositories by following the steps explained in the official github docs.

A short summary:

Open git bash

Clone a bare repository

```<code>git clone --bare https://github.com/user/repo.git
cd repo.git
</code>```

Paste the following code into the git bash console after changing the variables OLD_EMAIL, CORRECT_NAME and CORRECT_EMAIL:

```<code>#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
</code>```

Press enter to run the script

Push the corrected history to github

```<code>git push --force --tags origin 'refs/heads/*'
</code>```

This procedure should update the "Contributions Overview" and now also show the commits not shown before:

Warning: This action is destructive to your repository's history. If you're collaborating on a repository with others, it's considered bad practice to rewrite published history. You should only do this in an emergency.

Body:
The "Contributions Calendar" or "Activity overview" on github is only recording the commits that are related to the mail address that is recorded in the github account.

Change the mail address for all future commits

As already noted by many others in this thread, look up the current locally saved email address by:

git config user.email

If it doesn't match the mail on github, change using:

git config --global user.email my_email@gmail.com

This will globally change the mail address for all future commits but will not affect the "Contributions Overview" for the past ones. You can follow the official docs for an extended description.

Change the mail address to update the overview for the past commits

You realize that many of your past commits have not been recorded correctly in the Github "Contributions Overview":

To change that, you can change the author info for the repositories by following the steps explained in the official github docs.

A short summary:

Open git bash

Clone a bare repository

git clone --bare https://github.com/user/repo.git
cd repo.git

Paste the following code into the git bash console after changing the variables OLD_EMAIL, CORRECT_NAME and CORRECT_EMAIL:

#!/bin/sh

git filter-branch --env-filter '

OLD_EMAIL="your-old-email@example.com"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="your-correct-email@example.com"

if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

Press enter to run the script

Push the corrected history to github

git push --force --tags origin 'refs/heads/*'

This procedure should update the "Contributions Overview" and now also show the commits not shown before:

Warning: This action is destructive to your repository's history. If you're collaborating on a repository with others, it's considered bad practice to rewrite published history. You should only do this in an emergency.


来源: stackexchange

问:
Create a string from object array
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
```

<p>I want to loop through the array and print the following:</p>

<ol>
<li>If product 1, output <code>you have 2 One Plus</code></li>
<li>If product 2, output <code>you have 1 One Plus and 1 Apple</code></li>
</ol>

<p>Below is the code that I tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);</code>```

I’m able to get the JSON output, but how can I get it in the sentence format?

答:
const product1 = [
  {Brand: "One Plus"},
  {Brand: "One Plus"},
];
const product2 = [
  {Brand: "One Plus"},
  {Brand: "Apple"},
];

function whatYouHaveIn(list) {
  return `You have ` + Object.entries(list.reduce((a, c) => {
    a[c.Brand] = a[c.Brand] || 0;
    a[c.Brand]++;
    return a;
  }, {})).map(([brand, count]) => `${count} ${brand}`).join(` and `);
}

console.log(whatYouHaveIn(product1));

console.log(whatYouHaveIn(product2));```

ContentLicense: CC BY-SA 4.0

Title: Create a string from object array

Body:
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

If product 1, output you have 2 One Plus

If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?


问:
I wanted to convert the following C# Code to Python Code
Friends how to convert the following C# code to Python:</p>

```<code>class BaseClass {
    //some member(s)
}

class DerivedClass : BaseClass {
   //some member(s)
}

class Program {
    public static void Main(){
        BaseClass bc = new DerivedClass();
    }
}
</code>```

答: If you are a C# programmer, and want an introduction to Python, there are several resources on the net. A quick search found a presentaton with good examples, including conversions of class declarations (just search for class in the PDF). Multiple other resources are bound to exist, just search for them.

Body:
Friends how to convert the following C# code to Python:

class BaseClass {
    //some member(s)
}

class DerivedClass : BaseClass {
   //some member(s)
}

class Program {
    public static void Main(){
        BaseClass bc = new DerivedClass();
    }
}


问:
Python: for each row, get next earlier date where value > 0
Trying to get current or past date where value was > 0. Will use this to calculate number of days since the value was > 0. In the case where date has value, then it will be 0 days.

Sample data and desired results shown below. Data is 'date' and 'value' column, and results are last two columns.

```<code>date        value   'date value > 0'    'days since value > 0'
2020-04-30  0       2020-04-28           2
2020-04-29  0       2020-04-28           1
2020-04-28  1       2020-04-28           0
2020-03-31  6       2020-03-31           0
2020-03-30  1       2020-03-30           0
2020-03-29  3       2020-03-29           0
2020-02-29  0       2020-01-29           31
2020-01-31  0       2020-01-29           2
2020-01-30  0       2020-01-29           1
2020-01-29  1       2020-01-29           0
</code>```

The data format could be either a dictionary or dataframe. I am importing from csv and will export back to csv.

Logic: for each row, filter to only records where date <= current row date, then get max date of filtered dataframe that have value > 0. Max date is the 'date value > 0'.

Edit: I have been trying iterating sequentially through dataframe records eg pandas df.shift(), df.rolling(), df.iloc but stuck on how to 'look back' to get date of previous record with value > 0.

Body:
Trying to get current or past date where value was > 0. Will use this to calculate number of days since the value was > 0. In the case where date has value, then it will be 0 days.

Sample data and desired results shown below. Data is 'date' and 'value' column, and results are last two columns.

date        value   'date value > 0'    'days since value > 0'
2020-04-30  0       2020-04-28           2
2020-04-29  0       2020-04-28           1
2020-04-28  1       2020-04-28           0
2020-03-31  6       2020-03-31           0
2020-03-30  1       2020-03-30           0
2020-03-29  3       2020-03-29           0
2020-02-29  0       2020-01-29           31
2020-01-31  0       2020-01-29           2
2020-01-30  0       2020-01-29           1
2020-01-29  1       2020-01-29           0

The data format could be either a dictionary or dataframe. I am importing from csv and will export back to csv.

Logic: for each row, filter to only records where date <= current row date, then get max date of filtered dataframe that have value > 0. Max date is the 'date value > 0'.

Edit: I have been trying iterating sequentially through dataframe records eg pandas df.shift(), df.rolling(), df.iloc but stuck on how to 'look back' to get date of previous record with value > 0.

Body:
Let's assume you have a dataframe data with "date" column in datetime64 type and "value" column in int64 type:

>>> data
        date  value
0 2020-04-30      0
1 2020-04-29      0
2 2020-04-28      1
3 2020-03-31      6
4 2020-03-30      1
5 2020-03-29      3
6 2020-02-29      0
7 2020-01-31      0
8 2020-01-30      0
9 2020-01-29      1
>>> data.dtypes
date     datetime64[ns]
value             int64
dtype: object

Then you can sort the dataframe in ascending order of date, and then create a new column "prevdate" to copy the "date" column but set to NaT with the rows with value is 0, like this:

data['prevdate'] = data['date'].where(data['value'].ne(0))

and then forward fill the NaT values:

>>> data.sort_values('date', inplace=True)
>>> data['prevdate'] = data['date'].where(data['value'].ne(0)).fillna(method='ffill')
>>> data
        date  value   prevdate
9 2020-01-29      1 2020-01-29
8 2020-01-30      0 2020-01-29
7 2020-01-31      0 2020-01-29
6 2020-02-29      0 2020-01-29
5 2020-03-29      3 2020-03-29
4 2020-03-30      1 2020-03-30
3 2020-03-31      6 2020-03-31
2 2020-04-28      1 2020-04-28
1 2020-04-29      0 2020-04-28
0 2020-04-30      0 2020-04-28

Now you can simply take subtraction between the two date columns and convert the difference into integer:

>>> data['days'] = (data['date'] - data['prevdate']).apply(lambda x: x.days)
>>> data
        date  value   prevdate  days
9 2020-01-29      1 2020-01-29     0
8 2020-01-30      0 2020-01-29     1
7 2020-01-31      0 2020-01-29     2
6 2020-02-29      0 2020-01-29    31
5 2020-03-29      3 2020-03-29     0
4 2020-03-30      1 2020-03-30     0
3 2020-03-31      6 2020-03-31     0
2 2020-04-28      1 2020-04-28     0
1 2020-04-29      0 2020-04-28     1
0 2020-04-30      0 2020-04-28     2


问:
How call validate before Devise sign in?
I would like to disable user's authorization where the date the account was created_at is in 2010.

How can I use callbacks for this task and how can I use it with Devise?

答:
I think your question has 2 parts:

Based on some criteria (e.g. account creation date), you want to authorize users to perform certain actions

You want to use Devise for authentication

Note that there is a difference between authentication (you are who you say you are) and authorization (you are allowed to do what you're requesting), and they are typically implemented using different software.

For example, you can use Devise for authentication and CanCan to manage authorization (railscast on CanCan: http://asciicasts.com/episodes/192-authorization-with-cancan).

Using CanCan, you would simply allow users to perform action based on the created_at attribute for their account, and otherwise call Devise's authorize! method.

ContentLicense: CC BY-SA 3.0


问:
v-model in Toast UI editor for Vue.js
I'm trying to use the Vue.js wrapper for Toast UI and I can't get the v-model to work.

I followed this tutorial to make the following code:

import { Editor } from '@toast-ui/vue-editor'

export default {
  components: {
    editor: Editor
  },
  data () {
    return {
      editorText: 'Bloop'
    }
  },
  methods: {
    clicker () {
      alert(this.editorText)
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div>
    <editor v-model="editorText"/>
    <button @click="clicker">Submit</button>
  </div>
</template></code>```

The Toast UI editor is empty on page load. Anything typed into the editor is not saved in the "editorText" variable because the alert shows the initial value. I feel like I must be making a very simple mistake.

I would like to set the text in the editor when the page opens, and then get the markdown text from the editor when the button is pressed. Any help would be appreciated.

答:
That tutorial uses an old library (see repo). You are using this another (see repo), It doesn´t have allowed v-model, instead use initialValue:

<editor :initialValue="editorText" ref="toastuiEditor"/>
```

<p>And get html by this way: </p>

<pre class="lang-js prettyprint-override"><code>// ...
methods: {
    getHtml() {
        let html = this.$refs.toastuiEditor.invoke('getHtml');
    }
}
</code>```

Title: v-model in Toast UI editor for Vue.js

Body:
I'm trying to use the Vue.js wrapper for Toast UI and I can't get the v-model to work.

I followed this tutorial to make the following code:

import { Editor } from '@toast-ui/vue-editor'

export default {
  components: {
    editor: Editor
  },
  data () {
    return {
      editorText: 'Bloop'
    }
  },
  methods: {
    clicker () {
      alert(this.editorText)
    }
  }
}

<template>

    <editor v-model="editorText"/>
    <button @click="clicker">Submit</button>

</template>

The Toast UI editor is empty on page load. Anything typed into the editor is not saved in the "editorText" variable because the alert shows the initial value. I feel like I must be making a very simple mistake.

I would like to set the text in the editor when the page opens, and then get the markdown text from the editor when the button is pressed. Any help would be appreciated.

Body:
That tutorial uses an old library (see repo). You are using this another (see repo), It doesn´t have allowed v-model, instead use initialValue:

<editor :initialValue="editorText" ref="toastuiEditor"/>

And get html by this way:

// ...
methods: {
    getHtml() {
        let html = this.$refs.toastuiEditor.invoke('getHtml');
    }
}


问:
How to split audio, mix them and create another channel in kurento?
I am implementing a video conference app with a large number of people, and there was trouble with the internet to watch them all at the same time. I decided to create one independent audio channel, that will be listened always. Few videos should be shown, but at the same time I need to listen for all.

How to make this technique work?

I tried too many kurento examples. But about creating another channel no success. (

Sorry for my bad English.

答:
You can try kurento Composite. It merges all streams (audio/video) connected though HubPort and sends merged stream out. But Composite causes High CPU usage on Kurento Media Server.

Follow this thread

https://groups.google.com/d/msg/kurento/kXZ3CGo5WOA/q6ArbZ4HiasJ

Upvote if you found it useful.


问:
Force the generation of HTTP links in HTTPS mode
I'm using SSL in my ASP.NET MVC 3 application. Once that the user enters in HTTPS mode, all the links in the page are generated with the HTTPS preface, but I'd like to "let the user leave" the HTTPS mode, and get back to HTTP when critical information exchange has been already done.

Is there anyway in the Routes configuration or something to say something like:

```<code>/Home/Index will be always HTTP
</code>```

I've tried with:

```<code><a href="@Url.Action("Index","Home",null,"http")">Normal</a>
</code>```

But it fails when I'm using a custom port. I mean, at the beginning it is: http://127.0.0.1:5104/Home/Index but when the link is generated from HTTPS it looks: http://127.0.0.1/Home/Index and of course it doesn't work

Regards.

答:
As the user is browsing an HTTPS page, the request itself doesn't contain any information with respect to what port the HTTP binding is running on. which means that you would need to supply it yourself (it might be possible to get this value out from the IIS config file somehow).

Below is a sample helper function that allows you to specify which http port the request should be routed to.

```<code>public static string HttpAction(this UrlHelper helper, string action,
    string controller, object routeValues, int port)
{
    var url = helper.Action(action, controller, routeValues, "http");
    var uri = new Uri(url);

    var builder = new UriBuilder(uri.Scheme, uri.Host, port, uri.AbsolutePath, uri.Query);
    return builder.ToString();
}
</code>```

Usage:

```<code>@Url.HttpAction("index", "account", new { val = 5 }, 5055);
</code>```

Body:
I'm using SSL in my ASP.NET MVC 3 application. Once that the user enters in HTTPS mode, all the links in the page are generated with the HTTPS preface, but I'd like to "let the user leave" the HTTPS mode, and get back to HTTP when critical information exchange has been already done.

Is there anyway in the Routes configuration or something to say something like:

/Home/Index will be always HTTP

I've tried with:

Normal

But it fails when I'm using a custom port. I mean, at the beginning it is: http://127.0.0.1:5104/Home/Index but when the link is generated from HTTPS it looks: http://127.0.0.1/Home/Index and of course it doesn't work

Regards.

Body:
As the user is browsing an HTTPS page, the request itself doesn't contain any information with respect to what port the HTTP binding is running on. which means that you would need to supply it yourself (it might be possible to get this value out from the IIS config file somehow).

Below is a sample helper function that allows you to specify which http port the request should be routed to.

public static string HttpAction(this UrlHelper helper, string action,
    string controller, object routeValues, int port)
{
    var url = helper.Action(action, controller, routeValues, "http");
    var uri = new Uri(url);

    var builder = new UriBuilder(uri.Scheme, uri.Host, port, uri.AbsolutePath, uri.Query);
    return builder.ToString();
}

Usage:

@Url.HttpAction("index", "account", new { val = 5 }, 5055);


问:
Refering to column names inside dplyr's across()
Is it possible to refer to column names in a lambda function inside across()?

```<code>df <- tibble(age = c(12, 45), sex = c('f', 'f'))
allowed_values <- list(age = 18:100, sex = c("f", "m"))

df %>%
  mutate(across(c(age, sex),
                c(valid = ~ .x %in% allowed_values[[COLNAME]])))
</code>```

I just came across this question where OP asks about validating columns in a dataframe based on a list of allowed values.

dplyr just gained across() and it seems like a natural choice, but we need columns names to look up the allowed values.

The best I could come up with was a call to imap_dfr, but it is more cumbersome to integrate into an anlysis pipeline, because the results need to be re-combined with the original dataframe.

答:
I think that you may be asking too much of across at this point (but this may spur additional development, so maybe someday it will work the way you suggest).

I think that the imap functions from the purrr package may give you what you want at this point:

```<code>> df <- tibble(age = c(12, 45), sex = c('f', 'f'))
> allowed_values <- list(age = 18:100, sex = c("f", "m"))
>
> df %>% imap( ~ .x %in% allowed_values[[.y]])
$age
[1] FALSE  TRUE

$sex
[1] TRUE TRUE

> df %>% imap_dfc( ~ .x %in% allowed_values[[.y]])
# A tibble: 2 x 2
  age   sex
  <lgl> <lgl>
1 FALSE TRUE
2 TRUE  TRUE
</code>```

If you want a single column with the combined validity then you can pass the result through reduce:

```<code>> df %>% imap( ~ .x %in% allowed_values[[.y]]) %>%
+   reduce(`&`)
[1] FALSE  TRUE
</code>```

This could then be added as a new column to the original data, or just used for subsetting the data.  I am not expert enough with the tidyverse yet to know if this could be combined with mutate to add the columns directly.

Body:
Is it possible to refer to column names in a lambda function inside across()?

df <- tibble(age = c(12, 45), sex = c('f', 'f'))
allowed_values <- list(age = 18:100, sex = c("f", "m"))

df %>%
  mutate(across(c(age, sex),
                c(valid = ~ .x %in% allowed_values[[COLNAME]])))

I just came across this question where OP asks about validating columns in a dataframe based on a list of allowed values.

dplyr just gained across() and it seems like a natural choice, but we need columns names to look up the allowed values.

The best I could come up with was a call to imap_dfr, but it is more cumbersome to integrate into an anlysis pipeline, because the results need to be re-combined with the original dataframe.

Body:
I think that you may be asking too much of across at this point (but this may spur additional development, so maybe someday it will work the way you suggest).

I think that the imap functions from the purrr package may give you what you want at this point:

> df <- tibble(age = c(12, 45), sex = c('f', 'f'))
> allowed_values <- list(age = 18:100, sex = c("f", "m"))
>
> df %>% imap( ~ .x %in% allowed_values[[.y]])
$age
[1] FALSE  TRUE

$sex
[1] TRUE TRUE

> df %>% imap_dfc( ~ .x %in% allowed_values[[.y]])
# A tibble: 2 x 2
  age   sex
  <lgl> <lgl>
1 FALSE TRUE
2 TRUE  TRUE

If you want a single column with the combined validity then you can pass the result through reduce:

> df %>% imap( ~ .x %in% allowed_values[[.y]]) %>%
+   reduce(`&`)
[1] FALSE  TRUE

This could then be added as a new column to the original data, or just used for subsetting the data.  I am not expert enough with the tidyverse yet to know if this could be combined with mutate to add the columns directly.


答:
```<code>class BaseClass:
    //some member(s)

class DerivedClass(BaseClass):
    //some member(s)

bc=DerivedClass()
</code>```

This is just a example. For more information check this.

Title: I wanted to convert the following C# Code to Python Code

Body:
class BaseClass:
    //some member(s)

class DerivedClass(BaseClass):
    //some member(s)

bc=DerivedClass()

This is just a example. For more information check this.


问:
How to improve performance for get in Linked list?
I tried to implement a Linked list by myself and faced the question: "How I can get Node for O(1) complexity?"

Are there opportunities (or good practices) to improve "get" method? Do I need to add another data structure into Linked List? I read in some articles about using Hash Table into Linked List. Is it normal?

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  // O(1)
  addToTail(value) {
    let newNode = new Node(value);

    if (this.head === null) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  // O(n)
  get(value) {
    let cur = this.head;
    while (cur && cur.value !== value) {
      cur = cur.next;
    }

    return cur;
  }

  // O(n)
  remove(value) {
    let cur = this.head;
    let prev = null;
    while (cur && cur.value !== value) {
      prev = cur;
      cur = cur.next;
    }

    if (cur) {
      // First Node
      if (this.head === cur) {
        this.head = cur.next;
        if (this.head === null) {
          this.tail = null;
        }
      } else {
        // Not first Node
        prev.next = cur.next;

        if (cur.next === null) {
          this.tail = prev;
        }
      }

      return true;
    }

    return false;
  }

  print() {
    let cur = this.head;
    while (cur !== null) {
      console.log(cur.value);
      cur = cur.next;
    }
  }
}

const cars = ['Audio', 'BMW', 'Mazda', 'Toyota'];
const list = new LinkedList();
for (let i = 0; i < cars.length; i++) {
  list.addToTail(cars[i])
}

list.remove('Audio')
list.addToTail('Kia')
list.addToTail('Lexus')
console.log(list.get('Mazda'));```

答:
...and faced the question: "How I can get Node for O(1) complexity?"

You can't. A linked list always requires some level of scanning. A pure singly-linked list is O(n), IIRC.

I read in some articles about using Hash Table into Linked List. Is it normal?

It's not uncommon to have a map structure that does a hash of the key to find the right "bucket," where a "bucket" is a linked list or similar linearly-searched container for all of the entries whose keys hash the same. Basically, get is then:

Do the hash for the key

Look up the bucket by hash

Search in the bucket for the key

At that point, though, the overall thing isn't a linked list anymore, it's more of a map. Even a map backed by hash tables isn't O(1), though it'll be better than O(n).

(I realize you're doing this for learning purposes, but I have to point to JavaScript's native Map, which does use hashing or (quoting the spec) "...other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.")


问:
How to retrieve and display images in reactjs that are stored on the server side using multer and the path is stored in the database
I am having similar problem.I stored the path in database named Cast and the images on the server. The database has two fields name and image. In the react app,i want to display the image.I am not getting the image.
I am running express on localhost:5000 and reactjs on localhost:3000.
Ex: image in the db has the value "Anushka.jpg". On the server side it is stored as follows:

```<code>public
 └─ cast_images
     └─ Anushka.jpg
</code>```

app.js file(server side)

```<code>app.use('/login', express.static(path.join(__dirname, '/public')));
app.get('/login',(req,res)=>{
  Cast.find()
  .then(
    cast=>res.json(cast))
    .catch(err => res.status(400).json('Error: ' + err));
});
</code>```

App.js(frontend react file):

```<code>function App() {
  return (
    <Router>
    <Navbar />
    <br/>
    <Route path="/login" component={Login}/>
    </Router>
  );
}

export default App;
</code>```

Login.js

```<code>import React, { Component } from 'react';
import axios from 'axios';
export default class Login extends Component {
  state={
    casts:[]
  };
  componentDidMount() {
    axios.get('http://localhost:5000/admin/')
      .then(response => {
        this.setState({casts:response.data});
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      })
  }
    render() {
        const actor =this.state.casts.map(actor => {
          return (
             <p>
              <img src="/cast_images/{actor.image}" alt="hello"/>
              <h3>{actor.name}</h3>
            </p>
          );
        });
        return(<p>{actor}</p>);
    }
}
</code>```

I did not not mention here imports in React code.This is a part of code.Can u please tell me how to get the image.Thanks in advance.

答:
With this code you are mounting your public folder to the /login url path, I don't think that is what you want

app.use('/login', express.static(path.join(__dirname, '/public')));

So it should be changed to

```<code>app.use('/', express.static(path.join(__dirname, '/public')));
</code>```

And in React, you can use JavaScript template string literal to insert a variable inside a string.

```<code>const serverBaseURI = 'http://localhost:5000' // set this to the value of your express server, should be different value for production server
/* .... */
<img src={`${serverBaseURI}/cast_images/${actor.image}`} alt="hello"/>
</code>```

Body:
I am having similar problem.I stored the path in database named Cast and the images on the server. The database has two fields name and image. In the react app,i want to display the image.I am not getting the image.
I am running express on localhost:5000 and reactjs on localhost:3000.
Ex: image in the db has the value "Anushka.jpg". On the server side it is stored as follows:

public
 └─ cast_images
     └─ Anushka.jpg

app.js file(server side)

app.use('/login', express.static(path.join(__dirname, '/public')));
app.get('/login',(req,res)=>{
  Cast.find()
  .then(
    cast=>res.json(cast))
    .catch(err => res.status(400).json('Error: ' + err));
});

App.js(frontend react file):

function App() {
  return (
    <Router>
    <Navbar />

    <Route path="/login" component={Login}/>
    </Router>
  );
}

export default App;

Login.js

import React, { Component } from 'react';
import axios from 'axios';
export default class Login extends Component {
  state={
    casts:[]
  };
  componentDidMount() {
    axios.get('http://localhost:5000/admin/')
      .then(response => {
        this.setState({casts:response.data});
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      })
  }
    render() {
        const actor =this.state.casts.map(actor => {
          return (

{actor.name}

          );
        });
        return(
{actor}
);
    }
}

I did not not mention here imports in React code.This is a part of code.Can u please tell me how to get the image.Thanks in advance.

Body:
With this code you are mounting your public folder to the /login url path, I don't think that is what you want

app.use('/login', express.static(path.join(__dirname, '/public')));

So it should be changed to

app.use('/', express.static(path.join(__dirname, '/public')));

And in React, you can use JavaScript template string literal to insert a variable inside a string.

const serverBaseURI = 'http://localhost:5000' // set this to the value of your express server, should be different value for production server
/* .... */
<img src={`${serverBaseURI}/cast_images/${actor.image}`} alt="hello"/>


问:
Filterout empty value from objects
I have a dataset like this:

```<code>let data = {
 "00:00": [],
 "00:30": ["123"],
 "01:00: ["4560", "123"],
 "01:30": [],
 ...
 "23:30": []
}
</code>```

Now I would like to filterout those key from object whose value is not empty array.

I tried using object.key method but it will return the key name. I want key with value.

What I did is like:

```<code>let result = Object.keys(data).filter(o => data[o].length > 0);
console.log(result)
</code>```

this will return the result:

```<code>["00:30", "01:00"]
</code>```

what I expect is

```<code>[{"00:30": ["123"]}, {"01:00": ["4560", "123"]}]
</code>```

Any help is really appreciated.

答:
You could get the entries, filter by length and build a new object.

let data = { "00:00": [], "00:30": ["123"], "01:00": ["4560", "123"], "01:30": [], "23:30": [] },
    result = Object.fromEntries(Object
        .entries(data)
        .filter(({ 1: { length } }) => length)
    );

console.log(result);```

Title: Filterout empty value from objects

Body:
I have a dataset like this:

let data = {
 "00:00": [],
 "00:30": ["123"],
 "01:00: ["4560", "123"],
 "01:30": [],
 ...
 "23:30": []
}

Now I would like to filterout those key from object whose value is not empty array.

I tried using object.key method but it will return the key name. I want key with value.

What I did is like:

let result = Object.keys(data).filter(o => data[o].length > 0);
console.log(result)

this will return the result:

["00:30", "01:00"]

what I expect is

[{"00:30": ["123"]}, {"01:00": ["4560", "123"]}]

Any help is really appreciated.


问:
Print column header next to column entry if condition match
I am having a large file in the following format where 1st column is the id and then all are samples. I am trying to extract only ids for which only one sample is having value larger than 5 and remaining all have values less than 5. Additionally I also want to print the sample id along-with the sample value for which the value is greater than 5. Whats the best way to proceed it? I can identify all ids which full-fill the condition by following which I came across in the forum; but cannot get what I am expecting.

```<code> awk '{for(i=1;i<=NF;i++) {if($i+0>5) c++; printf "%-5s%s", $i, (i==NF? OFS c ORS: OFS)}c=0}' input.txt | awk 'NR==1{print $0}; NR>1{if ($NF==1) print $0}
</code>```

Input File

```<code>id      s1      s2      s3      s4      s5
T1      203     3       0       1       80
T2      70      2       0       0       1
T3      50      66      90      321     15
T4      1       4       2       1       10
T5      0       0       0       0       2
T6      2       1       2       11      2
T7      200     3       1       0       0
T8      15      11      9       8       1
T9      1       23      1       2       1
T10     34      1       1       2       1
</code>```

Expected output

```<code>T2      s1      70
T4      s5      10
T6      s4      11
T7      s1      200
T9      s2      23
T10     s1      34
</code>```

答:
Could you please try following, written on mobile couldn't test it should work but.</p>

```<code>awk '
FNR==1{
  for(k=2;k<=NF;k++){
    header[k]=$k
  }
  next
}
{
  for(k=2;k<=NF;k++){
    if($k>5){
      count++
      val=$k
      second=header[k]
    }
  }
  if(count==1){
     print $1,second,val
  }
  count=val=second=""
}
' Input_file
</code>```

Body:
I am having a large file in the following format where 1st column is the id and then all are samples. I am trying to extract only ids for which only one sample is having value larger than 5 and remaining all have values less than 5. Additionally I also want to print the sample id along-with the sample value for which the value is greater than 5. Whats the best way to proceed it? I can identify all ids which full-fill the condition by following which I came across in the forum; but cannot get what I am expecting.

 awk '{for(i=1;i<=NF;i++) {if($i+0>5) c++; printf "%-5s%s", $i, (i==NF? OFS c ORS: OFS)}c=0}' input.txt | awk 'NR==1{print $0}; NR>1{if ($NF==1) print $0}

Input File

id      s1      s2      s3      s4      s5
T1      203     3       0       1       80
T2      70      2       0       0       1
T3      50      66      90      321     15
T4      1       4       2       1       10
T5      0       0       0       0       2
T6      2       1       2       11      2
T7      200     3       1       0       0
T8      15      11      9       8       1
T9      1       23      1       2       1
T10     34      1       1       2       1

Expected output

T2      s1      70
T4      s5      10
T6      s4      11
T7      s1      200
T9      s2      23
T10     s1      34

Body:
Could you please try following, written on mobile couldn't test it should work but.

awk '
FNR==1{
  for(k=2;k<=NF;k++){
    header[k]=$k
  }
  next
}
{
  for(k=2;k<=NF;k++){
    if($k>5){
      count++
      val=$k
      second=header[k]
    }
  }
  if(count==1){
     print $1,second,val
  }
  count=val=second=""
}
' Input_file


问:
How do I added a token to the query of a dashboard in Splunk?
I recreated the dashboard using the report query and have the search returning all of the table results.  I have an input for the reference number as a text box.  The token name is: purchCostReferenceToken

I want to limit the table results based on this token. This is the query:

```<code><form>
  <label>Thru Train Dashboard</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      <label>Enter a TMS Reference Number to Filter Table</label>
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train Data</title>
      <table>
        <search>
          <query>index=... "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time</query>
          <earliest>-30d@d</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>
</code>```

Where do I add the token to limit the search?
I tried adding this to the end of the query before the table command:

```<code>...   | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) purchCostReference=$purchCostReferenceToken$ | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time
</code>```

I get an error...error in convert command: the argument purchCostReference- is invalid

I would like to add filters in several of the table columns.  The purchCostReference value is an extracted field in the query using xmlkv

答:
Technically, a token can be placed anywhere in a query, but the query has to be valid when the token is replaced with its value.  convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) purchCostReference=4 is not valid SPL.

If the field referenced by the token is extracted automatically then it's usually best to put the token in the base search.  That's not the case here.

You should use a search or where command to filter events based on the token value.  Something like xmlkv | search purchCostReference=$purchCostReferenceToken$.

Body:
I recreated the dashboard using the report query and have the search returning all of the table results.  I have an input for the reference number as a text box.  The token name is: purchCostReferenceToken

I want to limit the table results based on this token. This is the query:

<form>
  Thru Train Dashboard
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      Enter a TMS Reference Number to Filter Table
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train Data</title>

        <search>
          <query>index=... "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time</query>
          <earliest>-30d@d</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>

    </panel>
  </row>
</form>

Where do I add the token to limit the search?
I tried adding this to the end of the query before the table command:

...   | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) purchCostReference=$purchCostReferenceToken$ | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time

I get an error...error in convert command: the argument purchCostReference- is invalid

I would like to add filters in several of the table columns.  The purchCostReference value is an extracted field in the query using xmlkv


问:
In Java, is it possible to declare a field that can never become null?
Let's assume we define this Book class where we ensure that isbn can never be assigned a null value:

public class Book {

  private String isbn;

  public Book(String isbn) {
    setIsbn(isbn);
  }

  public void setIsbn(String isbn) {
    if (isbn == null) {
      throw new NullPointerException();
    }

    this.isbn = isbn;
  }

  public String getIsbn() {
    return this.isbn;
  }

}
```

This prevents creation of a Book object where isbn is null but after a book object with a non-null isbn is created, we can modify the value via reflection and set it to null.

Is there anyway (using a trick or a Java feature) to prevent an instance of Book to ever exist in the memory where its isbn is null?

NB: this question is not about Optionals.

答:
Technically references are nullable. Even though you can use final to make sure that the compiler won't let you leave a variable null, you can use reflection to remove its finality and set it to null.

If you count out reflection, then let's say native code or Unsafe or bytecode instrumentation or so on and so on. In the end, the internal representation allows nulls, so depending on how far you'll go there'll be a way to make a variable null if you really want to, unless you specify constraints about what's allowed/possible, such as whether a SecurityManager is involved.

If you're asking the question because you're afraid that your variable isn't safe enough from NullPointerExceptions, then using final, Objects.requireNonNull() and good design is enough.

Body:
Let's assume we define this Book class where we ensure that isbn can never be assigned a null value:

public class Book {

  private String isbn;

  public Book(String isbn) {
    setIsbn(isbn);
  }

  public void setIsbn(String isbn) {
    if (isbn == null) {
      throw new NullPointerException();
    }

    this.isbn = isbn;
  }

  public String getIsbn() {
    return this.isbn;
  }

}

This prevents creation of a Book object where isbn is null but after a book object with a non-null isbn is created, we can modify the value via reflection and set it to null.

Is there anyway (using a trick or a Java feature) to prevent an instance of Book to ever exist in the memory where its isbn is null?

NB: this question is not about Optionals.


问:
Weird bug when changing boolean number to classify dataframe
I have a dataframe where I am trying to add some boolean constraints that are numbers.

```<code>hrw_hotdry=combined_hrw[(combined_hrw['June_anom']<0) & (combined_hrw['June_anom_t'])>0]
hrw_hotdry.head()

Year    June_val    June_anom   July_val    July_anom   June_val_t  June_anom_t July_val_t  July_anom_t
0   1980    2.14    -1.40   0.99    -2.11   76.7    2.6 83.7    5.0
1   1981    2.85    -0.69   4.01    0.91    75.5    1.4 79.1    0.4
8   1988    2.08    -1.46   3.22    0.12    76.2    2.1 77.5    -1.2
10  1990    1.88    -1.66   3.16    0.06    77.3    3.2 76.7    -2.0
11  1991    3.13    -0.41   2.69    -0.41   75.1    1.0 78.4    -0.3
</code>```

However, when I change the second constraint to 1 like this:

```<code>hrw_hotdry=combined_hrw[(combined_hrw['June_anom']<0) & (combined_hrw['June_anom_t'])>1]
hrw_hotdry.head()

Year    June_val    June_anom   July_val    July_anom   June_val_t  June_anom_t July_val_t  July_anom_t
</code>```

There is no output. How does this make sense?

Body:
I have a dataframe where I am trying to add some boolean constraints that are numbers.

hrw_hotdry=combined_hrw[(combined_hrw['June_anom']<0) & (combined_hrw['June_anom_t'])>0]
hrw_hotdry.head()

Year    June_val    June_anom   July_val    July_anom   June_val_t  June_anom_t July_val_t  July_anom_t
0   1980    2.14    -1.40   0.99    -2.11   76.7    2.6 83.7    5.0
1   1981    2.85    -0.69   4.01    0.91    75.5    1.4 79.1    0.4
8   1988    2.08    -1.46   3.22    0.12    76.2    2.1 77.5    -1.2
10  1990    1.88    -1.66   3.16    0.06    77.3    3.2 76.7    -2.0
11  1991    3.13    -0.41   2.69    -0.41   75.1    1.0 78.4    -0.3

However, when I change the second constraint to 1 like this:

hrw_hotdry=combined_hrw[(combined_hrw['June_anom']<0) & (combined_hrw['June_anom_t'])>1]
hrw_hotdry.head()

Year    June_val    June_anom   July_val    July_anom   June_val_t  June_anom_t July_val_t  July_anom_t

There is no output. How does this make sense?

Body:
Parentheses were incorrect:

hrw_hotdry = combined_hrw[(combined_hrw['June_anom']<0) & (combined_hrw['June_anom_t']>1.0)]

    Year  June_val  June_anom  July_val  July_anom  June_val_t  June_anom_t  July_val_t  July_anom_t
0   1980      2.14      -1.40      0.99      -2.11        76.7          2.6        83.7          5.0
1   1981      2.85      -0.69      4.01       0.91        75.5          1.4        79.1          0.4
8   1988      2.08      -1.46      3.22       0.12        76.2          2.1        77.5         -1.2
10  1990      1.88      -1.66      3.16       0.06        77.3          3.2        76.7         -2.0


问:
Problems drawing Windows 10 Caption Buttons
I'm having problems drawing Windows 10 themed Window Caption Buttons using the VisualStyleRenderer class.

My problem is that I can't figure out which Theme Class to use.
I tried Window and CompositedWindow::Window, however, none of those actually contain Windows 10 themed buttons as I found out using this msstyle editor.

Which Theme Class contains Windows 10 themed Caption Buttons?

How it looks now:

How I want it to look:

How I'm drawing the buttons:

```<code>protected override void OnPaint(PaintEventArgs e)
{
    VisualStyleRenderer renderer = new VisualStyleRenderer("Window", 18 /*WP_CLOSEBUTTON*/, 1 /*CBS_NORMAL*/);
    var size = renderer.GetPartSize(e.Graphics, ThemeSizeType.True);
    renderer.DrawBackground(e.Graphics, new System.Drawing.Rectangle(10, 10, size.Width, size.Height));
}
</code>```

答:
The problem is the Window class you are using. This is the legacy GDI Window that is composited without a composition engine.

The DWM Desktop Window Manager composites every window, as every window is just a DirectX surface. You need to use the DWMWindow class as opposed to the Window class from aero.msstyles.

Notice how there are multiple glyphs for each DPI: 96, 120, 144, etc.

Body:
I'm having problems drawing Windows 10 themed Window Caption Buttons using the VisualStyleRenderer class.

My problem is that I can't figure out which Theme Class to use.
I tried Window and CompositedWindow::Window, however, none of those actually contain Windows 10 themed buttons as I found out using this msstyle editor.

Which Theme Class contains Windows 10 themed Caption Buttons?

How it looks now:

How I want it to look:

How I'm drawing the buttons:

protected override void OnPaint(PaintEventArgs e)
{
    VisualStyleRenderer renderer = new VisualStyleRenderer("Window", 18 /*WP_CLOSEBUTTON*/, 1 /*CBS_NORMAL*/);
    var size = renderer.GetPartSize(e.Graphics, ThemeSizeType.True);
    renderer.DrawBackground(e.Graphics, new System.Drawing.Rectangle(10, 10, size.Width, size.Height));
}


问:
Automatically Detect When a User Verifies Email
I have a website built with the Laravel framework. When a user creates a new account, they are immediately taken to their dashboard with a message telling them to check their email for a verification link. All buttons on the dashboard are disabled until they verify their email.

I would like the dashboard page to automatically detect when a user verifies their email, and then immediately enable the buttons without the user having to manually refresh the page after verification. How can I do this?

答:
One way would be to have an API endpoint where you can add user information (id, email, bla bla) and it returns either true or false. Make a request to that endpoint every so often (maybe use some form of backoff such as https://en.wikipedia.org/wiki/Exponential_backoff like if it fails try after one second, then if it fails try after ten seconds, ... ) to avoid overloading the backend.

keep the UI disabled until you get a positive response from the backend.

that being said, you might need to add this check on every action a user can take depending on business requirement because you can never (completely) trust the client


问:
I have an error "incompatible type" with the PreparedStatement
```<code>import java.sql.*;
import java.io.*;
public class preparedstatementdemo
    {
    public static void main(String arg[]) throws Exception
        {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:yoksource","","");
        String Sqlcmd="insert into yokrecord values(?,?,?)";
    **    PreparedStatement ps=con.prepareStatement(Sqlcmd);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a name");
        ps.setString(1,br.readLine());
        System.out.println("Enter age");
        ps.setInt(2,Integer.parseInt(br.readLine()));
        System.out.println("enter address");
        ps.setString(3,br.readLine());
        ps.executeUpdate();
        System.out.println("inserted");
        }
    }
</code>```

<p>** error :incompatible type </p>

答:
I believe the problem is with the actual INSERT command you use -- the syntax shold be:

```<code>INSERT INTO yokrecord (fieldname1,fieldname2,fieldname3) values(?,?,?);
</code>```

Body:
import java.sql.*;
import java.io.*;
public class preparedstatementdemo
    {
    public static void main(String arg[]) throws Exception
        {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:yoksource","","");
        String Sqlcmd="insert into yokrecord values(?,?,?)";
    **    PreparedStatement ps=con.prepareStatement(Sqlcmd);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a name");
        ps.setString(1,br.readLine());
        System.out.println("Enter age");
        ps.setInt(2,Integer.parseInt(br.readLine()));
        System.out.println("enter address");
        ps.setString(3,br.readLine());
        ps.executeUpdate();
        System.out.println("inserted");
        }
    }

** error :incompatible type

Body:
I believe the problem is with the actual INSERT command you use -- the syntax shold be:

INSERT INTO yokrecord (fieldname1,fieldname2,fieldname3) values(?,?,?);


问:
Create a CSV file of a 2D matrix of zeros using bash, or tiniest bit of python where not possible in bash
This is for a numerical data science application. I need to create a matrix of zeros, in a file, separated by commas (within a line) and ending with newline (at end of each line). This bash code was the closest:

```<code>l=`python -c "print(f'{\"0, \" * 9}0')"`  # 10 zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
</code>```

That’s fine as far as it goes, until you try to change the two literals 9 and 3 to shell variables. However, it is difficult (to me) to code it correctly to replace literal 9 with a shell variable n=9. I tried using bash and python but still not working.
For example these two different attempts don’t actually work (for me) with variables:

```<code>l=$(printf '0,%.0s' {1..$((n-1))}; printf '0')  # 100% bash code
yes $l | head -n $k  # print line 3 times
0,0
0,0
0,0

l=`python -c "print(f'{\"0, \" * 9}0')"`  # using a bit of python, 10 literal zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
</code>```

In this case, changing literal 9 to variable in the python was even worse, and gave me something crazy, like some kind of directory listing, which I definitely don’t want.

答:
Just a slight variation on your approach:

n=10
k=3
yes "$(yes 0 | head -n "$n" | paste -s -d,)" | head -n "$k"
```

And if blanks after the commas are required, piping to sed 's/,/, /g' would do that.

Body:
This is for a numerical data science application. I need to create a matrix of zeros, in a file, separated by commas (within a line) and ending with newline (at end of each line). This bash code was the closest:

l=`python -c "print(f'{\"0, \" * 9}0')"`  # 10 zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0

That’s fine as far as it goes, until you try to change the two literals 9 and 3 to shell variables. However, it is difficult (to me) to code it correctly to replace literal 9 with a shell variable n=9. I tried using bash and python but still not working.
For example these two different attempts don’t actually work (for me) with variables:

l=$(printf '0,%.0s' {1..$((n-1))}; printf '0')  # 100% bash code
yes $l | head -n $k  # print line 3 times
0,0
0,0
0,0

l=`python -c "print(f'{\"0, \" * 9}0')"`  # using a bit of python, 10 literal zeros comma separated in one line
yes $l | head -n 3  # print line 3 times
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0

In this case, changing literal 9 to variable in the python was even worse, and gave me something crazy, like some kind of directory listing, which I definitely don’t want.

Body:
Just a slight variation on your approach:

n=10
k=3
yes "$(yes 0 | head -n "$n" | paste -s -d,)" | head -n "$k"

And if blanks after the commas are required, piping to sed 's/,/, /g' would do that.


问:
Create a string from object array
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];
```

<p>I want to loop through the array and print the following:</p>

<ol>
<li>If product 1, output <code>you have 2 One Plus</code></li>
<li>If product 2, output <code>you have 1 One Plus and 1 Apple</code></li>
</ol>

<p>Below is the code that I tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);</code>```

I’m able to get the JSON output, but how can I get it in the sentence format?

答:
You first have to count the occurances,
than its just a matter of string concat or templates

function strinify(a) {
  let occurances = {};

  a.forEach(function(e,i){
   if( e.Brand in occurances ) {
    occurances[e.Brand] ++;
   } else {
    occurances[e.Brand] = 1;
   }
  });

  let str = [];

  for( brand in occurances ){
    count = occurances[brand];
    str.push(count + " " + brand);
  };

  return "you have " + str.join(" and ");
}

console.log(strinify([
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
]));```

Title: Create a string from object array

Body:
I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

If product 1, output you have 2 One Plus

If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?


问:
How to set the tab bar badge with swift?
How to set the tab bar badge with swift ? for example when I get new message  showing number 1 on the message icon !
Do I have to use the UITabBarItem.swift and write the code in it !
I'm not really sure how I can do it

Thank you !

答:
One can also set an empty string for the badge value to get a red circle if desired:

```<code>tabBarController?.tabBar.items?.last?.badgeValue = ""
</code>```

Body:
One can also set an empty string for the badge value to get a red circle if desired:

tabBarController?.tabBar.items?.last?.badgeValue = ""


问:
extracting all fields from a Lucene8 index
Given an index created with Lucene-8, but without knowledge of the fields used, how can I programmatically extract all the fields? (I'm aware that the Luke browser can be used interactively (thanks to @andrewjames) Examples for using latest version of Lucene. ) The scenario is that, during a development phase, I have to read indexes without prescribed schemas.
I'm using

```<code>IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
IndexSearcher searcher = new IndexSearcher(reader);
</code>```

The reader has methods such as:

```<code>reader.getDocCount(field);
</code>```

but this requires knowing the fields in advance.

I understand that documents in the index may be indexed with different fields; I'm quite prepared to iterate over all documents and extract the fields on a regular basis (these indexes are not huge).

I'm using Lucene 8.5.* so post and tutorials based on earlier Lucene versions may not work.

答:
You can access basic field info as follows:</p>

```<code>import java.util.List;
import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.store.FSDirectory;

public class IndexDataExplorer {

    private static final String INDEX_PATH = "/path/to/index/directory";

    public static void doSearch() throws IOException {
        IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));
        for (int i = 0; i < reader.numDocs(); i++) {
            Document doc = reader.document(i);
            List<IndexableField> fields = doc.getFields();
            for (IndexableField field : fields) {
                // use these to get field-related data:
                //field.name();
                //field.fieldType().toString();
            }
        }
    }
}
</code>```

Body:
Given an index created with Lucene-8, but without knowledge of the fields used, how can I programmatically extract all the fields? (I'm aware that the Luke browser can be used interactively (thanks to @andrewjames) Examples for using latest version of Lucene. ) The scenario is that, during a development phase, I have to read indexes without prescribed schemas.
I'm using

IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
IndexSearcher searcher = new IndexSearcher(reader);

The reader has methods such as:

reader.getDocCount(field);

but this requires knowing the fields in advance.

I understand that documents in the index may be indexed with different fields; I'm quite prepared to iterate over all documents and extract the fields on a regular basis (these indexes are not huge).

I'm using Lucene 8.5.* so post and tutorials based on earlier Lucene versions may not work.

Body:
You can access basic field info as follows:

import java.util.List;
import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.store.FSDirectory;

public class IndexDataExplorer {

    private static final String INDEX_PATH = "/path/to/index/directory";

    public static void doSearch() throws IOException {
        IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));
        for (int i = 0; i < reader.numDocs(); i++) {
            Document doc = reader.document(i);
            List<IndexableField> fields = doc.getFields();
            for (IndexableField field : fields) {
                // use these to get field-related data:
                //field.name();
                //field.fieldType().toString();
            }
        }
    }
}


问:
`flip` function implementation in JavaScript?
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

```<code>const funcName = (arg1) => (arg2) => (arg3) => { ... }
</code>```

I want it turns to:

```<code>const funcName = (arg2) => (arg1) => (arg3) => { ... }
</code>```

And like this:

```<code>const funcName = (arg3) => (arg2) => (arg1) => { ... }
</code>```

答:
A simple thing to do would be:

const flip = (fn) => (arg1, arg2) => fn(arg2, arg1);

const reverse = (fn) => (...args) => fn(...args.reverse());

const log = reverse(console.log.bind(null));

log('Giuseppe', 'is', 'name', 'my');```

Body:
Anyone please share the implementation of flip function in JavaScript. What I need is to reverse the first and the second parameters of a function.

Let's assume I have:

const funcName = (arg1) => (arg2) => (arg3) => { ... }

I want it turns to:

const funcName = (arg2) => (arg1) => (arg3) => { ... }

And like this:

const funcName = (arg3) => (arg2) => (arg1) => { ... }


问:
How to collect elements of a collection basing on a result of some method?
Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:

```<code>val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")

val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)
</code>```

However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?

答:
If you base it on an Option return, then this works:

```<code>order flatMap (map get)
</code>```

Though, of course, order collect map is enough in this particular example.

Body:
Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:

val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")

val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)

However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?

Body:
If you base it on an Option return, then this works:

order flatMap (map get)

Though, of course, order collect map is enough in this particular example.


答:
If you want to rule out reflection, the answer is no.

The only option you have is, installing a security manager which disallows reflection, but in which hostile environment do you expect your code to run? And even then, the user who starts the VM could add an agent, which can manipulate the bytecode.

So, as total security is concerned: no.

Title: In Java, is it possible to declare a field that can never become null?


问:
How to save a text as .txt file via a downloadable link?
HTML newbie here

I am working on an app using Streamlit. Based on the user inputs to the fields available, I am generating some data which I want to download in the form of a .txt file.

The data that I want to download is generated when I do

```<code>to_save = abc.serialize().encode("ascii", "ignore")
</code>```

and when I do print(to_save), I get (this is just a small part of a very huge text data)

b"UNA:+.?
  'UNB+UNOC:3+9978715000006:14+9978715000006:14+200529:1139+50582307060_WP?+_200101_200201++TL'UNH+1+MSCONS:D:04B:UN:2.3'BGM+7+50582307060_WP?+_200101_200201-1+9'DTM+137:202005291139:203'RFF+Z13:13008'NAD+MS+9978715000006::9'CTA+IC+:Michael
  Jordan'COM+m.jordan@energycortex.com:EM'NAD+MR+9978715000006::9'"

Now, I want to save this information as a .txt file via an HTML link. I am following:

How to download a file in Streamlit

How to force fully download txt file on link?

and I have

```<code>reference = 50582307060_WP+_200101_200201
to_save = abc.serialize().encode("ascii", "ignore")
href = f'<a href="data:text/plain;charset=UTF-8,{to_save}" download={reference}.txt>Download File</a> (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)
</code>```

But this doesn't work and shows as follows:

The start

The end

and when I do:

```<code>to_save = abc.serialize().encode("ascii", "ignore")
href = f'<a href="data:text/plain;charset=UTF-8" download={reference}.txt>Download File</a> (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)
</code>```

I get

The problem with this being that the information that has to be saved as a .txt file (to_save = abc.serialize().encode("ascii", "ignore")) isn't being saved and I get a Failed-Network error

What is the mistake that I am doing and how can I enable saving the information stored in to_save (to_save = abc.serialize().encode("ascii", "ignore")) as an HTML downloadable link? Also, the file should be saved as 'reference.txt', with reference being defined as a variable above.

答:
I reckon I have found a solution to your problem. Though I can't be entirely sure, it has two causes. The first one lies in the href attribute of the download link. The problem here is the " (double quotes) in the to_save variables data. The html, for what I could test with the by you provided data, renders it as follows:

Download File

```

<p>As you can see the value of the <code>href</code> attribute isn't all in the blue color (here in the stackoverflow code container above). That is because of the <code>"</code> that interrupt the string, it closes the earlier opened <code>"</code> after <code>href="</code>. In order to prevent this behaviour, you should replace the <code>"</code> in <code>to_save</code> with <code>"</code>. To the user this will look the same as <code>"</code> but the browser will treat it like a normal string. </p>

<p>You should add the following line of code to your python script to make that happen</p>

<pre class="lang-py prettyprint-override"><code>to_save = abc.serialize().encode("ascii", "ignore")
#add this line:
to_save = to_save.replace('"','"')
</code>```

Next the download attribute doesn't have any double quotes around it's value. It should, formally, look like this: download="filename.txt". Then again, for safety replace any possible"with"`.

The full python code should now look like this:

reference = 50582307060_WP+_200101_200201
reference = reference.replace('"','"')

to_save = abc.serialize().encode("ascii", "ignore")
to_save = to_save.replace('"','"')

href = f'Download File (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)

```

Hope this helps! If not, please comment.

Body:
HTML newbie here

I am working on an app using Streamlit. Based on the user inputs to the fields available, I am generating some data which I want to download in the form of a .txt file.

The data that I want to download is generated when I do

to_save = abc.serialize().encode("ascii", "ignore")

and when I do print(to_save), I get (this is just a small part of a very huge text data)

b"UNA:+.?
  'UNB+UNOC:3+9978715000006:14+9978715000006:14+200529:1139+50582307060_WP?+_200101_200201++TL'UNH+1+MSCONS:D:04B:UN:2.3'BGM+7+50582307060_WP?+_200101_200201-1+9'DTM+137:202005291139:203'RFF+Z13:13008'NAD+MS+9978715000006::9'CTA+IC+:Michael
  Jordan'COM+m.jordan@energycortex.com:EM'NAD+MR+9978715000006::9'"

Now, I want to save this information as a .txt file via an HTML link. I am following:

How to download a file in Streamlit

How to force fully download txt file on link?

and I have

reference = 50582307060_WP+_200101_200201
to_save = abc.serialize().encode("ascii", "ignore")
href = f'Download File (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)

But this doesn't work and shows as follows:

The start

The end

and when I do:

to_save = abc.serialize().encode("ascii", "ignore")
href = f'Download File (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)

I get

The problem with this being that the information that has to be saved as a .txt file (to_save = abc.serialize().encode("ascii", "ignore")) isn't being saved and I get a Failed-Network error

What is the mistake that I am doing and how can I enable saving the information stored in to_save (to_save = abc.serialize().encode("ascii", "ignore")) as an HTML downloadable link? Also, the file should be saved as 'reference.txt', with reference being defined as a variable above.

Body:
I reckon I have found a solution to your problem. Though I can't be entirely sure, it has two causes. The first one lies in the href attribute of the download link. The problem here is the " (double quotes) in the to_save variables data. The html, for what I could test with the by you provided data, renders it as follows:

<a href="data:text/plain;charset=UTF-8,b"UNA:+.? 'UNB+UNOC:3+9978715000006:14+9978715000006:14+200529:1139+50582307060_WP?+_200101_200201++TL'UNH+1+MSCONS:D:04B:UN:2.3'BGM+7+50582307060_WP?+_200101_200201-1+9'DTM+137:202005291139:203'RFF+Z13:13008'NAD+MS+9978715000006::9'CTA+IC+:Michael Jordan'COM+m.jordan@energycortex.com:EM'NAD+MR+9978715000006::9'"" download=filename.txt>Download File</a>

As you can see the value of the href attribute isn't all in the blue color (here in the stackoverflow code container above). That is because of the " that interrupt the string, it closes the earlier opened " after href=". In order to prevent this behaviour, you should replace the " in to_save with &quot;. To the user this will look the same as " but the browser will treat it like a normal string.

You should add the following line of code to your python script to make that happen

to_save = abc.serialize().encode("ascii", "ignore")
#add this line:
to_save = to_save.replace('"','&quot;')

Next the download attribute doesn't have any double quotes around it's value. It should, formally, look like this: download="filename.txt". Then again, for safety replace any possible"with"`.

The full python code should now look like this:

reference = 50582307060_WP+_200101_200201
reference = reference.replace('"','&quot;')

to_save = abc.serialize().encode("ascii", "ignore")
to_save = to_save.replace('"','&quot;')

href = f'<a href="data:text/plain;charset=UTF-8,{to_save}" download="{reference}.txt">Download File</a> (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)

Hope this helps! If not, please comment.


问:
Inserting special characters to mysql database
I am building a basic web application which searches through a mysql database using a simple php script to retrieve results based on a few checkboxes on the page, everything is working except the database handling.

The problem seems to be happening when i try to fill my database, i have a few thousand entries but here's a single example.

The input:
INSERT INTO example_database.test_table (testcolumn) values ("LÆRER");

Seems to run without a problem, but when i try to select all items from the table it gets returned without the "Æ" character
In console i get;>"LRER", In the web browser the character is presented as �, "L�RER"
I have tried altering both the database and table specifically for UTF-8 with no luck.

NOTE: The lowercase equivalent "æ" DOES work.
I am running a LAMP stack on Ubuntu 16.04.

mysql -V and php -v;

```<code>mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper
PHP 7.0.33-0ubuntu0.16.04.14 (cli) ( NTS )
</code>```

EDIT:

I have come to a diagnosis of sorts, after "opening" or entering mysql> the console stops recognizing the character upon input, at least it doesn't display anything as having been input. Still no idea how to fix it though.

答: Ended up figuring it out, it was an issue with the MySQL "shell"(?)/client not accepting the characters. I ended up making a separate page on my site with just a simple textbox input that I populated my tables with, after which everything worked fine. This isn't really a solution to the actual problem, but more of a workaround.</p>

Body:
I am building a basic web application which searches through a mysql database using a simple php script to retrieve results based on a few checkboxes on the page, everything is working except the database handling.

The problem seems to be happening when i try to fill my database, i have a few thousand entries but here's a single example.

The input:
INSERT INTO example_database.test_table (testcolumn) values ("LÆRER");

Seems to run without a problem, but when i try to select all items from the table it gets returned without the "Æ" character
In console i get;>"LRER", In the web browser the character is presented as �, "L�RER"
I have tried altering both the database and table specifically for UTF-8 with no luck.

NOTE: The lowercase equivalent "æ" DOES work.
I am running a LAMP stack on Ubuntu 16.04.

mysql -V and php -v;

mysql  Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using  EditLine wrapper
PHP 7.0.33-0ubuntu0.16.04.14 (cli) ( NTS )

EDIT:

I have come to a diagnosis of sorts, after "opening" or entering mysql> the console stops recognizing the character upon input, at least it doesn't display anything as having been input. Still no idea how to fix it though.


问:
Google Script to check sheet column values
I have a google sheet with a formula in each cell of column B that returns "Y" or "N" using an IF formula based on a certain condition.

What I would like to do is create a google script that runs hourly (via installable trigger) and searches column B for all rows with "Y" in the cells.  I then want it to take those rows and pull the values from column C, then use those values to push through another function using the value from C for that row and return the result in column D for that row and then repeat for every row where "Y" was found in column B. Based on searches in Stack, I found this code which will search the column. But I cant figure out how to use the data to pull the value from the adjacent column C to push through my other function and then return the result back in Column D. Also when running a simple test on this code, it looks like its only running for row 2 and not searching any other row in the sheet.

```<code>    function onSearch()
{
    var searchString = "Y";
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of DataFinal");
    var column =2; //column Index
    var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row
    var searchResult = columnValues.findIndex(searchString); //Row Index - 2

    if(searchResult != -1)
    {
        //searchResult + 2 is row index.
        SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 3)).setValue("found here");
    }
</code>```

This is the code that I want to include under the search script to then push the values from the found rows (with "Y") through and return the result from another function (shown below) back into column D.

```<code>    var timedis = gettime(value) \\ this is where i would take the value from column C push it through my other function
      o.setValue(timedis). \\ the result of gettime (timedis) is what i woudld like to put in column D in the same row and then repeat for all rows where "Y" was found in B.
}

    function gettime(f) {
      \\my other function script would go here. No help needed on this part.

    return timedis
    }
</code>```

答:
You can use a regular for loop to go through the whole column and do what you need:

function onSearch() {
  var searchString = "Y";
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of DataFinal");
  var column = 2; //column Index
  // start getRange at 2 to skip header row
  var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues().flat();

  for (let valuesIdx = 0; valuesIdx < columnValues.length; valuesIdx++) {
    if (columnValues[valuesIdx] === searchString) {
      // row number is valuesIdx + 2 because of skipping header row
      // and because rows in getRange are 1-indexed
      nextColVal = sheet.getRange(valuesIdx + 2, column + 1).getValue();
      let timedis = gettime(nextColVal);
      sheet.getRange(valuesIdx + 2, column + 2).setValue(timedis);
    }
  }
}
```

Body:
I have a google sheet with a formula in each cell of column B that returns "Y" or "N" using an IF formula based on a certain condition.

What I would like to do is create a google script that runs hourly (via installable trigger) and searches column B for all rows with "Y" in the cells.  I then want it to take those rows and pull the values from column C, then use those values to push through another function using the value from C for that row and return the result in column D for that row and then repeat for every row where "Y" was found in column B. Based on searches in Stack, I found this code which will search the column. But I cant figure out how to use the data to pull the value from the adjacent column C to push through my other function and then return the result back in Column D. Also when running a simple test on this code, it looks like its only running for row 2 and not searching any other row in the sheet.

    function onSearch()
{
    var searchString = "Y";
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of DataFinal");
    var column =2; //column Index
    var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row
    var searchResult = columnValues.findIndex(searchString); //Row Index - 2

    if(searchResult != -1)
    {
        //searchResult + 2 is row index.
        SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 3)).setValue("found here");
    }

This is the code that I want to include under the search script to then push the values from the found rows (with "Y") through and return the result from another function (shown below) back into column D.

    var timedis = gettime(value) \\ this is where i would take the value from column C push it through my other function
      o.setValue(timedis). \\ the result of gettime (timedis) is what i woudld like to put in column D in the same row and then repeat for all rows where "Y" was found in B.
}

    function gettime(f) {
      \\my other function script would go here. No help needed on this part.

    return timedis
    }


问:
empty screen while running my random numbers program
I'd like to write a basic program which is generating random numbers that are different from each other but when I run the program I always see a empty screen. I think there is a logical error where I check the numbers that they're not similar with each others and then stuck in "for" loop. Could you examine my code? Thanks..

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace denemeTahtasi2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[7];

            Random random = new Random();
            for (int i = 0; i < numbers.Length; i++)
            {
            c:
                numbers[i] = random.Next(1, 50);
                for (int j = 0; j < numbers.Length; j++)
                {
                    if (numbers[i] == numbers[j])
                    {
                        goto c;
                    }
                }
            }
            foreach (var item in numbers)
            {
                Console.Write(item + " ");
            }
            Console.ReadLine();
        }
    }
}

</code>```

note: Yes, I know I can do it using .contains method but I want to figure it out whats wrong with this program.

答:
The problem is that you have an endless loop. Both i and j start out at 0, so when you do if (numbers[i] == numbers[j]), it will always return true because you're looking at the same index. Then you hit the goto statement and do it all over again.

To fix this, add an if condition to skip the comparison if i and j are the same index:

```<code>for (int i = 0; i < numbers.Length; i++)
{
    c:
    numbers[i] = random.Next(1, 50);
    for (int j = 0; j < numbers.Length; j++)
    {
        // If i and j are the same index, skip the comparison
        if (i == j) continue;

        if (numbers[i] == numbers[j])
        {
            goto c;
        }
    }
}
</code>```

Additionally, since we don't need to look at any numbers after index i, we can improve the code slightly by limiting j to numbers that are less than i. In this way, we no longer need the comparison, since j will always be less than i:

```<code>for (int i = 0; i < numbers.Length; i++)
{
    c:
    numbers[i] = random.Next(1, 50);

    // Only compare indexes that are before this one
    // (since we haven't set any after this one yet)
    for (int j = 0; j < i; j++)
    {
        if (numbers[i] == numbers[j])
        {
            goto c;
        }
    }
}
</code>```

Body:
I'd like to write a basic program which is generating random numbers that are different from each other but when I run the program I always see a empty screen. I think there is a logical error where I check the numbers that they're not similar with each others and then stuck in "for" loop. Could you examine my code? Thanks..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace denemeTahtasi2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[7];

            Random random = new Random();
            for (int i = 0; i < numbers.Length; i++)
            {
            c:
                numbers[i] = random.Next(1, 50);
                for (int j = 0; j < numbers.Length; j++)
                {
                    if (numbers[i] == numbers[j])
                    {
                        goto c;
                    }
                }
            }
            foreach (var item in numbers)
            {
                Console.Write(item + " ");
            }
            Console.ReadLine();
        }
    }
}

note: Yes, I know I can do it using .contains method but I want to figure it out whats wrong with this program.

Body:
The problem is that you have an endless loop. Both i and j start out at 0, so when you do if (numbers[i] == numbers[j]), it will always return true because you're looking at the same index. Then you hit the goto statement and do it all over again.

To fix this, add an if condition to skip the comparison if i and j are the same index:

for (int i = 0; i < numbers.Length; i++)
{
    c:
    numbers[i] = random.Next(1, 50);
    for (int j = 0; j < numbers.Length; j++)
    {
        // If i and j are the same index, skip the comparison
        if (i == j) continue;

        if (numbers[i] == numbers[j])
        {
            goto c;
        }
    }
}

Additionally, since we don't need to look at any numbers after index i, we can improve the code slightly by limiting j to numbers that are less than i. In this way, we no longer need the comparison, since j will always be less than i:

for (int i = 0; i < numbers.Length; i++)
{
    c:
    numbers[i] = random.Next(1, 50);

    // Only compare indexes that are before this one
    // (since we haven't set any after this one yet)
    for (int j = 0; j < i; j++)
    {
        if (numbers[i] == numbers[j])
        {
            goto c;
        }
    }
}


问:
Flask - allowing users into a group of projects, based on project being a variable and an @app.route id
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

```<code>@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))
</code>```

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

```<code>Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'
</code>```

Any help is much appreciated. Thank you.

答:
Wrap the @roles_accepted decorator with another decorator! In the code below the variable name to extract the role is being passed in the outer decorator although it could be hard-coded.

```<code>def roles_accepted_from_route(variable_name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _variable = kwargs.get(variable_name, None)
            if _variable:
                print(_variable, _variable[:3])

                @roles_accepted('admin', _variable[:3])
                def inner_wrapper(*args, **kwargs):
                    print(f'roles_accepted returned True, variable: {_variable[:3]}')
                    return func(*args, **kwargs)
                return inner_wrapper(*args, **kwargs)

        return wrapper

    return decorator
</code>```

And use as follows:

```<code>@app.route('/<string:_id>')
@roles_accepted_from_route(variable_name='_id')
def some_route(_id):
    return f'Route Variable: {_id}'
</code>```

Single file example below, there is little error checking. A user with email: 'fred@example.net', password: 'password' with role 'LON' is created on the first Flask request.

```<code>from functools import wraps
from flask import Flask
from flask_security import roles_accepted
from flask_security.utils import hash_password
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, current_user

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db3'
app.config['SECURITY_PASSWORD_SALT'] = '5ce39dc7add2284076de45b923d74dd00a052117cdf0ab900548565681e56fce'

# Create database connection object
db = SQLAlchemy(app)

# Define models
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

# Create a user to test with
@app.before_first_request
def create_user():
    db.drop_all()
    db.create_all()
    _lon_role = user_datastore.create_role(name='LON')
    _user = user_datastore.create_user(email='fred@example.net', password=hash_password('password'))
    user_datastore.add_role_to_user(_user, _lon_role)
    db.session.commit()

def roles_accepted_from_route(variable_name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _variable = kwargs.get(variable_name, None)
            if _variable:
                print(_variable, _variable[:3])

                @roles_accepted('admin', _variable[:3])
                def inner_wrapper(*args, **kwargs):
                    print(f'roles_accepted returned True, variable: {_variable[:3]}')
                    return func(*args, **kwargs)
                return inner_wrapper(*args, **kwargs)

        return wrapper

    return decorator

@app.route('/')
def home():
    if current_user.is_authenticated:
        return f'You are logged in as : {current_user.email} and have roles: {",".join([r.name for r in current_user.roles])}'
    else:
        return f'<a href="/login">Login</a>'

@app.route('/<string:_id>')
@roles_accepted_from_route(variable_name='_id')
def some_route(_id):
    return f'Route Variable: {_id}'

if __name__ == '__main__':
    app.run()
</code>```

Body:
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'

Any help is much appreciated. Thank you.

Body:
Wrap the @roles_accepted decorator with another decorator! In the code below the variable name to extract the role is being passed in the outer decorator although it could be hard-coded.

def roles_accepted_from_route(variable_name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _variable = kwargs.get(variable_name, None)
            if _variable:
                print(_variable, _variable[:3])

                @roles_accepted('admin', _variable[:3])
                def inner_wrapper(*args, **kwargs):
                    print(f'roles_accepted returned True, variable: {_variable[:3]}')
                    return func(*args, **kwargs)
                return inner_wrapper(*args, **kwargs)

        return wrapper

    return decorator

And use as follows:

@app.route('/<string:_id>')
@roles_accepted_from_route(variable_name='_id')
def some_route(_id):
    return f'Route Variable: {_id}'

Single file example below, there is little error checking. A user with email: 'fred@example.net', password: 'password' with role 'LON' is created on the first Flask request.

from functools import wraps
from flask import Flask
from flask_security import roles_accepted
from flask_security.utils import hash_password
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, current_user

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db3'
app.config['SECURITY_PASSWORD_SALT'] = '5ce39dc7add2284076de45b923d74dd00a052117cdf0ab900548565681e56fce'

# Create database connection object
db = SQLAlchemy(app)

# Define models
roles_users = db.Table('roles_users',
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

# Create a user to test with
@app.before_first_request
def create_user():
    db.drop_all()
    db.create_all()
    _lon_role = user_datastore.create_role(name='LON')
    _user = user_datastore.create_user(email='fred@example.net', password=hash_password('password'))
    user_datastore.add_role_to_user(_user, _lon_role)
    db.session.commit()

def roles_accepted_from_route(variable_name):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            _variable = kwargs.get(variable_name, None)
            if _variable:
                print(_variable, _variable[:3])

                @roles_accepted('admin', _variable[:3])
                def inner_wrapper(*args, **kwargs):
                    print(f'roles_accepted returned True, variable: {_variable[:3]}')
                    return func(*args, **kwargs)
                return inner_wrapper(*args, **kwargs)

        return wrapper

    return decorator

@app.route('/')
def home():
    if current_user.is_authenticated:
        return f'You are logged in as : {current_user.email} and have roles: {",".join([r.name for r in current_user.roles])}'
    else:
        return f'<a href="/login">Login</a>'

@app.route('/<string:_id>')
@roles_accepted_from_route(variable_name='_id')
def some_route(_id):
    return f'Route Variable: {_id}'

if __name__ == '__main__':
    app.run()


问:
Python27 binary MSB LSB manipulate
I've got this simple question that i can't crack.
I do a readout from a chip that gives med MSB and LSB using SMBus in Python2.7.

I need to remove the 2 first bit in MSB and then combine it with the last 8 bit fron LSB.

Like:

```<code>MSB = bus.read_byte_data(address, register_1)
LSB = bus.read_byte_data(address, register_2)
</code>```

MSB = 11110000 , LSB = 11111111

MSB_cut = 110000 , LSB = 11111111

Combined = 11000011111111

And then convert it to an integer.

I have tried with Bitwise operation but i don't get it right. I know this it quit simple, so is there someone who can show med the right code?

Thanks.

答:
Okay

i've createt this really ugly solution:

```<code>MSB = bus.read_byte_data(adress, register_1)
LSB = bus.read_byte_data(adress, register_2)
mb = bin(MSB)
lb = bin(LSB)
tot = mb[4:] + lb[2:]
total = int(tot, 2)
</code>```

I think there must a more delicate way to this. :-)

Title: Python27 binary MSB LSB manipulate

Body:
I've got this simple question that i can't crack.
I do a readout from a chip that gives med MSB and LSB using SMBus in Python2.7.

I need to remove the 2 first bit in MSB and then combine it with the last 8 bit fron LSB.

Like:

MSB = bus.read_byte_data(address, register_1)
LSB = bus.read_byte_data(address, register_2)

MSB = 11110000 , LSB = 11111111

MSB_cut = 110000 , LSB = 11111111

Combined = 11000011111111

And then convert it to an integer.

I have tried with Bitwise operation but i don't get it right. I know this it quit simple, so is there someone who can show med the right code?

Thanks.

Body:
Okay

i've createt this really ugly solution:

MSB = bus.read_byte_data(adress, register_1)
LSB = bus.read_byte_data(adress, register_2)
mb = bin(MSB)
lb = bin(LSB)
tot = mb[4:] + lb[2:]
total = int(tot, 2)

I think there must a more delicate way to this. :-)