问:
Git Hooks inside PyCharm running in incorrect environment
I have recently started a new project in PyCharm, finally utilizing anaconda environments. However, after trying to make my first commit through PyCharm, it appears to be using my native python, not the environment set in PyCharm. I've tried to restart PyCharm several times, restarted my computer, and reinstalled the virtual environment.

Here is a copy of pre-commit hook:

```<code>set -e

# Run linters and tests
source scripts/lint.sh
</code>```

The linter is the following: (which python has been added to highlight the issue)

```<code>set -e
set -v

which python

flake8 ~project name~
mypy ~project name~
pytest -x
black --check --fast --quiet ~project name~

set +v
</code>```

I am running the commit through PyCharm -> VCS -> Commit. Inside PyCharm, the commit fails

(below this are a large amount of mypy errors, but note the environment)

However, if I run the commit from the terminal with $ git commit -m "testing commit" the commit works. It provides the following response:

This is the correct virtual environment inside of the project, seen here:

Am I setting something up incorrectly? I vastly prefer PyCharm's VCS and would prefer not to have to use git from the terminal.

答:
You can manually edit the auto-generated pre-commit file (located in your project dir at .git/hooks/pre-commit) to add the path to your virtual environment, replacing:

```<code># start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'
</code>```

with

```<code># start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'
os.environ['PATH'] = f'{os.path.dirname(INSTALL_PYTHON)}{os.pathsep}{os.environ["PATH"]}'
</code>```

Body:
I have recently started a new project in PyCharm, finally utilizing anaconda environments. However, after trying to make my first commit through PyCharm, it appears to be using my native python, not the environment set in PyCharm. I've tried to restart PyCharm several times, restarted my computer, and reinstalled the virtual environment.

Here is a copy of pre-commit hook:

set -e

# Run linters and tests
source scripts/lint.sh

The linter is the following: (which python has been added to highlight the issue)

set -e
set -v

which python

flake8 ~project name~
mypy ~project name~
pytest -x
black --check --fast --quiet ~project name~

set +v

I am running the commit through PyCharm -> VCS -> Commit. Inside PyCharm, the commit fails

(below this are a large amount of mypy errors, but note the environment)

However, if I run the commit from the terminal with $ git commit -m "testing commit" the commit works. It provides the following response:

This is the correct virtual environment inside of the project, seen here:

Am I setting something up incorrectly? I vastly prefer PyCharm's VCS and would prefer not to have to use git from the terminal.

Body:
You can manually edit the auto-generated pre-commit file (located in your project dir at .git/hooks/pre-commit) to add the path to your virtual environment, replacing:

# start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'

with

# start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'
os.environ['PATH'] = f'{os.path.dirname(INSTALL_PYTHON)}{os.pathsep}{os.environ["PATH"]}'


来源: stackexchange

问:
How to wait for firebase auth before starting angular app
I would like to display a small loading logo while the firebase authentication is retrieving a user token, before starting "for real" the single page application.

So far I have an authentication service :

```<code>constructor(
    public afAuth: AngularFireAuth,
    ) {
      this.afAuth.onAuthStateChanged(user => {
        if (user) {
           this.setCredentials(user)
        }
      })
    }

  setCredentials(user: firebase.User) {
      return user.getIdTokenResult(true).then(idTokenResult => {
        this.credentials = {
          userId: idTokenResult.claims.id,
          role: idTokenResult.claims.role,
          token: idTokenResult.token,
        };
        // STARTS THE APPLICATION NOW ?
      })
  }
</code>```

Is it possible to achieve such behavior ? I've read about APP_INITIALIZER without success. I want to avoid localstorage / session storage and instead rely solely on this initialization.

Update :

created an init function :

```<code>export function initApp(auth: AuthService, afAuth: AngularFireAuth) {
    return () => {
      return new Promise((resolve) => {
        afAuth.user.pipe(
            take(1),
        ).subscribe(user => {
          if (user) {
            auth.setCredentials(user)
            .then(() => resolve())
          } else {
              resolve();
          }
        })
      });
    }
  }
</code>```

And edited AppModule providers:

```<code>providers: [
    interceptorProviders /* my interceptors */,
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
      deps: [AuthService, AngularFireAuth],
      multi: true
    }
  ]
</code>```

Still need to figure out how to add a waiting logo but it's another question. I'll update asap.

答:
You should use your authentication service in a CanActivate router guard: https://angular.io/api/router/CanActivate

This means your AppModule will initially load and then your child route (ex. MainModule with router path '') has the guard. Then in AppModule you can check for the status of the service and show a loading information until MainModule is activated (when firebase auth is finished)

ContentLicense: CC BY-SA 4.0

Body:
I would like to display a small loading logo while the firebase authentication is retrieving a user token, before starting "for real" the single page application.

So far I have an authentication service :

constructor(
    public afAuth: AngularFireAuth,
    ) {
      this.afAuth.onAuthStateChanged(user => {
        if (user) {
           this.setCredentials(user)
        }
      })
    }

  setCredentials(user: firebase.User) {
      return user.getIdTokenResult(true).then(idTokenResult => {
        this.credentials = {
          userId: idTokenResult.claims.id,
          role: idTokenResult.claims.role,
          token: idTokenResult.token,
        };
        // STARTS THE APPLICATION NOW ?
      })
  }

Is it possible to achieve such behavior ? I've read about APP_INITIALIZER without success. I want to avoid localstorage / session storage and instead rely solely on this initialization.

Update :

created an init function :

export function initApp(auth: AuthService, afAuth: AngularFireAuth) {
    return () => {
      return new Promise((resolve) => {
        afAuth.user.pipe(
            take(1),
        ).subscribe(user => {
          if (user) {
            auth.setCredentials(user)
            .then(() => resolve())
          } else {
              resolve();
          }
        })
      });
    }
  }

And edited AppModule providers:

providers: [
    interceptorProviders /* my interceptors */,
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
      deps: [AuthService, AngularFireAuth],
      multi: true
    }
  ]

Still need to figure out how to add a waiting logo but it's another question. I'll update asap.


问:
SPS/ TwinCat/ Syntax Error-Code/ Declaration of TON and TOF
I am currently programming in ST (TwinCat), but two errors occured, which I do not understand at all.
Error-Code says:
(1) (TRUE AND TON_01.Q) is no valid assignment target
(2) Q is no input of TOF

I already declared Q as my Output , but TON and TOF cannot handle it. The Code and the Error is attached to the post. enter image description here

Thank you for your Help.

答:
The problem is that you are doing an assignment of TOF_01.Q and not a check.
So instead of:

IF TOF_01.Q := TRUE ... it should be

IF TOF_01.Q = TRUE ... or simply

IF TOF_01.Q...

Same with TON_01.Q obviously.


问:
Scheme Function to remove one list's items from another
I'm trying to create a scheme function which given two lists L1 and L2, will remove any items present in L2 from L1.

I have a small start, but I don't know exactly what else to do.

```<code>(define (remove L1 L2)
(((null? L2) L1))
</code>```

答:
Here is a code snippet for the simple case.

```<code>(define (remove L1 L2)
  (cond ((null? L1) '())
        ((memv (car L1) L2) (remove (cdr L1) L2))
        (else  (cons (car L1) (remove (cdr L1) L2)))))
</code>```

Remember that in Scheme, or any functional language, the question you need to ask is not "what should I be doing?", but rather you should ask "what value do I need to produce?".

Please note that this simple example doesn't handle nested lists.  So (remove '(A (C D)) '(B C D)) would produce (A (C D)).  Handling nesting lists is left as an exercise for the reader :D

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a scheme function which given two lists L1 and L2, will remove any items present in L2 from L1.

I have a small start, but I don't know exactly what else to do.

(define (remove L1 L2)
(((null? L2) L1))

Body:
Here is a code snippet for the simple case.

(define (remove L1 L2)
  (cond ((null? L1) '())
        ((memv (car L1) L2) (remove (cdr L1) L2))
        (else  (cons (car L1) (remove (cdr L1) L2)))))

Remember that in Scheme, or any functional language, the question you need to ask is not "what should I be doing?", but rather you should ask "what value do I need to produce?".

Please note that this simple example doesn't handle nested lists.  So (remove '(A (C D)) '(B C D)) would produce (A (C D)).  Handling nesting lists is left as an exercise for the reader :D


问:
Generating large DataFrame in a distributed way in pyspark efficiently (without pyspark.sql.Row)
The problem boils down to the following: I want to generate a DataFrame in pyspark using existing parallelized collection of inputs and a function which given one input can generate a relatively large batch of rows. In the example below I want to generate 10^12 rows dataframe using e.g. 1000 executors:

```<code>def generate_data(one_integer):
  import numpy as np
  from pyspark.sql import Row
  M = 10000000 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  row_type = Row("seed", "n", "x")
  return [row_type(one_integer, i, float(np_array[i])) for i in range(M)]

N = 100000 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = spark.sparkContext.parallelize(list_of_integers)
row_rdd = list_of_integers_rdd.flatMap(list_of_integers_rdd)
from pyspark.sql.types import StructType, StructField, FloatType, IntegerType
my_schema = StructType([
       StructField("seed", IntegerType()),
       StructField("n", IntegerType()),
       StructField("x", FloatType())])
df = spark.createDataFrame(row_rdd, schema=my_schema)
</code>```

(I don't really want to study distribution of random numbers given seed - this is just an example I was able to come up with to illustrate the situation when large dataframe is not loaded from warehouse, but generated by the code)

The code above does pretty much exactly what I want. Problem is that it does it in a very inefficient way - at expense of creating a python Row object for each row, then converting the python Row objects into internal Spark columnar representation.

Is there a way I can convert batch of rows already in columnar representation (e.g. one or a few numpy arrays as above np_array) just by letting spark know that these are the columns of a batch of values?

E.g. I can write the code to generate python collection RDD where each element is an pyarrow.RecordBatch or a pandas.DataFrame, but I can't find a way to convert any of these into Spark DataFrame without creating an RDD of pyspark Row objects in the process.

There is at least a dozen of articles with examples how I can use pyarrow + pandas to convert a local (to driver) pandas dataframe to Spark dataframe efficiently, but that is not an option for me because I need data to be actually generated in a distributed way on executors rather than generating one pandas dataframe on driver and sending that to executors.

UPD.
I've found one way to avoid creation of Row objects - using RDD of python tuples. As expected it is still way too slow, but still a bit faster than using Row objects. Still, this is not really what I'm looking for (which is a really efficient way of passing columnar data to Spark from python).

Also measured time to do certain operations on a machine (crude way with quite a bit of variation in measured time, but still it representative in my opinion):
The dataset in question is 10M rows, 3 cols (one column is constant integer, other is integer range from 0 to 10M-1, third is floating point value generated using np.random.random_sample:

Locally generate pandas dataframe (10M rows): ~440-450ms

Locally generate python list of spark.sql.Row objects (10M rows): ~12-15s

Locally generate python list of tuples representing rows (10M rows): ~3.4-3.5s

Generate Spark dataframe using just 1 executor and 1 initial seed value:

using spark.createDataFrame(row_rdd, schema=my_schema): ~70-80s

using spark.createDataFrame(tuple_rdd, schema=my_schema): ~40-45s

(non-distributed creation) using spark.createDataFrame(pandas_df, schema=my_schema): ~0.4-0.5s (without pandas df generation itself which takes roughly same time) - with spark.sql.execution.arrow.enabled set to true.

The example with local-to-driver pandas dataframe converted to Spark dataframe in ~1s for 10M rows gives me a reason to believe same should be possible with dataframes generated in executors. However fastest I can achieve now is ~40s for 10M rows using RDD of python tuples.

So the question still stays - is there a way to generate a large Spark dataframe in a distributed way efficiently in pyspark?

答:
Here's solution to your problem without using Row - only RDD based. I think it could be the most efficient way, since it uses map to calculate your function output and flatMap to combine those outputs - both those operations are performed on RDDs, so everything should be distributed.

```<code>import numpy as np
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('abc').getOrCreate()
sc = spark.sparkContext

def generate_data(one_integer):
  M = 2 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  return [(one_integer, i, float(np_array[i])) for i in range(M)]

N = 30 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = sc.parallelize(list_of_integers)
generated_data_rdd = list_of_integers_rdd.map(lambda x: generate_data(x))
solved_rdd = generated_data_rdd.flatMap(lambda list: list)

df = spark.createDataFrame(solved_rdd).toDF("seed", "n", "x")
df.show()
</code>```

Body:
The problem boils down to the following: I want to generate a DataFrame in pyspark using existing parallelized collection of inputs and a function which given one input can generate a relatively large batch of rows. In the example below I want to generate 10^12 rows dataframe using e.g. 1000 executors:

def generate_data(one_integer):
  import numpy as np
  from pyspark.sql import Row
  M = 10000000 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  row_type = Row("seed", "n", "x")
  return [row_type(one_integer, i, float(np_array[i])) for i in range(M)]

N = 100000 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = spark.sparkContext.parallelize(list_of_integers)
row_rdd = list_of_integers_rdd.flatMap(list_of_integers_rdd)
from pyspark.sql.types import StructType, StructField, FloatType, IntegerType
my_schema = StructType([
       StructField("seed", IntegerType()),
       StructField("n", IntegerType()),
       StructField("x", FloatType())])
df = spark.createDataFrame(row_rdd, schema=my_schema)

(I don't really want to study distribution of random numbers given seed - this is just an example I was able to come up with to illustrate the situation when large dataframe is not loaded from warehouse, but generated by the code)

The code above does pretty much exactly what I want. Problem is that it does it in a very inefficient way - at expense of creating a python Row object for each row, then converting the python Row objects into internal Spark columnar representation.

Is there a way I can convert batch of rows already in columnar representation (e.g. one or a few numpy arrays as above np_array) just by letting spark know that these are the columns of a batch of values?

E.g. I can write the code to generate python collection RDD where each element is an pyarrow.RecordBatch or a pandas.DataFrame, but I can't find a way to convert any of these into Spark DataFrame without creating an RDD of pyspark Row objects in the process.

There is at least a dozen of articles with examples how I can use pyarrow + pandas to convert a local (to driver) pandas dataframe to Spark dataframe efficiently, but that is not an option for me because I need data to be actually generated in a distributed way on executors rather than generating one pandas dataframe on driver and sending that to executors.

UPD.
I've found one way to avoid creation of Row objects - using RDD of python tuples. As expected it is still way too slow, but still a bit faster than using Row objects. Still, this is not really what I'm looking for (which is a really efficient way of passing columnar data to Spark from python).

Also measured time to do certain operations on a machine (crude way with quite a bit of variation in measured time, but still it representative in my opinion):
The dataset in question is 10M rows, 3 cols (one column is constant integer, other is integer range from 0 to 10M-1, third is floating point value generated using np.random.random_sample:

Locally generate pandas dataframe (10M rows): ~440-450ms

Locally generate python list of spark.sql.Row objects (10M rows): ~12-15s

Locally generate python list of tuples representing rows (10M rows): ~3.4-3.5s

Generate Spark dataframe using just 1 executor and 1 initial seed value:

using spark.createDataFrame(row_rdd, schema=my_schema): ~70-80s

using spark.createDataFrame(tuple_rdd, schema=my_schema): ~40-45s

(non-distributed creation) using spark.createDataFrame(pandas_df, schema=my_schema): ~0.4-0.5s (without pandas df generation itself which takes roughly same time) - with spark.sql.execution.arrow.enabled set to true.

The example with local-to-driver pandas dataframe converted to Spark dataframe in ~1s for 10M rows gives me a reason to believe same should be possible with dataframes generated in executors. However fastest I can achieve now is ~40s for 10M rows using RDD of python tuples.

So the question still stays - is there a way to generate a large Spark dataframe in a distributed way efficiently in pyspark?

Body:
Here's solution to your problem without using Row - only RDD based. I think it could be the most efficient way, since it uses map to calculate your function output and flatMap to combine those outputs - both those operations are performed on RDDs, so everything should be distributed.

import numpy as np
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('abc').getOrCreate()
sc = spark.sparkContext

def generate_data(one_integer):
  M = 2 # number of values to generate per seed, e.g. 10M
  np.random.seed(one_integer)
  np_array = np.random.random_sample(M) # generates an array of M random values
  return [(one_integer, i, float(np_array[i])) for i in range(M)]

N = 30 # number of seeds to try, e.g. 100K
list_of_integers = [i for i in range(N)]
list_of_integers_rdd = sc.parallelize(list_of_integers)
generated_data_rdd = list_of_integers_rdd.map(lambda x: generate_data(x))
solved_rdd = generated_data_rdd.flatMap(lambda list: list)

df = spark.createDataFrame(solved_rdd).toDF("seed", "n", "x")
df.show()


问:
How to start an embedded YouTube video at a certain timestamp in iphone
I want to start an embedded youtube video from a timestamp. I know how to do it on browsers but that does not seem to work on iPhone. Here is a detailed tutorial by MATT CUTTS.

Start an embedded video at a certain timestamp

In above link you can see if we append #t=31m08s or &start=200 in url it works but when i use same url inside UiWebView, default youtube player starts video from first frame. Can anyone have an idea or have implemented same. I am using UIWebView with embed tag to play youtube video. I am using below embed tag inside UIWebView.

```<code> <embed id="yt" src="http://www.youtube.com/watch?v=dsFQ9kM1qDs" type="application/x-shockwave-flash" width= "500" height="400"></embed>
</code>```

Below is the code i am using to play this video in UIWebView

```<code>- (IBAction) playYoutube {
    [self embedYouTube:@"http://www.youtube.com/watch?v=dsFQ9kM1qDs#t=2m08s"];
}

- (void)embedYouTube:(NSString*)url
{
    [webView setFrame:CGRectMake(0, 0, 480, 320)];
    NSString* embedHTML = @"\
    <html><head>"
    "<style type=\"text/css\">"
    "body {"
    "background-color: transparent;"
    "color: white;"
    "} </style>"
    "</head><body style=\"margin:0\">"
    "  <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" "
    "width=\"%0.0f\" height=\"%0.0f\"></embed>"
    "   </body></html>";

    NSString* html = [NSString stringWithFormat:embedHTML, url, webView.frame.size.width,  webView.frame.size.height];
    [webView loadHTMLString:html baseURL:nil];
}
</code>```

答:
Try adding ?t=1m10s at the end of the link

E.g. src="https://youtu.be/dsFQ9kM1qDs?t=1m10s"

Note: Make sure that you use youtu.be link (the link that you get when you click share button on YouTube) and not youtube.com link

Body:
I want to start an embedded youtube video from a timestamp. I know how to do it on browsers but that does not seem to work on iPhone. Here is a detailed tutorial by MATT CUTTS.

Start an embedded video at a certain timestamp

In above link you can see if we append #t=31m08s or &start=200 in url it works but when i use same url inside UiWebView, default youtube player starts video from first frame. Can anyone have an idea or have implemented same. I am using UIWebView with embed tag to play youtube video. I am using below embed tag inside UIWebView.

 <embed id="yt" src="http://www.youtube.com/watch?v=dsFQ9kM1qDs" type="application/x-shockwave-flash" width= "500" height="400"></embed>

Below is the code i am using to play this video in UIWebView

- (IBAction) playYoutube {
    [self embedYouTube:@"http://www.youtube.com/watch?v=dsFQ9kM1qDs#t=2m08s"];
}

- (void)embedYouTube:(NSString*)url
{
    [webView setFrame:CGRectMake(0, 0, 480, 320)];
    NSString* embedHTML = @"\
    "
    ""
    ""
    "  <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" "
    "width=\"%0.0f\" height=\"%0.0f\"></embed>"
    "   ";

    NSString* html = [NSString stringWithFormat:embedHTML, url, webView.frame.size.width,  webView.frame.size.height];
    [webView loadHTMLString:html baseURL:nil];
}


问:
micropython ds18x20 wrong rom/address/serial
I have  ESP23 dev kit with micropython firmware esp32-idf3-20200329-v1.12-317-g688323307.
I also have ds18b20 waterproof sensor. datasheet link

I wrote this code for it:

```<code>import time, onewire, ds18x20
import machine

from machine import Pin

ds_pin=Pin(19)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()

for rom in roms:
    print(rom)
</code>```

It returns tis info:

```<code>[bytearray(b'(\xbcN6\x14\x19\x01\xba')]
</code>```

Before reading temp data from sensor, we first need to use the scan() function to scan for DS18B20 sensors. The addresses found are saved on the roms variable (the roms variable is of type list). scan() function sends request and sensor returns its unique 64-bit serial code.

I used manual here

Today I bought two more ds18x20 waterproof sensors (I don’t know what type of sensor - ds18a20/ds18b20 or else - are they, ‘cause eager chinese manufacturers sealed sensors inside metal bullet too good, so I can’t just look inside).
I tried to run the same code with them, but it returned the following:

```<code>bytearray(b'(\xff\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfe\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfc\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf8\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xd0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xfe\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xf6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xe6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xc6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xfd\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xf9\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xfe\xff\xff\xff')
bytearray(b'(\x90\x86y\xfa\xff\xff\xff')
bytearray(b'(\x90\x86y\xf2\xff\xff\xff')
bytearray(b'(\x90\x86y\xe2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xfd\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf9\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xe1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xc1\xff\xff')
bytearray(b'(\x90\x86y\xa2\x81\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xfb\xff')
bytearray(b'(\x90\x86y\xa2\x01\xf3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xe3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xc3\xff')
bytearray(b'(\x90\x86y\xa2\x01\x83\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfe')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfc')
bytearray(b'(\x90\x86y\xa2\x01\x03\xdc')
bytearray(b'(\x90\x86y\xa2\x01\x03\\')
</code>```

When I try to read temperature using this values it returns ‘CRC error’.

What can be done? Is the problem with code, or the sensors are failed somehow?

答:
looks like fake sensor

How to tell original from fake DS18B20 temperature sensors

Body:
I have  ESP23 dev kit with micropython firmware esp32-idf3-20200329-v1.12-317-g688323307.
I also have ds18b20 waterproof sensor. datasheet link

I wrote this code for it:

import time, onewire, ds18x20
import machine

from machine import Pin

ds_pin=Pin(19)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()

for rom in roms:
    print(rom)

It returns tis info:

[bytearray(b'(\xbcN6\x14\x19\x01\xba')]

Before reading temp data from sensor, we first need to use the scan() function to scan for DS18B20 sensors. The addresses found are saved on the roms variable (the roms variable is of type list). scan() function sends request and sensor returns its unique 64-bit serial code.

I used manual here

Today I bought two more ds18x20 waterproof sensors (I don’t know what type of sensor - ds18a20/ds18b20 or else - are they, ‘cause eager chinese manufacturers sealed sensors inside metal bullet too good, so I can’t just look inside).
I tried to run the same code with them, but it returned the following:

bytearray(b'(\xff\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfe\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfc\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf8\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xd0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xfe\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xf6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xe6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xc6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xfd\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xf9\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xfe\xff\xff\xff')
bytearray(b'(\x90\x86y\xfa\xff\xff\xff')
bytearray(b'(\x90\x86y\xf2\xff\xff\xff')
bytearray(b'(\x90\x86y\xe2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xfd\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf9\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xe1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xc1\xff\xff')
bytearray(b'(\x90\x86y\xa2\x81\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xfb\xff')
bytearray(b'(\x90\x86y\xa2\x01\xf3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xe3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xc3\xff')
bytearray(b'(\x90\x86y\xa2\x01\x83\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfe')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfc')
bytearray(b'(\x90\x86y\xa2\x01\x03\xdc')
bytearray(b'(\x90\x86y\xa2\x01\x03\\')

When I try to read temperature using this values it returns ‘CRC error’.

What can be done? Is the problem with code, or the sensors are failed somehow?


问:
Re-using CLI installation in a multi-stage docker file
I am writing a multi-stage Dockerfile. The first step is to install a cli:

```<code>FROM python:3 as cfngenerate

RUN pip install cloudformation-cli
</code>```

The second step is to build a Java project with maven. This build relies on the CLI above.

```<code>FROM maven as build

COPY --from=cfngenerate /usr/local/bin/cfn /usr/local/bin/cfn

RUN mvn package
</code>```

This however doesn't work. The Maven step fails with: java.io.IOException: Cannot run program "cfn-cli": error=2, No such file or directory

How can I ensure that the CLI is available in the second step?

I think the more general question is, how do I have one step rely on two frameworks (Maven and a python CLI)?

答:
You have 2 "FROM" means two separate images. If you need both frameworks, there are few options

Use base docker images, then install python and maven

Use python image, then install maven. You need to do required setup for maven.

Use maven image, then install python. You need to do required setup for python.

Look for an image which already install python and maven, shared by others. (eg. https://hub.docker.com/r/openkbs/jre-mvn-py3). It might included unnecessary things you don't need.

Body:
I am writing a multi-stage Dockerfile. The first step is to install a cli:

FROM python:3 as cfngenerate

RUN pip install cloudformation-cli

The second step is to build a Java project with maven. This build relies on the CLI above.

FROM maven as build

COPY --from=cfngenerate /usr/local/bin/cfn /usr/local/bin/cfn

RUN mvn package

This however doesn't work. The Maven step fails with: java.io.IOException: Cannot run program "cfn-cli": error=2, No such file or directory

How can I ensure that the CLI is available in the second step?

I think the more general question is, how do I have one step rely on two frameworks (Maven and a python CLI)?


问:
Button does not look the same on mobile as in android studio layout view
I have defined three buttons using the same drawable background file "find_button.xml". The "start server activity" button (id="start_button") ignores for some reason the file "find_button.xml" .
I am not able to find any mistake..

Layout view in android studio:

Layout View on mobile:

xml Layoutfile:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1A91C6"
    tools:context=".ServerInitial">

    <Button
        android:id="@+id/start_button"

        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:onClick="startServerActivity"
        android:text="@string/start_server_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/close_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ListView
        android:id="@+id/peers_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="24dp"

        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:cacheColorHint="?android:attr/colorMultiSelectHighlight"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/start_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/find_button">

    </ListView>

    <Button
        android:id="@+id/find_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:drawableLeft="@drawable/ic_search_black_72dp"
        android:gravity="left|center_vertical"
        android:onClick="sucheGeräte"
        android:text="@string/suchen_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/close_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#E3931D"
        android:onClick="closeConnection"
        android:text="@string/close_connection"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

drawable backgroundfile "find_button.xml"

```<code>    <?xml vers`enter code here`ion="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="20dp" />
</shape>
</code>```

New Info: I installed new and realized , that while permission requests showed up, the button looked as it was supposed to look.After permission requests had been confirmed, the button changed back to it's old design.

I am using a pretty nice routine "has permissions" in onCreate for checking permissions, maybe the bug is somewhere there.

```<code>public class ServerInitial extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {

public static final String TAG = MainActivity.class.getSimpleName();
public WifiP2pManager manager;
public WifiP2pManager.Channel channel2;
public BroadcastReceiver receiver;
public IntentFilter intentFilter;
private List<WifiP2pDevice> peers_list = new ArrayList<>();
private ListView peerslist;
private int count = 0;
private String[] devicenames;
public WifiP2pDevice device;
public Button start;

private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {

        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_FINE_LOCATION
};

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (!hasPermissions(this, PERMISSIONS))
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

    assert manager != null;
    channel2 = manager.initialize(this, getMainLooper(), null);
    receiver = new P2PBroadcastReceiver(manager, channel2, ServerInitial.this, ServerInitial.this,
            ServerInitial.this);
    intentFilter = new IntentFilter();
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    setContentView(R.layout.activity_server_initial);

    start = findViewById(R.id.start_button);
    // Check if recreating a previously destroyed instance.
    if (savedInstanceState != null) {
        //Restore value of members from saved state.
        devicenames = savedInstanceState.getStringArray("list");
        fillListe();
    } else {

        devicenames = null;

        // Initialize members with default values for a new instance.
        // ...
    }

    manager.discoverPeers(channel2, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            System.out.println("Da draussen ist was los .......");
            //ergebnisSuche.setText("Da ist was los...");

        }

        @Override
        public void onFailure(int reason) {
            System.out.println("Da draussen ist nix los .......");
            //ergebnisSuche.setText("Da ist nix los...");

        }
    });

}
</code>```

答:
I found the solution. I apply some changes to the "start server" button later in my code. This seems to make the button to ignore the background drawable.
I assigned in my code the drawable with "start.setBackground(...) and now it works. (see code below)</p>

```<code> @Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
    if (info.groupFormed) {

        if (info.isGroupOwner) {

            //Intent intent1 = new Intent(this, ServerActivity.class);
            //startActivity(intent1);
            start.setBackgroundColor(getResources().getColor(R.color.lightGreen));
            start.setText("Connected !! Push Button to start..");
            start.setBackground(getResources().getDrawable(R.drawable.find_button));
            start.setTextColor(Color.GREEN);
            start.setTypeface(Typeface.DEFAULT_BOLD);
            start.setEnabled(true);
        } else {
</code>```

Body:
I have defined three buttons using the same drawable background file "find_button.xml". The "start server activity" button (id="start_button") ignores for some reason the file "find_button.xml" .
I am not able to find any mistake..

Layout view in android studio:

Layout View on mobile:

xml Layoutfile:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1A91C6"
    tools:context=".ServerInitial">

    <Button
        android:id="@+id/start_button"

        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:onClick="startServerActivity"
        android:text="@string/start_server_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/close_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ListView
        android:id="@+id/peers_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="24dp"

        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:cacheColorHint="?android:attr/colorMultiSelectHighlight"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/start_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/find_button">

    </ListView>

    <Button
        android:id="@+id/find_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:drawableLeft="@drawable/ic_search_black_72dp"
        android:gravity="left|center_vertical"
        android:onClick="sucheGeräte"
        android:text="@string/suchen_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/close_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#E3931D"
        android:onClick="closeConnection"
        android:text="@string/close_connection"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

drawable backgroundfile "find_button.xml"

    <?xml vers`enter code here`ion="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="20dp" />
</shape>

New Info: I installed new and realized , that while permission requests showed up, the button looked as it was supposed to look.After permission requests had been confirmed, the button changed back to it's old design.

I am using a pretty nice routine "has permissions" in onCreate for checking permissions, maybe the bug is somewhere there.

public class ServerInitial extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {

public static final String TAG = MainActivity.class.getSimpleName();
public WifiP2pManager manager;
public WifiP2pManager.Channel channel2;
public BroadcastReceiver receiver;
public IntentFilter intentFilter;
private List<WifiP2pDevice> peers_list = new ArrayList<>();
private ListView peerslist;
private int count = 0;
private String[] devicenames;
public WifiP2pDevice device;
public Button start;

private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {

        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_FINE_LOCATION
};

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (!hasPermissions(this, PERMISSIONS))
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

    assert manager != null;
    channel2 = manager.initialize(this, getMainLooper(), null);
    receiver = new P2PBroadcastReceiver(manager, channel2, ServerInitial.this, ServerInitial.this,
            ServerInitial.this);
    intentFilter = new IntentFilter();
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    setContentView(R.layout.activity_server_initial);

    start = findViewById(R.id.start_button);
    // Check if recreating a previously destroyed instance.
    if (savedInstanceState != null) {
        //Restore value of members from saved state.
        devicenames = savedInstanceState.getStringArray("list");
        fillListe();
    } else {

        devicenames = null;

        // Initialize members with default values for a new instance.
        // ...
    }

    manager.discoverPeers(channel2, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            System.out.println("Da draussen ist was los .......");
            //ergebnisSuche.setText("Da ist was los...");

        }

        @Override
        public void onFailure(int reason) {
            System.out.println("Da draussen ist nix los .......");
            //ergebnisSuche.setText("Da ist nix los...");

        }
    });

}

Body:
I found the solution. I apply some changes to the "start server" button later in my code. This seems to make the button to ignore the background drawable.
I assigned in my code the drawable with "start.setBackground(...) and now it works. (see code below)

 @Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
    if (info.groupFormed) {

        if (info.isGroupOwner) {

            //Intent intent1 = new Intent(this, ServerActivity.class);
            //startActivity(intent1);
            start.setBackgroundColor(getResources().getColor(R.color.lightGreen));
            start.setText("Connected !! Push Button to start..");
            start.setBackground(getResources().getDrawable(R.drawable.find_button));
            start.setTextColor(Color.GREEN);
            start.setTypeface(Typeface.DEFAULT_BOLD);
            start.setEnabled(true);
        } else {


问:
Upgrading permissions of a Chrome Extensions
We currently have an extension in the Chrome Web Store with many users. We currently request access to foo.site.com but now we'd like to update our permissions so that we can get bar.site.com.

As I understand it now, if we push a new update (new extension version to the Chrome Web Store) requiring these two permissions, existing users will have their extension disabled until they manually re-enable. New users who download the extension after the update will be fine and have both permissions. However, disabling our current users is not an option.

Any way to get around this?

We've looked into optional permissions, which would solve the issue for existing users (we would just ask them to click a button to upgrade the permissions and be on our way). However for new users, they would not only have to install the extension but also accept the optional permissions which sucks. Is there any way for new users to accept all the permission (optional and required) at install time?

答:
There is a way (using optional permissions) to add new extension permissions without disabling the extension for the existing users, while also ensuring new users get prompted to accept both required and optional permissions after installation.

Optional permissions can be requested using chrome.permissions.request API, but it functions only if the request is preceded by a user action. The simplest way to fulfill this requirement and still provide a seamless user experience is to check for the permissions in the background page and request the optional permissions in a popup at runtime.

Permission request can be made in the background page right after loading the extension (after installation and subsequent browser launches). Any existing user missing any of the permissions will be prompted to accept the permission after relaunching the browser.

The following example includes:

The background page JavaScript (background_page.js)

Notification popup html file (notification_popup.html)

Notification popup JavaScript (notification_popup.js)

You will also need declare the "optional_permissions" in manifest.json for the example to work. The example will work with both a Chrome Extension and a Firefox Add-on.

background_page.js

```<code>var brwsr = null;
if (typeof chrome != "undefined") {
    brwsr = chrome;
}
else{
    brwsr = browser;
}
var opt_perms = brwsr.runtime.getManifest().optional_permissions;
var requiredOptionalPermissions = {}
if(typeof opt_perms!="undefined" && opt_perms.length>0){
    var perms = []
    var origins = []
    var re = new RegExp("^(http|https)://", "i");
    for(var i=0; i<opt_perms.length; i++){
        if(opt_perms[i]==="<all_urls>"|| re.test(opt_perms[i])){
            origins.push(opt_perms[i])
        }
        else{
            perms.push(opt_perms[i])
        }
    }
    if(perms.length>0){
        requiredOptionalPermissions.permissions = perms
    }
    if(origins.length>0){
        requiredOptionalPermissions.origins = origins
    }
}
var requiresPermission = ()=>{
// add your code here
}
// check if optional permission exists and request if not
var runFunctionsRequiringOptPermissions = function(requiredPermissions={}, userGesture=false, callback=()=>{}){
    if(typeof requiredPermissions.permissions!="undefined" || typeof requiredPermissions.origins!="undefined"){
        brwsr.permissions.contains(requiredPermissions, function(res) {
            if (!res) {
                // The extension doesn't have the permissions.)
                if(userGesture){
                    brwsr.permissions.request(requiredPermissions, function(granted){
                        if(granted){
                            // perform actions that required the permission
                            requiresPermission()
                        }
                        callback();
                    });
                    return;
                }
                // open the notification popup
                window.open("notification_popup.html", "extension_popup", "width=530,height=190,status=no,scrollbars=yes,resizable=no,screenY=+"+(screen.height/2-95)+",screenX="+(screen.width/2-265));
            }
            else{
                // perform actions that required the permission
                requiresPermission()
            }
        });
    }
}

runFunctionsRequiringOptPermissions(requiredOptionalPermissions)
// add listener
brwsr.runtime.onConnect.addListener(function(port) {
    if(port.name == "optionalPermRequestPopup"){
        port.onMessage.addListener(
            function(request, sender, sendResponse) {
                if (request.okButtonClicked === true) {
                    runFunctionsRequiringOptPermissions(requiredOptionalPermissions, true, function(){
                        // callback to close the notification popup
                        port.postMessage({'close':true});
                    })
                    return;
                }
                port.postMessage({'close':true})
            }
        );
    }
});

</code>```

notification_popup.html

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Extension Name</title>
    <style>
      .container {
        font-size:medium;
        text-align:center;
      }
      .button{
        height: 30px;
        width: 70px;
        background-color: #448be9;
        color: white;
        border-color: #448be9;
        border-width: thin;
        margin-right: 10px;
        float: right;
      }
      .btnCancel{
        background-color: white;
        color: #448be9
      }
      </style>
    </head>
    <body>
    <div class="container">
        <p class='text'>Please upgrade the permissions to enable the latest features.</p>
        <button class="button btnCancel">Cancel</button>
        <button class="button btnOk">OK</button>
    </div>
    <script src="notification_popup.js"></script>
    </body>
</html>
</code>```

notification_popup.js

```<code>var brwsr = null;
if (typeof chrome != "undefined") {
    brwsr = chrome;
}
else{
    brwsr = browser;
}
var port = brwsr.runtime.connect({
    name : "optionalPermRequestPopup"
});
window.addEventListener("load", function(event) {
    var okButtons = document.querySelectorAll(".btnOk");
    okButtons.forEach(function(okButton) {
        okButton.addEventListener("click", function(event) {
            port.postMessage({okButtonClicked: true})
        });
    });
    port.onMessage.addListener(function(request) {
        for (var key in request) {
            switch(key){
                case "close":
                    window.close();
                    break;
                default:
                    break;
            }
        }
    });
});
</code>```

Body:
There is a way (using optional permissions) to add new extension permissions without disabling the extension for the existing users, while also ensuring new users get prompted to accept both required and optional permissions after installation.

Optional permissions can be requested using chrome.permissions.request API, but it functions only if the request is preceded by a user action. The simplest way to fulfill this requirement and still provide a seamless user experience is to check for the permissions in the background page and request the optional permissions in a popup at runtime.

Permission request can be made in the background page right after loading the extension (after installation and subsequent browser launches). Any existing user missing any of the permissions will be prompted to accept the permission after relaunching the browser.

The following example includes:

The background page JavaScript (background_page.js)

Notification popup html file (notification_popup.html)

Notification popup JavaScript (notification_popup.js)

You will also need declare the "optional_permissions" in manifest.json for the example to work. The example will work with both a Chrome Extension and a Firefox Add-on.

background_page.js

var brwsr = null;
if (typeof chrome != "undefined") {
    brwsr = chrome;
}
else{
    brwsr = browser;
}
var opt_perms = brwsr.runtime.getManifest().optional_permissions;
var requiredOptionalPermissions = {}
if(typeof opt_perms!="undefined" && opt_perms.length>0){
    var perms = []
    var origins = []
    var re = new RegExp("^(http|https)://", "i");
    for(var i=0; i<opt_perms.length; i++){
        if(opt_perms[i]==="<all_urls>"|| re.test(opt_perms[i])){
            origins.push(opt_perms[i])
        }
        else{
            perms.push(opt_perms[i])
        }
    }
    if(perms.length>0){
        requiredOptionalPermissions.permissions = perms
    }
    if(origins.length>0){
        requiredOptionalPermissions.origins = origins
    }
}
var requiresPermission = ()=>{
// add your code here
}
// check if optional permission exists and request if not
var runFunctionsRequiringOptPermissions = function(requiredPermissions={}, userGesture=false, callback=()=>{}){
    if(typeof requiredPermissions.permissions!="undefined" || typeof requiredPermissions.origins!="undefined"){
        brwsr.permissions.contains(requiredPermissions, function(res) {
            if (!res) {
                // The extension doesn't have the permissions.)
                if(userGesture){
                    brwsr.permissions.request(requiredPermissions, function(granted){
                        if(granted){
                            // perform actions that required the permission
                            requiresPermission()
                        }
                        callback();
                    });
                    return;
                }
                // open the notification popup
                window.open("notification_popup.html", "extension_popup", "width=530,height=190,status=no,scrollbars=yes,resizable=no,screenY=+"+(screen.height/2-95)+",screenX="+(screen.width/2-265));
            }
            else{
                // perform actions that required the permission
                requiresPermission()
            }
        });
    }
}

runFunctionsRequiringOptPermissions(requiredOptionalPermissions)
// add listener
brwsr.runtime.onConnect.addListener(function(port) {
    if(port.name == "optionalPermRequestPopup"){
        port.onMessage.addListener(
            function(request, sender, sendResponse) {
                if (request.okButtonClicked === true) {
                    runFunctionsRequiringOptPermissions(requiredOptionalPermissions, true, function(){
                        // callback to close the notification popup
                        port.postMessage({'close':true});
                    })
                    return;
                }
                port.postMessage({'close':true})
            }
        );
    }
});

notification_popup.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Extension Name</title>
    <style>
      .container {
        font-size:medium;
        text-align:center;
      }
      .button{
        height: 30px;
        width: 70px;
        background-color: #448be9;
        color: white;
        border-color: #448be9;
        border-width: thin;
        margin-right: 10px;
        float: right;
      }
      .btnCancel{
        background-color: white;
        color: #448be9
      }
      </style>
    </head>
    <body>
    <div class="container">
        <p class='text'>Please upgrade the permissions to enable the latest features.</p>
        <button class="button btnCancel">Cancel</button>
        <button class="button btnOk">OK</button>
    </div>
    <script src="notification_popup.js"></script>
    </body>
</html>

notification_popup.js

var brwsr = null;
if (typeof chrome != "undefined") {
    brwsr = chrome;
}
else{
    brwsr = browser;
}
var port = brwsr.runtime.connect({
    name : "optionalPermRequestPopup"
});
window.addEventListener("load", function(event) {
    var okButtons = document.querySelectorAll(".btnOk");
    okButtons.forEach(function(okButton) {
        okButton.addEventListener("click", function(event) {
            port.postMessage({okButtonClicked: true})
        });
    });
    port.onMessage.addListener(function(request) {
        for (var key in request) {
            switch(key){
                case "close":
                    window.close();
                    break;
                default:
                    break;
            }
        }
    });
});


问:
"Could not find the main class" when double-clicking .jar file
First: I realize that this issue should be quite simple and lots of people seem to have experienced it. However, it appears my issue may be slightly different from existing posts.

I'm using NetBeans to compile a Java application. When it's done building, the output goes into the dist\ folder correctly. The jar file is present there. If I go to the command line, navigate to that folder, and call the following:

java -jar Prosperity.jar

everything works fine. Obviously the name of the application is Prosperity. The following command also works fine:

javaw -jar Prosperity.jar

However, double-clicking the .jar file gives the message: "Could not find the main class:", and then gives the path to the .jar file. I've checked a hundred times that the META-INF folder exists inside the .jar file, and that within it there exists a MANIFEST.MF with the correct main class name. I have also checked that the main class (App.class) .class file exists inside the .jar file.

So the question is: what's the difference between double-clicking a file and running javaw on it? It's getting really frustrating that it won't just run!

Thanks for any direction you can give me, I'm tearin' my hair out here!

答:
I just had the exact same problem, fixed the same way. I had to completely delete the association, not just the user customisation, and reinstall the JRE.

The association before the fix was still:

```<code>jarfile="C:\Program Files (x86)\Java\jre6\bin\javaw.exe" -jar "%1" %*
</code>```

And after (the same):

```<code>jarfile="C:\Program Files (x86)\Java\jre6\bin\javaw.exe" -jar "%1" %*
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I just had the exact same problem, fixed the same way. I had to completely delete the association, not just the user customisation, and reinstall the JRE.

The association before the fix was still:

jarfile="C:\Program Files (x86)\Java\jre6\bin\javaw.exe" -jar "%1" %*

And after (the same):

jarfile="C:\Program Files (x86)\Java\jre6\bin\javaw.exe" -jar "%1" %*


问:
Error "The input device is not a TTY"
I am running the following command from my Jenkinsfile. However, I get the error "The input device is not a TTY".

```<code>docker run -v $PWD:/foobar -it cloudfoundry/cflinuxfs2 /foobar/script.sh
</code>```

Is there a way to run the script from the Jenkinsfile without doing interactive mode?

I basically have a file called script.sh that I would like to run inside the Docker container.

答:
My Jenkins pipeline step shown below failed with the same error.

```<code>       steps {
            echo 'Building ...'
            sh 'sh ./Tools/build.sh'
        }
</code>```

In my "build.sh" script file "docker run" command output this error when it was executed by Jenkins job. However it was working OK when the script ran in the shell terminal.The error happened because of -t option passed to docker run command that as I know tries to allocate terminal and  fails if there is no terminal to allocate.

In my case I have changed the script to pass -t option only  if a terminal could be detected. Here is the code after changes :

```<code>DOCKER_RUN_OPTIONS="-i --rm"

# Only allocate tty if we detect one
if [ -t 0 ] && [ -t 1 ]; then
    DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS -t"
fi

docker run $DOCKER_RUN_OPTIONS --name my-container-name  my-image-tag
</code>```

Title: Error "The input device is not a TTY"

Body:
I am running the following command from my Jenkinsfile. However, I get the error "The input device is not a TTY".

docker run -v $PWD:/foobar -it cloudfoundry/cflinuxfs2 /foobar/script.sh

Is there a way to run the script from the Jenkinsfile without doing interactive mode?

I basically have a file called script.sh that I would like to run inside the Docker container.

Body:
My Jenkins pipeline step shown below failed with the same error.

       steps {
            echo 'Building ...'
            sh 'sh ./Tools/build.sh'
        }

In my "build.sh" script file "docker run" command output this error when it was executed by Jenkins job. However it was working OK when the script ran in the shell terminal.The error happened because of -t option passed to docker run command that as I know tries to allocate terminal and  fails if there is no terminal to allocate.

In my case I have changed the script to pass -t option only  if a terminal could be detected. Here is the code after changes :

DOCKER_RUN_OPTIONS="-i --rm"

# Only allocate tty if we detect one
if [ -t 0 ] && [ -t 1 ]; then
    DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS -t"
fi

docker run $DOCKER_RUN_OPTIONS --name my-container-name  my-image-tag


问:
react-recharts LineChart does not render
i'm attempting to use Recharts/LineChart for reactJs with a simple set of data, but nothing is displayed : https://codesandbox.io/s/lucid-water-omrql?file=/src/App.js

Is there something wrong with the parameters ?
Thanks

答: O, i've understood why it didn't work, i've targetted the dataKey attribute to something inexistant</p>


问:
Power shell command in python output gives integer. Why?
```<code>import os
policyINAppconfigFile = os.system('%SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command  "findstr "maxAllowedContentLength" C:\\Windows\\sysnative\\inetsrv\\config\\applicationHost.config "')
numbers = []
for word in policyINAppconfigFile.split():
    if word.isdigit():
        numbers.append(int(word))
print(numbers)
</code>```

The code above gives the error output:

Traceback (most recent call last):
  File "c:/Users/Administrator/Documents/IIS code/testing123.py", line 119, in
    for word in policyINAppconfigFile.split():
builtins.AttributeError: 'int' object has no attribute 'split'

答:
When you run a command via os.system you get the exit code back; not the return value. The subprocess module is great for grabbing the output of a command:

import subprocess
import os

power_shell = os.path.join(
    os.environ["SYSTEMROOT"], "System32",
    "WindowsPowerShell", "v1.0", "powershell.exe"
)

policyINAppconfigFile = subprocess.check_output(
    [power_shell, "-Command",  "findstr maxAllowedContentLength",
    "C:\\Windows\\sysnative\\inetsrv\\config\\applicationHost.config"]
)
```

Body:
import os
policyINAppconfigFile = os.system('%SYSTEMROOT%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command  "findstr "maxAllowedContentLength" C:\\Windows\\sysnative\\inetsrv\\config\\applicationHost.config "')
numbers = []
for word in policyINAppconfigFile.split():
    if word.isdigit():
        numbers.append(int(word))
print(numbers)

The code above gives the error output:

Traceback (most recent call last):
  File "c:/Users/Administrator/Documents/IIS code/testing123.py", line 119, in
    for word in policyINAppconfigFile.split():
builtins.AttributeError: 'int' object has no attribute 'split'


问:
How to set only the background image in CSS to opacity and nothing else
I need a little bit help on how to set just the background image to opacity of .5 and nothing else.
I am using grid so anything I put in there is opaque and unfortunately I cant seem to find any help on Google either to explain how to bypass everything but the image.</p>

```<code>.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 310px);
}

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
 }

.one {
background-color: tomato;
grid-area: one;
}

.two {
background-image: url(./henry-perks-TStCoAiFjDY-unsplash.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
opacity: .5;
grid-area: two;
}

<body>
<div class="grid">
    <div class="one"></div>
    <div class="two">

        <h2 class="title">CJs Pizza Place</h2>

    </div>
    <div class="three"></div>

   </div>

 </body>
</code>```

答:
You can use pseudo ::after and give background image properties to that.

Also make sure this pseudo element is absolute positioned with 100% of width and height. And your actual div is relative positioned.

Just like

.grid {
  display: grid;
  grid-template-areas: "one two three" "one two three" "one two three";
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: repeat(3, 310px);
}

.title {
  font-family: 'Chelsea Market', cursive;
  font-size: 30px;
  text-align: center;
}

.one {
  background-color: tomato;
  grid-area: one;
}

.two {

  position: relative;
  grid-area: two;
}

.two::after {
  background-image: url('https://earthsky.org/upl/2018/06/sun-pillar-6-25-2018-Peter-Gipson-sq.jpg');
   background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  opacity: .5;
  content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="grid">
    <div class="one"></div>
    <div class="two">

      <h2 class="title">CJs Pizza Place</h2>

    </div>
    <div class="three"></div>

  </div>

</body></code>```

Body:
I need a little bit help on how to set just the background image to opacity of .5 and nothing else.
I am using grid so anything I put in there is opaque and unfortunately I cant seem to find any help on Google either to explain how to bypass everything but the image.

.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 310px);
}

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
 }

.one {
background-color: tomato;
grid-area: one;
}

.two {
background-image: url(./henry-perks-TStCoAiFjDY-unsplash.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
opacity: .5;
grid-area: two;
}

CJs Pizza Place

Body:
You can use pseudo ::after and give background image properties to that.

Also make sure this pseudo element is absolute positioned with 100% of width and height. And your actual div is relative positioned.

Just like

.grid {
  display: grid;
  grid-template-areas: "one two three" "one two three" "one two three";
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: repeat(3, 310px);
}

.title {
  font-family: 'Chelsea Market', cursive;
  font-size: 30px;
  text-align: center;
}

.one {
  background-color: tomato;
  grid-area: one;
}

.two {

  position: relative;
  grid-area: two;
}

.two::after {
  background-image: url('https://earthsky.org/upl/2018/06/sun-pillar-6-25-2018-Peter-Gipson-sq.jpg');
   background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  opacity: .5;
  content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

<body>
  <div class="grid">
    <div class="one"></div>
    <div class="two">

      <h2 class="title">CJs Pizza Place</h2>

    </div>
    <div class="three"></div>

  </div>

</body>


问:
Problem with MySQL while using 'WITH' clause to manage hierachical data
I am having a hard time getting the following query to work correctly. I feel like I have everything set up correctly. I read that earlier versions of MySQL Workbench did not support 'with'. I updated Ubuntu and am running MySQL Workbench 8.0.20. However, when I try to use the 'with' clause, MySQL keeps telling me that with is not valid at the position for the server version. The goal is to list my data in a hierarchical fashion. For this I am using one table with TestCat_2 as my primary key and a Parent_id. I haven't really done a query like this before so I hope it is just something simple I am missing. For an example of what I am trying to accomplish, I will post the URLs of two blogs I was trying to follow. I would like to display the whole tree. Otherwise, if anyone could help me find a workaround I would appreciate it.

https://www.mysqltutorial.org/mysql-adjacency-list-tree/

https://www.akki.io/blog/mysql-adjacency-list-model-for-hierarchical-data-using-cte/

My Query:

```<code>WITH RECURSIVE category_path (TestCat_2, TestCat2_name, path) as

(

select TestCat_2, TestCat2_name, TestCat2_name as path
from TestCat
where Parent_id is null

union all

select t.TestCat_2, t.TestCat2_name, concat(tp.path, ' > ', t.TestCat2_name)
from category_path as tp join TestCat as t
on tp.TestCat_2 = t.Parent_id

)

select TestCat_2, TestCat2_name, path from category_path
order by path;
</code>```

答: You must use a MySQL server which supports this language construct. Common Table Expressions (CTE) were introduced in MySQL 8.0.</p>

Body:
I am having a hard time getting the following query to work correctly. I feel like I have everything set up correctly. I read that earlier versions of MySQL Workbench did not support 'with'. I updated Ubuntu and am running MySQL Workbench 8.0.20. However, when I try to use the 'with' clause, MySQL keeps telling me that with is not valid at the position for the server version. The goal is to list my data in a hierarchical fashion. For this I am using one table with TestCat_2 as my primary key and a Parent_id. I haven't really done a query like this before so I hope it is just something simple I am missing. For an example of what I am trying to accomplish, I will post the URLs of two blogs I was trying to follow. I would like to display the whole tree. Otherwise, if anyone could help me find a workaround I would appreciate it.

https://www.mysqltutorial.org/mysql-adjacency-list-tree/

https://www.akki.io/blog/mysql-adjacency-list-model-for-hierarchical-data-using-cte/

My Query:

WITH RECURSIVE category_path (TestCat_2, TestCat2_name, path) as

(

select TestCat_2, TestCat2_name, TestCat2_name as path
from TestCat
where Parent_id is null

union all

select t.TestCat_2, t.TestCat2_name, concat(tp.path, ' > ', t.TestCat2_name)
from category_path as tp join TestCat as t
on tp.TestCat_2 = t.Parent_id

)

select TestCat_2, TestCat2_name, path from category_path
order by path;


问:
IOS App Created Wholly with HTML 5 - Input lag... fixable?
Like many others, I have decided to build my app via HTML 5, with limited native code (some of the UI and whatnot). However, I have run into a critical problem related to the UX. It seems that input boxes and buttons created via HTML 5 always have a longer lag time in recognizing their click event then the native interface.

For example:

A button created using UIButton and native code, when pressed, will immediately register the click and immediately flip me to the next page.

However...

A button created through HTML5 in the UIWebView always has a 500-1500 MS lag time before registering the click... which results in a very disjointed and fragmented user experience.

My question to you... is there any way to solve this problem via actually pushing the users touch event quicker somehow, or even by faking it to make it look like the HTML5 input boxes are giving instant feedback?

Thank you very much for your assistance everyone. :)

答:
I believe this could be because MobileSafari has the double-tap gesture for zooming, which means that a single tap will have a slight delay while the system waits for a possible second tap.

A possible solution using touchStart/touchMove/touchEnd events is detailed here


问:
How to store Pagination data in ViewModel Android?
On rotating the device I am losing the previous page loaded page data. How can I resolve this?

With below implementation, only the data of the current page is persisted in the ViewModel but all other pages are lost. Any solution for this?

API response (Page 1)
http://www.mocky.io/v2/5ed20f9732000052005ca0a6

ViewModel

```<code>class NewsApiViewModel(application: Application) : AndroidViewModel(application) {

    val topHeadlines = MutableLiveData<TopHeadlines>()
    var networkLiveData = MutableLiveData<Boolean>()

    fun fetchTopHeadlines(pageNumber: Int) {
        if (!getApplication<Application>().hasNetworkConnection()) {
            networkLiveData.value = false
        }
        val destinationService = ServiceBuilder.buildService(DestinationService::class.java)
        val requestCall = destinationService.getTopHeadlines(AppConstants.COUNTRY_INDIA, AppConstants.PAGE_SIZE, pageNumber, AppConstants.NEWS_API_KEY)
        requestCall.enqueue(object : Callback<TopHeadlines> {
            override fun onFailure(call: Call<TopHeadlines>, t: Throwable) {
                Log.e("ANKUSH", "$t ")
            }

            override fun onResponse(call: Call<TopHeadlines>, response: Response<TopHeadlines>) {
                if (response.isSuccessful) {
                    topHeadlines.postValue(response.body())
                }
            }
        })
    }

}
</code>```

MainActivity

```<code>fun observeAndUpdateData() {
        activity.viewModel.topHeadlines.observeForever {
            isDataLoading = false
            checkAndShowLoader(isDataLoading)
            if (AppConstants.STATUS_OK == it.status) {
                it.articles?.let { articles ->
                    if (articles.size < AppConstants.PAGE_SIZE) {
                        activity.isAllDataLoaded = true
                    }
                    activity.adapter.updateData(articles)
                }
            }
        }
    }

fun getTopHeadlines(pageNumber: Int) {
        if (activity.isAllDataLoaded) return
        isDataLoading = true
        checkAndShowLoader(isDataLoading)
        activity.viewModel.fetchTopHeadlines(pageNumber)
    }
</code>```

答:
You just need to store the current page and the data you gathered in a list in the ViewModel.

So don't pass the page number to the fetchTopHeadlines function, instead, consider having a private global variable in the ViewModel and everytime that you call the fetchTopHeadlines, increment the page number too.

Also to prevent loss of previous pages, Consider having an ArrayList in your ViewModel. After fetching the data from server, first put all your data in the list defined in the ViewModel and then publish that list to your View.

Here is a sample that helps you dealing with it.

Body:
On rotating the device I am losing the previous page loaded page data. How can I resolve this?

With below implementation, only the data of the current page is persisted in the ViewModel but all other pages are lost. Any solution for this?

API response (Page 1)
http://www.mocky.io/v2/5ed20f9732000052005ca0a6

ViewModel

class NewsApiViewModel(application: Application) : AndroidViewModel(application) {

    val topHeadlines = MutableLiveData<TopHeadlines>()
    var networkLiveData = MutableLiveData<Boolean>()

    fun fetchTopHeadlines(pageNumber: Int) {
        if (!getApplication<Application>().hasNetworkConnection()) {
            networkLiveData.value = false
        }
        val destinationService = ServiceBuilder.buildService(DestinationService::class.java)
        val requestCall = destinationService.getTopHeadlines(AppConstants.COUNTRY_INDIA, AppConstants.PAGE_SIZE, pageNumber, AppConstants.NEWS_API_KEY)
        requestCall.enqueue(object : Callback<TopHeadlines> {
            override fun onFailure(call: Call<TopHeadlines>, t: Throwable) {
                Log.e("ANKUSH", "$t ")
            }

            override fun onResponse(call: Call<TopHeadlines>, response: Response<TopHeadlines>) {
                if (response.isSuccessful) {
                    topHeadlines.postValue(response.body())
                }
            }
        })
    }

}

MainActivity

fun observeAndUpdateData() {
        activity.viewModel.topHeadlines.observeForever {
            isDataLoading = false
            checkAndShowLoader(isDataLoading)
            if (AppConstants.STATUS_OK == it.status) {
                it.articles?.let { articles ->
                    if (articles.size < AppConstants.PAGE_SIZE) {
                        activity.isAllDataLoaded = true
                    }
                    activity.adapter.updateData(articles)
                }
            }
        }
    }

fun getTopHeadlines(pageNumber: Int) {
        if (activity.isAllDataLoaded) return
        isDataLoading = true
        checkAndShowLoader(isDataLoading)
        activity.viewModel.fetchTopHeadlines(pageNumber)
    }


问:
Start scrolling before overflow when dragging the recyclerview item in Android
Controlling the drag and drop events with ItemTouchHelper.SimpleCallback on my RecyclerView as follow:

```<code>@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {

    int fromPosition = viewHolder.getAdapterPosition();
    int toPosition = target.getAdapterPosition();

    Collections.swap(adapter.getShelves(), fromPosition, toPosition);
    adapter.notifyItemMoved(fromPosition, toPosition);

    return true;
}
</code>```

The item dragging with a long press. When the dragging item overflows the screen, the scrolling is starting to its direction by stages normally. The part of the holder for dragging is top of the item so there isn't any problem when dragging down but dragging up is very difficult for people because the fingers overflow the device. How to start dragging to up/down when don't just reached, or before certain margin to screen bounds?

答:
your can use library github link

add to dependencies:

```<code>   dependencies {
    implementation 'com.thesurix.gesturerecycler:gesture-recycler:1.11.0'
}
</code>```

and kotlin:

```<code>    // Define your RecyclerView and adapter as usually
val manager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = manager

// Extend GestureAdapter and write your own
// ViewHolder items must extend GestureViewHolder
val adapter = MonthsAdapter(R.layout.linear_item)
adapter.data = months
recyclerView.adapter = adapter
</code>```

and Swipe:

```<code> val gestureManager = GestureManager.Builder(recyclerView)
                 // Enable swipe
                .setSwipeEnabled(true)
                 // Enable long press drag and drop
                .setLongPressDragEnabled(true)
                 // Enable manual drag from the beginning, you need to provide View inside your GestureViewHolder
                .setManualDragEnabled(true)
                 // Use custom gesture flags
                 // Do not use those methods if you want predefined flags for RecyclerView layout manager
                .setSwipeFlags(ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
                .setDragFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN)
                .build()
</code>```

Body:
Controlling the drag and drop events with ItemTouchHelper.SimpleCallback on my RecyclerView as follow:

@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {

    int fromPosition = viewHolder.getAdapterPosition();
    int toPosition = target.getAdapterPosition();

    Collections.swap(adapter.getShelves(), fromPosition, toPosition);
    adapter.notifyItemMoved(fromPosition, toPosition);

    return true;
}

The item dragging with a long press. When the dragging item overflows the screen, the scrolling is starting to its direction by stages normally. The part of the holder for dragging is top of the item so there isn't any problem when dragging down but dragging up is very difficult for people because the fingers overflow the device. How to start dragging to up/down when don't just reached, or before certain margin to screen bounds?

Body:
your can use library github link

add to dependencies:

   dependencies {
    implementation 'com.thesurix.gesturerecycler:gesture-recycler:1.11.0'
}

and kotlin:

    // Define your RecyclerView and adapter as usually
val manager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = manager

// Extend GestureAdapter and write your own
// ViewHolder items must extend GestureViewHolder
val adapter = MonthsAdapter(R.layout.linear_item)
adapter.data = months
recyclerView.adapter = adapter

and Swipe:

 val gestureManager = GestureManager.Builder(recyclerView)
                 // Enable swipe
                .setSwipeEnabled(true)
                 // Enable long press drag and drop
                .setLongPressDragEnabled(true)
                 // Enable manual drag from the beginning, you need to provide View inside your GestureViewHolder
                .setManualDragEnabled(true)
                 // Use custom gesture flags
                 // Do not use those methods if you want predefined flags for RecyclerView layout manager
                .setSwipeFlags(ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
                .setDragFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN)
                .build()


问:
How do you encode an apostrophe so that it's searchable in mysql?
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

```<code>mov_title = '$search_keywords'
</code>```

it all works, but this method will not yield any results for partial searches, so I have to use this

```<code>mov_title LIKE '%$search_keywords%'
</code>```

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

```<code>$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));
</code>```

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

答: If you prefer to keep your database intact, you could just run the htmlspecialchars() function on any search words you are looking for before constructing the query. Though I recommend putting the data into the database exactly as is, (but use mysql_real_escape_string() to escape it to hinder sql injection attempts). Then use htmlspecialchars() when you are printing the data to the browser.</p>

LastEditorDisplayName: Jonathan Leffler

Body:
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

mov_title = '$search_keywords'

it all works, but this method will not yield any results for partial searches, so I have to use this

mov_title LIKE '%$search_keywords%'

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

LastEditorDisplayName: lubos hasko


问:
JQuery is not working because Mootools is already loaded in joomla
I tried to include the JQuery lib into joomla but it's not working. Many comps and modules use mootools inside my CMS. I think the problem is a conflict between the two frameworks.

I have searched the internet and found some articles but the following code is still not working as expected.

```<code><?php
JHTML::stylesheet('demo_page.css', 'media/system/css/');
JHTML::stylesheet('ftab.css', 'media/system/css/');
JHTML::stylesheet('demo_table.css', 'media/system/css/');
$option="com_mycomp";
$base=JUri::root().'components/'.$option.'/js/';
$document=&JFactory::getDocument();
$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");
JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');
?>
</code>```

This should sort my table using JQuery but it does not.

How do I use mootools and jQuery concurrently in joomla ?

Thank you in advance for your help!

答:
Reading your code, I see this:

```<code>$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");
JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');
</code>```

but it should look like this:

```<code>JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');
$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");
</code>```

Now, here's why:

Javascript is interpreted in the order it comes to the page. The page is being told to use jQuery.noConflict() and the jQuery datatable, before it knows what those things are.

Body:
I tried to include the JQuery lib into joomla but it's not working. Many comps and modules use mootools inside my CMS. I think the problem is a conflict between the two frameworks.

I have searched the internet and found some articles but the following code is still not working as expected.

<?php
JHTML::stylesheet('demo_page.css', 'media/system/css/');
JHTML::stylesheet('ftab.css', 'media/system/css/');
JHTML::stylesheet('demo_table.css', 'media/system/css/');
$option="com_mycomp";
$base=JUri::root().'components/'.$option.'/js/';
$document=&JFactory::getDocument();
$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");
JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');
?>

This should sort my table using JQuery but it does not.

How do I use mootools and jQuery concurrently in joomla ?

Thank you in advance for your help!

Body:
Reading your code, I see this:

$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");
JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');

but it should look like this:

JHTML::script('jquery.js',$base,true);
$document->addScript($base,'jquery.js');
$document->addScript($base,'jquery.dataTables.js');
$noConflict="jQuery.noConflict();";
//$document->addScriptDeclaration($noConflict);
$document->addScriptDeclaration("jQuery(document).ready(function($){jQuery('#example').dataTable();});");

Now, here's why:

Javascript is interpreted in the order it comes to the page. The page is being told to use jQuery.noConflict() and the jQuery datatable, before it knows what those things are.


问:
How to correctly create new class instance and handle to him?
I created bots panel and to setup a new bot I create new class instance:

```<code>global.bots[account.name] = new Bot(account);
</code>```

How much correct record new bot in global variable, for to access its methods? Example:

```<code>global.bots[account.name].stopBot
</code>```

Sorry, if my question seems dumb, but I am a newbie. Hope for understanding.

答:
to access a method usually () are required and when arguments are needed try (<argument1>, <argument2>)

in your example

```<code>global.bots[account.name].stopBot()
</code>```

Body:
I created bots panel and to setup a new bot I create new class instance:

global.bots[account.name] = new Bot(account);

How much correct record new bot in global variable, for to access its methods? Example:

global.bots[account.name].stopBot

Sorry, if my question seems dumb, but I am a newbie. Hope for understanding.

Body:
to access a method usually () are required and when arguments are needed try (<argument1>, <argument2>)

in your example

global.bots[account.name].stopBot()


问:
Changing display of element in Selenium Python does not work
I want to upload a file using Selenium, but first I need to make the input element visible. It looks like that:

```<code><input class="tb_sK" type="file">
</code>```

I tried changing the style.display using JavaScript with this code:

```<code>js = "arguments[0].style.display='block'"
driver.execute_script(js, upload_button)
</code>```

The input now looks like this but is still invisible :

```<code><input class="tb_sK" type="file" style="display: block;">
</code>```

I'm not very familiar with html, but in the devtools, I saw this :
input

There is nothing in element.style and the 'display' is in .tb_sK. So I think I must change this.

How can I do it ?

答:
You could try removing the class attribute:

driver.execute_script("arguments[0].removeAttribute('class')", upload_button)
```

This way the input won't be affected by the CSS rule you showed in your print and thus won't be invisible anymore.

Body:
I want to upload a file using Selenium, but first I need to make the input element visible. It looks like that:

<input class="tb_sK" type="file">

I tried changing the style.display using JavaScript with this code:

js = "arguments[0].style.display='block'"
driver.execute_script(js, upload_button)

The input now looks like this but is still invisible :

<input class="tb_sK" type="file" style="display: block;">

I'm not very familiar with html, but in the devtools, I saw this :
input

There is nothing in element.style and the 'display' is in .tb_sK. So I think I must change this.

How can I do it ?

Body:
You could try removing the class attribute:

driver.execute_script("arguments[0].removeAttribute('class')", upload_button)

This way the input won't be affected by the CSS rule you showed in your print and thus won't be invisible anymore.


问:
angular material mat-select drop-down width
The current drop-down box has width greater than the the width of the line:

Is there a way to get rid of the extra width?

Here is my current code:

html:

```<code><mat-form-field>
    <mat-select disableOptionCentering placeholder="Choose an option">
      <mat-option [value]="option" *ngFor="let option of my_list">
          {{ option }}
      </mat-option>
    </mat-select>
</mat-form-field>
</code>```

my_list:

```<code>export const my_list: string[] = [ "a", "b", "c", "d"];
</code>```

style.css:

```<code>.mat-select-panel{
    margin-left: 15px;
    margin-top: 28px;
}
</code>```

答:
set width at mat-form-field tag level.
 try this,</p>

```<code><mat-form-field style="width:50px">
</code>```

Body:
The current drop-down box has width greater than the the width of the line:

Is there a way to get rid of the extra width?

Here is my current code:

html:

<mat-form-field>
    <mat-select disableOptionCentering placeholder="Choose an option">
      <mat-option [value]="option" *ngFor="let option of my_list">
          {{ option }}
      </mat-option>
    </mat-select>
</mat-form-field>

my_list:

export const my_list: string[] = [ "a", "b", "c", "d"];

style.css:

.mat-select-panel{
    margin-left: 15px;
    margin-top: 28px;
}

Body:
set width at mat-form-field tag level.
 try this,

<mat-form-field style="width:50px">