答:
Firstly you need to add it to crontab,try:

sudo nano /etc/crontab

and after that you can put your service:

 * * * * * cd /home/kali && /usr/bin/python3.8 /home/kali/time.py

Check it again 'sudo crontab -e'

Title: How do I execute cron service in linux?

Body:
I am trying to run a Python code every minute in Linux but at loss to configure cron service.  Following is what I added after running 'crontab -e' but nothing is happening.

* * * * * cd /home/kali && /usr/bin/python3.8 /home/kali/time.py

time.py contains simple code to show current time.

from datetime import datetime
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

Any suggestions?


来源: stackexchange

问:
JSON format to Data Frame in Python
I am reading API data from the cloud server in JSON format as shown here

How to write a code to store this data frame into the data frame in any database. How to convert JSON format to DataFrame?

The requirement output format is shown in table2

答:
To help others also, here is an example with nested json. I have tried to make this similar to the example you showed in your question.

```<code>import json
import pandas as pd
import pandas.io.json as pd_json
jsondata = '''
{
    "source": { "id": "2480300" },
    "time": "2013-07-02T16:32:30.152+02:00",
    "type": "huawei_E3131SignalStrength",
    "c8y_SignalStrength": {
        "rssi": { "value": -53, "unit": "dBm" },
        "ber": { "value": 0.14, "unit": "%" }
    }
}

'''

data = pd_json.loads(jsondata) #load
df=pd_json.json_normalize(data) #normalise
df
</code>```

Result:

```<code>   c8y_SignalStrength.ber.unit  c8y_SignalStrength.ber.value    c8y_SignalStrength.rssi.unit    c8y_SignalStrength.rssi.value   source.id   time    type
  % 0.14    dBm -53 2480300 2013-07-02T16:32:30.152+02:00   huawei_E3131SignalStrength
</code>```

ContentLicense: CC BY-SA 4.0

Title: JSON format to Data Frame in Python

Body:
To help others also, here is an example with nested json. I have tried to make this similar to the example you showed in your question.

import json
import pandas as pd
import pandas.io.json as pd_json
jsondata = '''
{
    "source": { "id": "2480300" },
    "time": "2013-07-02T16:32:30.152+02:00",
    "type": "huawei_E3131SignalStrength",
    "c8y_SignalStrength": {
        "rssi": { "value": -53, "unit": "dBm" },
        "ber": { "value": 0.14, "unit": "%" }
    }
}

'''

data = pd_json.loads(jsondata) #load
df=pd_json.json_normalize(data) #normalise
df

Result:

   c8y_SignalStrength.ber.unit  c8y_SignalStrength.ber.value    c8y_SignalStrength.rssi.unit    c8y_SignalStrength.rssi.value   source.id   time    type
  % 0.14    dBm -53 2480300 2013-07-02T16:32:30.152+02:00   huawei_E3131SignalStrength


问:
how to preview image before upload in ionic 3?
i am trying to upload and preview image using jquery. But getting this

Error

```<code>Property 'result' does not exist on type 'EventTarget'.
reader.onload = function (e) {
 $('#blah').attr('src', e.target.result);
}
</code>```

page.ts

```<code>function readURL(input) {

  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$('#file').on('change', function () {
  readURL(this);
});
</code>```

page.html

```<code> <label for="file" class="lbl"><i class="fa fa-plus-circle"></i>   Add Attachment</label>
<input type="file" id="file" style="visibility: hidden">
<img src="#" id="blah">
</code>```

what will be the solution?? i think this code is correct but just the problem is 'result' property. Thanks in advance

答:
for ionic 4

In html

```<code>        <img class="logo" src="{{img_new}}" *ngIf="img_new!=''"/>

        <input type="file" name="image" accept="image/*" (change)="changeListener($event)">
</code>```

In ts

```<code>changeListener($event): void {
        this.file = $event.target.files[0];
    console.log(this.file);
    let reader = new FileReader();
      reader.onload = ($event:any) => {
        this.img_new = $event.target.result;
      }
      reader.readAsDataURL($event.target.files[0]);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to upload and preview image using jquery. But getting this

Error

Property 'result' does not exist on type 'EventTarget'.
reader.onload = function (e) {
 $('#blah').attr('src', e.target.result);
}

page.ts

function readURL(input) {

  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$('#file').on('change', function () {
  readURL(this);
});

page.html

    Add Attachment
<input type="file" id="file" style="visibility: hidden">

what will be the solution?? i think this code is correct but just the problem is 'result' property. Thanks in advance

Body:
for ionic 4

In html

        <img class="logo" src="{{img_new}}" *ngIf="img_new!=''"/>

        <input type="file" name="image" accept="image/*" (change)="changeListener($event)">

In ts

changeListener($event): void {
        this.file = $event.target.files[0];
    console.log(this.file);
    let reader = new FileReader();
      reader.onload = ($event:any) => {
        this.img_new = $event.target.result;
      }
      reader.readAsDataURL($event.target.files[0]);
    }


问:
Order by 3 columns value String.Length
I want to order my DataTable CC by length of 3 columns value. Only for one it's working:

```<code>IEnumerable<DataRow> preCC = from r in CC.AsEnumerable()
                                     orderby r.Field<string>("Col_1").Length descending
                                     select r;
</code>```

But I need order by r.Field<string>("Col_1").Length, r.Field<string>("Col_2").Length and r.Field<string>("Col_3").Length at the same time.

答:
You can use the ThenBy method, something like this:

```<code>CC.AsEnumerable()
         .OrderByDescending(c => c.r.Field<string>("Col_1").Length)
         .ThenByDescending(c => OrderByDescending(c => c.r.Field<string>("Col_2").Length))
         .ThenByDescending(c => OrderByDescending(c => c.r.Field<string>("Col_3").Length))
</code>```

Title: Order by 3 columns value String.Length

Body:
I want to order my DataTable CC by length of 3 columns value. Only for one it's working:

IEnumerable<DataRow> preCC = from r in CC.AsEnumerable()
                                     orderby r.Field<string>("Col_1").Length descending
                                     select r;

But I need order by r.Field<string>("Col_1").Length, r.Field<string>("Col_2").Length and r.Field<string>("Col_3").Length at the same time.

Body:
You can use the ThenBy method, something like this:

CC.AsEnumerable()
         .OrderByDescending(c => c.r.Field<string>("Col_1").Length)
         .ThenByDescending(c => OrderByDescending(c => c.r.Field<string>("Col_2").Length))
         .ThenByDescending(c => OrderByDescending(c => c.r.Field<string>("Col_3").Length))


问:
(Swift) How to get rid of "Left side of mutating operator isn't mutable"
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

```<code>func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}
</code>```

handleTap function :

```<code>@objc
func handleTap(_ someString: String) {
     someString += "my"
}
</code>```

答:
For passing parameters using UITapGestureRecognizer, One approach would be to subClass UITapGestureRecognizer and then set a property as example below:

```<code>class SampleGesture: UITapGestureRecognizer {
    var someString = String()
}

class ViewController: UIViewController {

    let tapGesture = SampleGesture(target: self, action: #selector(self.handleTap))
    tapGesture.delegate = self
    webView.addGestureRecognizer(tapGesture)
    tapGesture.someString = //your text
}
</code>```

And as for error others already said in answers that Parameters of a function are 'constants' by default

```<code>@objc func handleTap(sender: SampleGesture) {
     var newTitle: String = sender.someString   // you can declare as globally
     newTitle += "my"
}
</code>```

Body:
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}

handleTap function :

@objc
func handleTap(_ someString: String) {
     someString += "my"
}

Body:
For passing parameters using UITapGestureRecognizer, One approach would be to subClass UITapGestureRecognizer and then set a property as example below:

class SampleGesture: UITapGestureRecognizer {
    var someString = String()
}

class ViewController: UIViewController {

    let tapGesture = SampleGesture(target: self, action: #selector(self.handleTap))
    tapGesture.delegate = self
    webView.addGestureRecognizer(tapGesture)
    tapGesture.someString = //your text
}

And as for error others already said in answers that Parameters of a function are 'constants' by default

@objc func handleTap(sender: SampleGesture) {
     var newTitle: String = sender.someString   // you can declare as globally
     newTitle += "my"
}


问:
Don't understand interval join in Flink
From Flink's official doc:

https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/joining.html#interval-join

The example code is:

```<code>import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;

...

val orangeStream: DataStream[Integer] = ...
val greenStream: DataStream[Integer] = ...

orangeStream
    .keyBy(elem => /* select key */)
    .intervalJoin(greenStream.keyBy(elem => /* select key */))
    .between(Time.milliseconds(-2), Time.milliseconds(1))
    .process(new ProcessJoinFunction[Integer, Integer, String] {
        override def processElement(left: Integer, right: Integer, ctx: ProcessJoinFunction[Integer, Integer, String]#Context, out: Collector[String]): Unit = {
         out.collect(left + "," + right);
        }
      });
    });
</code>```

From the above code, I would like know how to specify the starting time(eg, from the beginning of today) from which to perform this interval join(the data before the starting time will not take into account).

eg, I have run the program for 3 days, I don't want to perform this join for all the data for 3 days,
I just want to perform the join for the data generated today.

答:
I don't think it works like You think it does.

The actual interval is calculated based on the actual timestamps of orangeStream in this case, so You are not really providing the interval of the data You want to take in account, but rather this is something like window which specifies which elements will be joined with the given element of the orange stream.

So, for the window described above if You have orange element with timestamp 5, then it will be joined with elements that have timestamps from 3 to 6.

I really don't think You could use it to perform joins only with some part of the data, the only think I can think of is to simply filter the data using the timestamps and filter out all elements that have been generated earlier.

Title: Don't understand interval join in Flink

Body:
From Flink's official doc:

https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/stream/operators/joining.html#interval-join

The example code is:

import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;

...

val orangeStream: DataStream[Integer] = ...
val greenStream: DataStream[Integer] = ...

orangeStream
    .keyBy(elem => /* select key */)
    .intervalJoin(greenStream.keyBy(elem => /* select key */))
    .between(Time.milliseconds(-2), Time.milliseconds(1))
    .process(new ProcessJoinFunction[Integer, Integer, String] {
        override def processElement(left: Integer, right: Integer, ctx: ProcessJoinFunction[Integer, Integer, String]#Context, out: Collector[String]): Unit = {
         out.collect(left + "," + right);
        }
      });
    });

From the above code, I would like know how to specify the starting time(eg, from the beginning of today) from which to perform this interval join(the data before the starting time will not take into account).

eg, I have run the program for 3 days, I don't want to perform this join for all the data for 3 days,
I just want to perform the join for the data generated today.


问:
Input value must be equal to some value in database
So i have this simple code to select value from database in registration form and it's work great

```<code><div id="ref1" class="form-group form-material floating">
    <select class="form-control" name="reference" id="reference">
      @foreach (App\Models\Reference::getReference() as $key => $value)
        <option value="" selected disabled hidden></option>
        <option value="{{$value->id}}">{{$value->reference}}</option>
      @endforeach
    </select>
    <label class="floating-label" for="inputStatus">Reference</label>
</div>
</code>```

But i want to change this into input field, so when user type it manually and it's not having the same value in the database, the registration will fail (Error Message : 'Wrong reference code'), does anyone have and idea how to do it? Thanks

Edit 1 :
I also have this validation code for the reference

```<code>reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Reference maximal 8 digit'
                }
            }
        }
</code>```

Can i also use exists rule on that validator?

答:
This can be done by creating custom Laravel Request validation. If your reference is stored in database, you can check if the input value exists in database, after the form is submitted by using exists rule. Here's a simple example:

```<code>    public function rules()
    {
        return [
            'field_name' => 'exists:your_table_name', //Table name where reference is stored
        ];
    }
    public function messages()
    {
        return [
            'field_name.exists' => 'Wrong reference code',
        ];
    }
</code>```

You can read more on official documentation.

Body:
So i have this simple code to select value from database in registration form and it's work great

    <select class="form-control" name="reference" id="reference">
      @foreach (App\Models\Reference::getReference() as $key => $value)
        <option value="" selected disabled hidden></option>
        <option value="{{$value->id}}">{{$value->reference}}</option>
      @endforeach
    </select>
    Reference

But i want to change this into input field, so when user type it manually and it's not having the same value in the database, the registration will fail (Error Message : 'Wrong reference code'), does anyone have and idea how to do it? Thanks

Edit 1 :
I also have this validation code for the reference

reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Reference maximal 8 digit'
                }
            }
        }

Can i also use exists rule on that validator?

Body:
This can be done by creating custom Laravel Request validation. If your reference is stored in database, you can check if the input value exists in database, after the form is submitted by using exists rule. Here's a simple example:

    public function rules()
    {
        return [
            'field_name' => 'exists:your_table_name', //Table name where reference is stored
        ];
    }
    public function messages()
    {
        return [
            'field_name.exists' => 'Wrong reference code',
        ];
    }

You can read more on official documentation.


问:
exclude directories with the same name ending
I'm trying to write a shell script that runs commands on all folders except the ones with  names ending with "_long" and "_wavs".

This is what I have tried:

```<code>dirs=($(find /Volumes/exchange -type d))

for dir in "${dirs[@]}/!(`basename "$dir"`_long|`basename "$dir"`_wavs)/";
do
   *commands*
done
</code>```

答:
A simple for loop with find excluding dirs with certain names :

```<code>for dir in $(find /Volumes/exchange -type d ! -name "*_wavs" ! -name "*_long")
do
    # commands on "$dir"
done
</code>```

Body:
I'm trying to write a shell script that runs commands on all folders except the ones with  names ending with "_long" and "_wavs".

This is what I have tried:

dirs=($(find /Volumes/exchange -type d))

for dir in "${dirs[@]}/!(`basename "$dir"`_long|`basename "$dir"`_wavs)/";
do
   *commands*
done

Body:
A simple for loop with find excluding dirs with certain names :

for dir in $(find /Volumes/exchange -type d ! -name "*_wavs" ! -name "*_long")
do
    # commands on "$dir"
done


问:
How can I make this construction simpler, like with classes or functions in python?
```<code>print(
    "1. Engine block \n"
    "2. Pistons \n"
    "3. Crankshaft \n"
    "4. Camshaft \n"
    "5. Cylinder head \n"
    "6. Connecting Rod \n"
)

part = int(input("Choose an engine part to show you details about it: "))

if part == 1:
    print("Engine block")
elif part == 2:
    print("Pistons")
elif part == 3:
    print("Crankshaft")
</code>```

I have 26 statements like these and I wonder if I can make it simpler with classes,

functions, lists or something I can't find a way??

答:
If you really want an extra function</p>

```<code>print(
    "1. Engine block\n"
    "2. Pistons\n"
    "3. Crankshaft\n"
    "4. Camshaft\n"
    "5. Cylinder head\n"
    "6. Connecting Rod\n"
)

def list_dict():
    return {1: "Engine block", 2: "Pistons", 3: "Crankshaft"}

def ans(part):
    return list_dict()[part]

part = int(input("Choose an engine part to show you details about it: "))
print(ans(part))
</code>```

Body:
print(
    "1. Engine block \n"
    "2. Pistons \n"
    "3. Crankshaft \n"
    "4. Camshaft \n"
    "5. Cylinder head \n"
    "6. Connecting Rod \n"
)

part = int(input("Choose an engine part to show you details about it: "))

if part == 1:
    print("Engine block")
elif part == 2:
    print("Pistons")
elif part == 3:
    print("Crankshaft")

I have 26 statements like these and I wonder if I can make it simpler with classes,

functions, lists or something I can't find a way??

Body:
If you really want an extra function

print(
    "1. Engine block\n"
    "2. Pistons\n"
    "3. Crankshaft\n"
    "4. Camshaft\n"
    "5. Cylinder head\n"
    "6. Connecting Rod\n"
)

def list_dict():
    return {1: "Engine block", 2: "Pistons", 3: "Crankshaft"}

def ans(part):
    return list_dict()[part]

part = int(input("Choose an engine part to show you details about it: "))
print(ans(part))


问:
Can an application distributed using Mac Apple Store auto-update its database?
The Mac Apple Store Approval Guidelines states that:

2.21 Apps may not use update mechanisms outside of the App Store

Now, if you develop an application that is something like a dictionary and you want to update the data often (maybe daily), the Mac App Store update mechanism is useless because it would require Apple approval.

The question is if such an application, that is apple to update it's database by itself, will be accepted by Apple.

I am not sending this question to Apple because, at this moment I do not have an OS X developer account.

答: I think that guideline is referring to updates of the App itself. I think if you alert users that the app will be downloading a new database, you should be fine.</p>


问:
How to have text views that move along the progress bar
Context: I want to build a horizontal progress bar with some values and want to put some text that move along below this progress bar. So my final ideia is something like this (I already have the progress bar built I only left the text views below)

My current code is something like this:

This is my StackedHorizontalProgressBar class:

```<code>public class StackedHorizontalProgressBar extends ProgressBar {
  private Paint paint;
  int primary_progress, max_value;

  public StackedHorizontalProgressBar(Context context) {
    super(context);
    init();
  }

  public StackedHorizontalProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  @Override public synchronized void setMax(int max) {
    this.max_value = max;
    super.setMax(max);
  }

  @Override public synchronized void setProgress(int progress) {
    if (progress > max_value) {
      progress = max_value;
    }
    this.primary_progress = progress;
    super.setProgress(progress);
  }

  @Override public synchronized void setSecondaryProgress(int secondaryProgress) {
    if ((primary_progress + secondaryProgress) > max_value) {
      secondaryProgress = (max_value - primary_progress);
    }
    super.setSecondaryProgress(primary_progress + secondaryProgress);
  }

  private void init() {
    paint = new Paint();
    paint.setColor(Color.BLACK);
    primary_progress = 0;
    max_value = 100;
  }
}
</code>```

This is my Main Activity layout (that uses above class)

```<code><android.support.constraint.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

  <github.nisrulz.stackedhorizontalprogressbar.StackedHorizontalProgressBar
      android:id="@+id/stackedhorizontalprogressbar"
      style="?android:attr/progressBarStyleHorizontal"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="16dp"
      android:progressDrawable="@drawable/stacked_horizontal_progress"
      app:layout_constraintTop_toTopOf="parent"
      tools:layout_editor_absoluteX="16dp" />

</android.support.constraint.ConstraintLayout>
</code>```

This is my MainActivity class:

```<code>public class MainActivity extends AppCompatActivity {

    int max = 100;
    int countPrimary = 20;
    int countSecondary = 30;
    StackedHorizontalProgressBar stackedHorizontalProgressBar;

    TextView txt_primary, txt_secondary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        stackedHorizontalProgressBar =
                (StackedHorizontalProgressBar) findViewById(R.id.stackedhorizontalprogressbar);
        stackedHorizontalProgressBar.setMax(max);

        stackedHorizontalProgressBar.setProgress(countPrimary);
        txt_primary.setText("Primary Value : " + countPrimary + "%");

        stackedHorizontalProgressBar.setSecondaryProgress(countSecondary);
        txt_secondary.setText("Secondary Value : " + countSecondary + "%");

    }

}
</code>```

I think I must use canvas for this, so if there is anyone with experience with this that can help me.

答:
```<code>public class ProgressBarAvtivity extends AppCompatActivity {
ProgressBar progressBar;
TextView tvProgress;
    int d = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar_avtivity);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setProgress(d);
        tvProgress = (TextView)findViewById(R.id.tvProgress);
        tvProgress.setText(String.valueOf(d));
        if (d > 40) {
        tvProgress.setX(((width )* d / 100) - (d/2));
         }
        else {
        tvProgress.setX(((width )* d / 100));

    }
 }}
</code>```

Body:
Context: I want to build a horizontal progress bar with some values and want to put some text that move along below this progress bar. So my final ideia is something like this (I already have the progress bar built I only left the text views below)

My current code is something like this:

This is my StackedHorizontalProgressBar class:

public class StackedHorizontalProgressBar extends ProgressBar {
  private Paint paint;
  int primary_progress, max_value;

  public StackedHorizontalProgressBar(Context context) {
    super(context);
    init();
  }

  public StackedHorizontalProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  @Override public synchronized void setMax(int max) {
    this.max_value = max;
    super.setMax(max);
  }

  @Override public synchronized void setProgress(int progress) {
    if (progress > max_value) {
      progress = max_value;
    }
    this.primary_progress = progress;
    super.setProgress(progress);
  }

  @Override public synchronized void setSecondaryProgress(int secondaryProgress) {
    if ((primary_progress + secondaryProgress) > max_value) {
      secondaryProgress = (max_value - primary_progress);
    }
    super.setSecondaryProgress(primary_progress + secondaryProgress);
  }

  private void init() {
    paint = new Paint();
    paint.setColor(Color.BLACK);
    primary_progress = 0;
    max_value = 100;
  }
}

This is my Main Activity layout (that uses above class)

<android.support.constraint.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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

  <github.nisrulz.stackedhorizontalprogressbar.StackedHorizontalProgressBar
      android:id="@+id/stackedhorizontalprogressbar"
      style="?android:attr/progressBarStyleHorizontal"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="16dp"
      android:progressDrawable="@drawable/stacked_horizontal_progress"
      app:layout_constraintTop_toTopOf="parent"
      tools:layout_editor_absoluteX="16dp" />

</android.support.constraint.ConstraintLayout>

This is my MainActivity class:

public class MainActivity extends AppCompatActivity {

    int max = 100;
    int countPrimary = 20;
    int countSecondary = 30;
    StackedHorizontalProgressBar stackedHorizontalProgressBar;

    TextView txt_primary, txt_secondary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        stackedHorizontalProgressBar =
                (StackedHorizontalProgressBar) findViewById(R.id.stackedhorizontalprogressbar);
        stackedHorizontalProgressBar.setMax(max);

        stackedHorizontalProgressBar.setProgress(countPrimary);
        txt_primary.setText("Primary Value : " + countPrimary + "%");

        stackedHorizontalProgressBar.setSecondaryProgress(countSecondary);
        txt_secondary.setText("Secondary Value : " + countSecondary + "%");

    }

}

I think I must use canvas for this, so if there is anyone with experience with this that can help me.


问:
How does one get pdb.trace() working in unittest?
I am running commands such as:

```<code>python3 -m unittest -v -b core.tests.tests.TestApplication.test_name
</code>```

This freezes whenever it gets to import pdb(), pdb.set_trace().

Is there a way I can modify the code so that we can use debugger?

答: The solution is to remove -b, which buffers the string output.</p>

Body:
I am running commands such as:

python3 -m unittest -v -b core.tests.tests.TestApplication.test_name

This freezes whenever it gets to import pdb(), pdb.set_trace().

Is there a way I can modify the code so that we can use debugger?


问:
Python Pandas - Find rows where element is in row's array
I want to find all rows where a certain value is present inside the column's list value.

So imagine I have a dataframe set up like this:

```<code>|  placeID |                             users |
------------------------------------------------
|    134986|   [U1030, U1017, U1123, U1044...] |
|    133986|   [U1034, U1011, U1133, U1044...] |
|    134886|   [U1031, U1015, U1133, U1044...] |
|    134976|   [U1130, U1016, U1133, U1044...] |
</code>```

How can I get all rows where 'U1030' exists in the users column?

Or... is the real problem that I should not have my data arranged like this, and I should instead explode that column to have a row for each user?

What's the right way to approach this?

答:
When you are wanting to check whether a value exists inside the column when the value in the column is a list, it's helpful to use the map function.

Implementing it like below, with a lambda inline function, the list of values stored in the 'users' column is mapped to the value u, and userID is compared to it...

Really the answer is pretty straightforward when you look at the code below:

```<code>
# user_filter filters the dataframe to all the rows where
# 'userID' is NOT in the 'users' column (the value of which
# is a list type)
user_filter = df['users'].map(lambda u: userID not in u)

# cuisine_filter filters the dataframe to only the rows
# where 'cuisine' exists in the 'cuisines' column (the value
# of which is a list type)
cuisine_filter = df['cuisines'].map(lambda c: cuisine in c)

# Display the result, filtering by the weight assigned
df[user_filter & cuisine_filter]

</code>```

Body:
I want to find all rows where a certain value is present inside the column's list value.

So imagine I have a dataframe set up like this:

|  placeID |                             users |
------------------------------------------------
|    134986|   [U1030, U1017, U1123, U1044...] |
|    133986|   [U1034, U1011, U1133, U1044...] |
|    134886|   [U1031, U1015, U1133, U1044...] |
|    134976|   [U1130, U1016, U1133, U1044...] |

How can I get all rows where 'U1030' exists in the users column?

Or... is the real problem that I should not have my data arranged like this, and I should instead explode that column to have a row for each user?

What's the right way to approach this?

Body:
When you are wanting to check whether a value exists inside the column when the value in the column is a list, it's helpful to use the map function.

Implementing it like below, with a lambda inline function, the list of values stored in the 'users' column is mapped to the value u, and userID is compared to it...

Really the answer is pretty straightforward when you look at the code below:

# user_filter filters the dataframe to all the rows where
# 'userID' is NOT in the 'users' column (the value of which
# is a list type)
user_filter = df['users'].map(lambda u: userID not in u)

# cuisine_filter filters the dataframe to only the rows
# where 'cuisine' exists in the 'cuisines' column (the value
# of which is a list type)
cuisine_filter = df['cuisines'].map(lambda c: cuisine in c)

# Display the result, filtering by the weight assigned
df[user_filter & cuisine_filter]


问:
Liquibase updating mysql db with junk values
My Liquibase update changeset is given as below:

```<code><changeSet author="liquibase" id="6226">
    <update tableName="master">
    <column name="insighttype" valueNumeric="0"/>
    <where>id=1</where>
    </update>
</changeSet>
</code>```

While running liquibase command, in the log I see:

```<code>UPDATE db.master SET insighttype = 0 WHERE id=7
</code>```

But when I go back and check in the database:

```<code>+----+-----------------+-------------+
| id | insightname     | insighttype |
+----+-----------------+-------------+
|  1 | action_items    |             |
|  2 | sentiments      |             |
|  3 | wordcloud       |             |
|  4 | entity          |            |
|  5 | summary         |             |
|  6 | trade_info      |             |
|  7 | topic_modelling |            |
+----+-----------------+-------------+
</code>```

答:
In order to update boolean columns, you should use valueBoolean attribute.

E.G.

```<code><changeSet author="liquibase" id="6226">
    <update tableName="master">
        <column name="insighttype" valueBoolean="false"/>
        <where>id=1</where>
    </update>
</changeSet>
</code>```

Body:
My Liquibase update changeset is given as below:

<changeSet author="liquibase" id="6226">
    <update tableName="master">
    <column name="insighttype" valueNumeric="0"/>
    <where>id=1</where>
    </update>
</changeSet>

While running liquibase command, in the log I see:

UPDATE db.master SET insighttype = 0 WHERE id=7

But when I go back and check in the database:

+----+-----------------+-------------+
| id | insightname     | insighttype |
+----+-----------------+-------------+
|  1 | action_items    |             |
|  2 | sentiments      |             |
|  3 | wordcloud       |             |
|  4 | entity          |            |
|  5 | summary         |             |
|  6 | trade_info      |             |
|  7 | topic_modelling |            |
+----+-----------------+-------------+

Body:
In order to update boolean columns, you should use valueBoolean attribute.

E.G.

<changeSet author="liquibase" id="6226">
    <update tableName="master">
        <column name="insighttype" valueBoolean="false"/>
        <where>id=1</where>
    </update>
</changeSet>


问:
AutoCompleteTextView on selectiong item 3 warnings appears
This is the declaration of AutoCompleteTextView.

```<code>@Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if(savedInstanceState==null){
            mViewModel = new ViewModelProvider(this).get(SearchPartyViewModel.class);
        }
        View root=inflater.inflate(R.layout.fragment_new_order, container, false);
        initMessege=(TextView)root.findViewById(R.id.initMessege);
        newOrderPartyProgressBar=(ProgressBar)root.findViewById(R.id.newOrderPartyProgressBar);
        newProductDetailView=(ConstraintLayout)root.findViewById(R.id.newProductDetailView);
        listView=(LinearLayout)root.findViewById(R.id.listView);
        productSearchAutoCompleteTextView=(AutoCompleteTextView)root.findViewById(R.id.productSearchAutoCompleteTextView);
        newOrderParty=(AutoCompleteTextView)root.findViewById(R.id.newOrderParty);
        GetRetailList();
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_dropdown_item,retailerList);
        newOrderParty.setAdapter(adapter);
        newOrderParty.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("choosen",retailerList.get(position));
            }
        });
        return root;
    }
</code>```

when a item is selected from the drop down list the following erros appears

```<code>W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
</code>```

答:
write below code in your AutoCompleteTextView.setOnItemClickListener()

=================================================================================

autoComplete.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            autoComplete.postDelayed(new Runnable() {
                @Override
                public void run() {
                    autoComplete.showDropDown();
                }
            },100);
            autoComplete.setText(autoComplete.getText().toString());
            autoComplete.setSelection(autoComplete.getText().length());

```<code>    }
});
</code>```

=========================================================================================
This will give you hint for your question, change according to your need and adapter data.

Body:
This is the declaration of AutoCompleteTextView.

@Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if(savedInstanceState==null){
            mViewModel = new ViewModelProvider(this).get(SearchPartyViewModel.class);
        }
        View root=inflater.inflate(R.layout.fragment_new_order, container, false);
        initMessege=(TextView)root.findViewById(R.id.initMessege);
        newOrderPartyProgressBar=(ProgressBar)root.findViewById(R.id.newOrderPartyProgressBar);
        newProductDetailView=(ConstraintLayout)root.findViewById(R.id.newProductDetailView);
        listView=(LinearLayout)root.findViewById(R.id.listView);
        productSearchAutoCompleteTextView=(AutoCompleteTextView)root.findViewById(R.id.productSearchAutoCompleteTextView);
        newOrderParty=(AutoCompleteTextView)root.findViewById(R.id.newOrderParty);
        GetRetailList();
        ArrayAdapter<String> adapter= new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_dropdown_item,retailerList);
        newOrderParty.setAdapter(adapter);
        newOrderParty.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("choosen",retailerList.get(position));
            }
        });
        return root;
    }

when a item is selected from the drop down list the following erros appears

W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection

Body:
write below code in your AutoCompleteTextView.setOnItemClickListener()

=================================================================================

autoComplete.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            autoComplete.postDelayed(new Runnable() {
                @Override
                public void run() {
                    autoComplete.showDropDown();
                }
            },100);
            autoComplete.setText(autoComplete.getText().toString());
            autoComplete.setSelection(autoComplete.getText().length());

    }
});

=========================================================================================
This will give you hint for your question, change according to your need and adapter data.


问:
Aria-live="polite" does not read in proper order on NVDA Screen Reader?
aria-live screen reader reading is not in a proper order

```<code>Example:

<div id="one"    aria-live="polite">TEST 1</div>
<div id="two"    aria-live="polite">TEST 2</div>
<div id="three"  aria-live="polite">TEST 3</div>
</code>```

screen reader reading like:"TEST 2 TEST 1 TEST 3" it reads randomly
but content are updating using javascript in proper order

答:
As suspected the problem you have is that you are sending multiple updates at the same time.

I am not sure of why this behaviour exists (I guess it is due to some polling mechanism in the screen reader that listens for page changes and then queues them up, with a microsecond delay it could be that it 'fires up', sees the second update and immediately adds that to the queue (as the first as already occured) then sees that other updates have happened and adds them to the message queue. Just speculation, it could even be a browser micro optimisation on simultaneous updates.

To add further to this my computer starts with update 3 and then reads 1 and 2 - whereas my old laptop starts at 2 and then reads 1 and 3, so I am guessing it is a timing issue linked to CPU performance.

The fiddle below shows that with a slight delay between updates it works as expected.

Obviously I am not suggesting this fiddle is how to do it in production!

Instead I would create a global 'messages queue' function that accepts messages and then updates the relevant element with a slight throttling between messages (100ms should be plenty and fast enough that it doesn't leave gaps between messages even at fastest speech rates).

This would be a global queue, a function to add a message and then some function that throttles the responses (and shuts itself off if there are no messages to update to save CPU cycles, reactivating if a message is added).

Sadly the functions I use to do this are tied to loads of helpers all over the place and it is too difficult for me to extract them for an example so you will have to write that yourself.

function buttonStart(e) {
        document.getElementById('one').innerHTML    = "Button Description A TEST 1";
        document.getElementById('two').innerHTML    = "Button Description A TEST 2";
        document.getElementById('three').innerHTML  = "Button Description A TEST 3";
    }

function buttonStart2(e) {
  document.getElementById('one').innerHTML    = "Button Description  TEST 1";
    window.setTimeout(function(){
      document.getElementById('two').innerHTML    = "Button Description  TEST 2";
    },100);
    window.setTimeout(function(){
      document.getElementById('three').innerHTML  = "Button Description  TEST 3";
    },200);

    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        #accessbile {
            overflow: hidden;
            min-width: 0px;
            max-width: 0px;
            position: absolute;
            left: -20000px;
        }</code>```

    <button onclick="buttonStart()">START</button>
    <button onclick="buttonStart2()">START 2</button>

```

Body:
aria-live screen reader reading is not in a proper order

Example:

TEST 1

TEST 2

TEST 3

screen reader reading like:"TEST 2 TEST 1 TEST 3" it reads randomly
but content are updating using javascript in proper order

Body:
As suspected the problem you have is that you are sending multiple updates at the same time.

I am not sure of why this behaviour exists (I guess it is due to some polling mechanism in the screen reader that listens for page changes and then queues them up, with a microsecond delay it could be that it 'fires up', sees the second update and immediately adds that to the queue (as the first as already occured) then sees that other updates have happened and adds them to the message queue. Just speculation, it could even be a browser micro optimisation on simultaneous updates.

To add further to this my computer starts with update 3 and then reads 1 and 2 - whereas my old laptop starts at 2 and then reads 1 and 3, so I am guessing it is a timing issue linked to CPU performance.

The fiddle below shows that with a slight delay between updates it works as expected.

Obviously I am not suggesting this fiddle is how to do it in production!

Instead I would create a global 'messages queue' function that accepts messages and then updates the relevant element with a slight throttling between messages (100ms should be plenty and fast enough that it doesn't leave gaps between messages even at fastest speech rates).

This would be a global queue, a function to add a message and then some function that throttles the responses (and shuts itself off if there are no messages to update to save CPU cycles, reactivating if a message is added).

Sadly the functions I use to do this are tied to loads of helpers all over the place and it is too difficult for me to extract them for an example so you will have to write that yourself.

function buttonStart(e) {
        document.getElementById('one').innerHTML    = "Button Description A TEST 1";
        document.getElementById('two').innerHTML    = "Button Description A TEST 2";
        document.getElementById('three').innerHTML  = "Button Description A TEST 3";
    }

function buttonStart2(e) {
  document.getElementById('one').innerHTML    = "Button Description  TEST 1";
    window.setTimeout(function(){
      document.getElementById('two').innerHTML    = "Button Description  TEST 2";
    },100);
    window.setTimeout(function(){
      document.getElementById('three').innerHTML  = "Button Description  TEST 3";
    },200);

    }

        #accessbile {
            overflow: hidden;
            min-width: 0px;
            max-width: 0px;
            position: absolute;
            left: -20000px;
        }

    <button onclick="buttonStart()">START</button>
    <button onclick="buttonStart2()">START 2</button>

    <div id="accessbile">
        <div id="one"   aria-live="polite"></div>
        <div id="two"   aria-live="polite"></div>
        <div id="three" aria-live="polite"></div>
    </div>


问:
What evaluation metric to use for LightGBM ranker function
I'm using LGMRanker from LightGBM but not sure what evaluation metric I should be using. Here is my code:

```<code>import lightgbm as lgb

gbm = lgb.LGBMRanker
gridParams = {
'learning_rate': [0.005,0.01,0.02],
'max_depth': [5,6,7],
'n_estimators': [100,200],
'num_leaves': [20,30,50]
}
lgb_grid = GridSearchCV(estimator = gbm, param_grid = gridParams, scoring = '??', cv = 3, verbose=2, n_jobs = -1)
</code>```

What' appropriate here? I don't have any group, should I specify something?

答: DCG and NDCG are good evaluation methods for ranking algorithms. They can help you measure the quality of your results. You can read about them here. https://machinelearningmedium.com/2017/07/24/discounted-cumulative-gain/</p>

Body:
I'm using LGMRanker from LightGBM but not sure what evaluation metric I should be using. Here is my code:

import lightgbm as lgb

gbm = lgb.LGBMRanker
gridParams = {
'learning_rate': [0.005,0.01,0.02],
'max_depth': [5,6,7],
'n_estimators': [100,200],
'num_leaves': [20,30,50]
}
lgb_grid = GridSearchCV(estimator = gbm, param_grid = gridParams, scoring = '??', cv = 3, verbose=2, n_jobs = -1)

What' appropriate here? I don't have any group, should I specify something?


问:
How do I limit the number of times a block is called?
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

```<code>str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"
</code>```

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)

答:
Why are you using gsub()? By its design, gsub is designed to replace all occurrences of something, so, right off the bat you're fighting it.

Use sub instead:

```<code>str = 'aaaaaaaaaa'
count = 5
count.times { str.sub!(/a/, 'x') }
p str
# >> "xxxxxaaaaa"

str = 'mississippi'
2.times { str.sub!(/s/, '5') }
2.times { str.sub!(/s/, 'S') }
2.times { str.sub!(/i/, '1') }
p str
# >> "m1551SSippi"
</code>```

Body:
In How do I limit the number of replacements when using gsub?, someone suggested the following way to do a limited number of substitutions:

str = 'aaaaaaaaaa'
count = 5
p str.gsub(/a/){if count.zero? then $& else count -= 1; 'x' end}
# => "xxxxxaaaaa"

It works, but the code mixes up how many times to substitute (5) with what the substitution should be ("x" if there should be a substitution, $& otherwise). Is it possible to seperate the two out?

(If it's too hard to seperate the two things out in this scenario, but it can be done in some other scenarios, post that as an answer)

Body:
Why are you using gsub()? By its design, gsub is designed to replace all occurrences of something, so, right off the bat you're fighting it.

Use sub instead:

str = 'aaaaaaaaaa'
count = 5
count.times { str.sub!(/a/, 'x') }
p str
# >> "xxxxxaaaaa"

str = 'mississippi'
2.times { str.sub!(/s/, '5') }
2.times { str.sub!(/s/, 'S') }
2.times { str.sub!(/i/, '1') }
p str
# >> "m1551SSippi"


问:
jQuery How to add click to ul
I want to add class checked on li when users click it using jQuery. I have written the below code which works.

HTML

Documents checked

Documents Verified

Forwarded to Logistics

Received by Logistics

```

<pre class="lang-css prettyprint-override"><code>.checked {
  background: green;
}
</code>```

jQuery

$(function() {
    $('li.row').on('click', function() {
      $(this).addClass('checked');
    });
});
```

<p>This is working but I am told this is bad practice and asked to find better way to do this. I do the following but it is not working.</p>

<pre class="lang-js prettyprint-override"><code>$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});
</code>```

答:
use this Code for solution your problem

$(".row").click(function(){
  $(this).toggleClass("change")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.change {
  background-color:green;
}</code>```

Documents checked

Documents Verified

Forwarded to Logistics

Received by Logistics

```

Title: jQuery How to add click to ul

Body:
I want to add class checked on li when users click it using jQuery. I have written the below code which works.

HTML

Documents checked

Documents Verified

Forwarded to Logistics

Received by Logistics

.checked {
  background: green;
}

jQuery

$(function() {
    $('li.row').on('click', function() {
      $(this).addClass('checked');
    });
});

This is working but I am told this is bad practice and asked to find better way to do this. I do the following but it is not working.

$(function() {
    $('ul').on('click', function(li) {
      $(li).addClass('checked');
    });
});

Body:
use this Code for solution your problem

$(".row").click(function(){
  $(this).toggleClass("change")
})

.change {
  background-color:green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li class="row">Documents checked</li>
    <li class="row">Documents Verified </li>
    <li class="row">Forwarded to Logistics </li>
    <li class="row">Received by Logistics</li>
</ul>


问:
How to transfer or remove data synchronization with Redux-persist?
Made an authorization application. After a successful login, data is written to AsyncStorage.
I need to access data through shared storage. How to transfer or remove data synchronization with Redux-persist?</p>

答: Redux-persist have blacklist and whitelist, if your value in backlist it won't be persisted ( whitelist is opposite).</p>


问:
UICollectionViewFlowLayout Issue
I have tried to create self-sizing collectionView cell, but my label doesn't want to expand his height and become multilines, instead the label just goes in one single line and my cell goes beyond of collectionView frame. I have created my own custom UICollectionViewFlowLayout and tried to handle all stuff there. What have I done wrong? Looking forward for your answers, thanks!

My implementation:

```<code>class VerticalLayout:UICollectionViewFlowLayout {
override func prepare() {
    super.prepare()
    self.scrollDirection = .vertical
    self.minimumLineSpacing = 0
    self.minimumInteritemSpacing = 0
    self.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 173)
    self.sectionInset = .zero
    }
}
</code>```

答:
You must count text height and pass it to your collectionview delegate method

```<code> func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let itemHeight: CGFloat = estimatedHeightForText(text: items[indexPath.item].text, fontSize: fontSize, fontWeight: fontWeight, width: widthForText) + someRawValue // here count height for cell
    var itemWidth: CGFloat = someRawVal

    return CGSize(width: itemWidth, height: itemHeight)

}
</code>```

Count it here

```<code>    func estimatedHeightForText(text: String, fontSize: CGFloat, fontWeight: UIFont.Weight, width: CGFloat) -> CGRect {

    let size = CGSize(width: width, height: 1000)
    let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)

    return NSString(string: text).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
}
</code>```

UPD. widthForText - this is important value for text width in your cell. Count it properly

Title: UICollectionViewFlowLayout Issue

Body:
I have tried to create self-sizing collectionView cell, but my label doesn't want to expand his height and become multilines, instead the label just goes in one single line and my cell goes beyond of collectionView frame. I have created my own custom UICollectionViewFlowLayout and tried to handle all stuff there. What have I done wrong? Looking forward for your answers, thanks!

My implementation:

class VerticalLayout:UICollectionViewFlowLayout {
override func prepare() {
    super.prepare()
    self.scrollDirection = .vertical
    self.minimumLineSpacing = 0
    self.minimumInteritemSpacing = 0
    self.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 173)
    self.sectionInset = .zero
    }
}

Body:
You must count text height and pass it to your collectionview delegate method

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let itemHeight: CGFloat = estimatedHeightForText(text: items[indexPath.item].text, fontSize: fontSize, fontWeight: fontWeight, width: widthForText) + someRawValue // here count height for cell
    var itemWidth: CGFloat = someRawVal

    return CGSize(width: itemWidth, height: itemHeight)

}

Count it here

    func estimatedHeightForText(text: String, fontSize: CGFloat, fontWeight: UIFont.Weight, width: CGFloat) -> CGRect {

    let size = CGSize(width: width, height: 1000)
    let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)

    return NSString(string: text).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
}

UPD. widthForText - this is important value for text width in your cell. Count it properly


问:
How to use the variable beyond it's scope in Javascript?
I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

```<code>const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });
</code>```

EDIT 1:
I want to use the label this way

```<code>const client = new vision.ImageAnnotatorClient();
    // Performs label detection on the image file
    client
        .labelDetection(`${filename}`)
        .then(results => {
            var labels = results[0].labelAnnotations;

            console.log('Labels: ');
            labels.forEach(label => console.log(label.description));
        })

        .catch(err => {
            console.error('ERROR: ', err);
        });

console.log('Labels: ');
                labels.forEach(label => console.log(label.description));
</code>```

But the console shows the error "Cannot use undefined for forEach"

答:
Simply define labels outside of the promise:

```<code>const client = new vision.ImageAnnotatorClient();
let labels = null;

// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });
</code>```

Not sure where you want to use it, but you will only be able to use its value after the promise is resolved. In which case a better approach would be:

```<code>

I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
        return labels;
    })

    .then(labels => {
        console.error('Some other usage for labels: ', labels);
    });

    .catch(err => {
        console.error('ERROR: ', err);
    });
</code>```

Body:
I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });

EDIT 1:
I want to use the label this way

const client = new vision.ImageAnnotatorClient();
    // Performs label detection on the image file
    client
        .labelDetection(`${filename}`)
        .then(results => {
            var labels = results[0].labelAnnotations;

            console.log('Labels: ');
            labels.forEach(label => console.log(label.description));
        })

        .catch(err => {
            console.error('ERROR: ', err);
        });

console.log('Labels: ');
                labels.forEach(label => console.log(label.description));

But the console shows the error "Cannot use undefined for forEach"

Body:
Simply define labels outside of the promise:

const client = new vision.ImageAnnotatorClient();
let labels = null;

// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });

Not sure where you want to use it, but you will only be able to use its value after the promise is resolved. In which case a better approach would be:

I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
        return labels;
    })

    .then(labels => {
        console.error('Some other usage for labels: ', labels);
    });

    .catch(err => {
        console.error('ERROR: ', err);
    });


问:
Android EditText text control - how to disable possibility to insert GIF from Google Keyboard?
My app's target API is 27 (Oreo). My app uses EditText control for text input. However, from Google Keyboard it's now possible to insert GIF. In this case, my app receives ACTION_SEND intent, with gif inserted from a keyboard, which is implemented for completely different functionality. So it just messes entire app flow and takes the user to completely different activity.

I want my EditText to accept text only and don't allow users to insert any gif there. How can I configure EditText to stop allow inserting GIFS from keyboard?

答:
I did the following tricks:

```<code>view.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)
</code>```

Set these flags to your view and Gboard hides GIF button.

Body:
I did the following tricks:

view.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT)

Set these flags to your view and Gboard hides GIF button.


问:
Ruby, forming API request without implicitly stating each parameter
I'm trying to make a request to a web service (fwix), and in my rails app I've created the following initializer, which works... sorta, I have two problems however:

For some reason the values of the parameters need to have +'s as the spaces, is this a standard thing that I can accomplish with ruby? Additionally is this a standard way to form a url? I thought that spaces were %20.

In my code how can I take any of the options sent in and just use them instead of having to state each one like query_items << "api_key=#{options[:api_key]}" if options[:api_key]

The following is my code, the trouble area I'm having are the lines starting with query_items for each parameter in the last method, any ideas would be awesome!

```<code>require 'httparty'
module Fwix
  class API
    include HTTParty

    class JSONParser < HTTParty::Parser
      def json
        JSON.parse(body)
      end
    end

    parser JSONParser
    base_uri "http://geoapi.fwix.com"

    def self.query(options = {})
      begin
        query_url = query_url(options)
        puts "querying: #{base_uri}#{query_url}"
        response = get( query_url )
      rescue
        raise "Connection to Fwix API failed" if response.nil?
      end
    end

    def self.query_url(input_options = {})
      @defaults ||= {
        :api_key => "my_api_key",
      }

      options = @defaults.merge(input_options)
      query_url = "/content.json?"
      query_items = []
      query_items << "api_key=#{options[:api_key]}" if options[:api_key]
      query_items << "province=#{options[:province]}" if options[:province]
      query_items << "city=#{options[:city]}" if options[:city]
      query_items << "address=#{options[:address]}" if options[:address]

      query_url += query_items.join('&')
      query_url
    end
  end
end
</code>```

答:
```<code>def self.query_url(input_options = {})
  options = {
    :api_key => "my_api_key",
  }.merge(input_options)

  query_url = "/content.json?"
  query_items = []

  options.each { |k, v| query_items << "#{k}=#{v.gsub(/\s/, '+')}" }

  query_url += query_items.join('&')
end
</code>```

Body:
I'm trying to make a request to a web service (fwix), and in my rails app I've created the following initializer, which works... sorta, I have two problems however:

For some reason the values of the parameters need to have +'s as the spaces, is this a standard thing that I can accomplish with ruby? Additionally is this a standard way to form a url? I thought that spaces were %20.

In my code how can I take any of the options sent in and just use them instead of having to state each one like query_items << "api_key=#{options[:api_key]}" if options[:api_key]

The following is my code, the trouble area I'm having are the lines starting with query_items for each parameter in the last method, any ideas would be awesome!

require 'httparty'
module Fwix
  class API
    include HTTParty

    class JSONParser < HTTParty::Parser
      def json
        JSON.parse(body)
      end
    end

    parser JSONParser
    base_uri "http://geoapi.fwix.com"

    def self.query(options = {})
      begin
        query_url = query_url(options)
        puts "querying: #{base_uri}#{query_url}"
        response = get( query_url )
      rescue
        raise "Connection to Fwix API failed" if response.nil?
      end
    end

    def self.query_url(input_options = {})
      @defaults ||= {
        :api_key => "my_api_key",
      }

      options = @defaults.merge(input_options)
      query_url = "/content.json?"
      query_items = []
      query_items << "api_key=#{options[:api_key]}" if options[:api_key]
      query_items << "province=#{options[:province]}" if options[:province]
      query_items << "city=#{options[:city]}" if options[:city]
      query_items << "address=#{options[:address]}" if options[:address]

      query_url += query_items.join('&')
      query_url
    end
  end
end


问:
Data-frame to show selected results only from columns divisions
A data-frame to divide the month columns by the Total column. At the end, I want to only show the results greater than 35% (0.35).

```<code>import pandas as pd

data = {'Name' : ["John","Peter","Kate","Liz"],
'Jan-2016': [408,88,277,32],
'Feb-2016': [313,348,73,302],
'Mar-2016': [497,197,196,164],
'Apr-2016': [88,87,447,118],
'May-2016': [79,20,235,273],
'Total': [1385,740,1228,889]}

df = pd.DataFrame(data)

df_1 = df[["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016"]].div(df["Total"], axis=0)
</code>```

I can only work out the calculation.

What's the way to output the results greater and equal to 0.3 only?
(please note 1 person may have 0-3 columns fit)

Thank you.

答:
You can use:

```<code>df.set_index('Name', inplace=True)
df.iloc[:, :-1].div(df['Total'], axis=0)\
.stack().loc[lambda x: x >= 0.3]
</code>```

Output:

```<code>Name
John   Mar-2016    0.358845
Peter  Feb-2016    0.470270
Kate   Apr-2016    0.364007
Liz    Feb-2016    0.339708
       May-2016    0.307087
dtype: float64
</code>```

Body:
A data-frame to divide the month columns by the Total column. At the end, I want to only show the results greater than 35% (0.35).

import pandas as pd

data = {'Name' : ["John","Peter","Kate","Liz"],
'Jan-2016': [408,88,277,32],
'Feb-2016': [313,348,73,302],
'Mar-2016': [497,197,196,164],
'Apr-2016': [88,87,447,118],
'May-2016': [79,20,235,273],
'Total': [1385,740,1228,889]}

df = pd.DataFrame(data)

df_1 = df[["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016"]].div(df["Total"], axis=0)

I can only work out the calculation.

What's the way to output the results greater and equal to 0.3 only?
(please note 1 person may have 0-3 columns fit)

Thank you.

Body:
You can use:

df.set_index('Name', inplace=True)
df.iloc[:, :-1].div(df['Total'], axis=0)\
.stack().loc[lambda x: x >= 0.3]

Output:

Name
John   Mar-2016    0.358845
Peter  Feb-2016    0.470270
Kate   Apr-2016    0.364007
Liz    Feb-2016    0.339708
       May-2016    0.307087
dtype: float64


问:
How to use $transitions.onStart() in Angular 8?
I have an issue when try to migrate project written by AngularJS to Angular 8, how I can migrate the code below to Angular 8:

For AngularJS:

```<code>// `transition start` text only show once when I redirect the url

this.$transitions.onStart({}, (transition) => {
    console.log('transition start');
});
</code>```

For Angular 8:

```<code>// I try to convert the code above to this one but when I redirect the url, `transition start` will show twice or even more than

this.router.events.subscribe((event) => {
   if (event instanceof NavigationStart) {
     console.log('transition start');
   }
});
</code>```

Does anyone have same the issue and any idea about that?

Thanks!

答:
Try unsubscribing to the event:</p>

```<code>onRouteChange() {
    this._routeListener = this.router.events.subscribe((event) => ...);
}

ngOnDestroy() {
    this._routeListener.unsubscribe();
}
</code>```

Body:
I have an issue when try to migrate project written by AngularJS to Angular 8, how I can migrate the code below to Angular 8:

For AngularJS:

// `transition start` text only show once when I redirect the url

this.$transitions.onStart({}, (transition) => {
    console.log('transition start');
});

For Angular 8:

// I try to convert the code above to this one but when I redirect the url, `transition start` will show twice or even more than

this.router.events.subscribe((event) => {
   if (event instanceof NavigationStart) {
     console.log('transition start');
   }
});

Does anyone have same the issue and any idea about that?

Thanks!

Body:
Try unsubscribing to the event:

onRouteChange() {
    this._routeListener = this.router.events.subscribe((event) => ...);
}

ngOnDestroy() {
    this._routeListener.unsubscribe();
}


问:
How does character array with single quote affects an character array without the quotes?
```<code>char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };
</code>```

what is the difference? It does not raise any errors. why?

答:
This will create a character array the way you think it does, with the actual characters 12345:

```<code>char a[5] = { '1', '2', '3', '4', '5' };
</code>```

This will create a character array with five characters with the ASCII decimal values 1 to 5:

```<code>char a[5] = { 1, 2, 3, 4, 5 };
</code>```

Notice also that all of these are unprintables:

The reason that it doesn't give any errors is because it's a totally valid way of handling characters. A char in C is just an ASCII encoded integer.

Body:
char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };

what is the difference? It does not raise any errors. why?

Body:
This will create a character array the way you think it does, with the actual characters 12345:

char a[5] = { '1', '2', '3', '4', '5' };

This will create a character array with five characters with the ASCII decimal values 1 to 5:

char a[5] = { 1, 2, 3, 4, 5 };

Notice also that all of these are unprintables:

The reason that it doesn't give any errors is because it's a totally valid way of handling characters. A char in C is just an ASCII encoded integer.


问:
Unable to stop the propogation of events in reactJs
I have a condition where I have simple dropdown menu

```<code>handleDropdown = (e) => {
    if (e.type === "focus") {
      console.log("inside dropdown focus");
      this.setState({ dropDownDis: "block" })
    } else if (e.type === "blur") {
      console.log("inside dropdown blur");
      this.setState({ dropDownDis: "none" })
    }
  }

 logout = (e) => {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    console.log("inside logout")
  }
</code>```

When I click on Logout, The menu closes but logout method doesn't calls.

html

```<code>  <div className="header-user">
              <button
                type="button"
                className="dropdown-button"
                ref={this.myRef}
                onFocus={this.handleDropdown}
                onBlur={this.handleDropdown}
              >
              <img src="/img/headericon.png" alt="no header icon" />
              </button>

              <div className="dropdown-menu" style={{ display: dropDownDis }}>

              <ul className="sidebar-list">
               <li>
                <img src="../img/user.png"/> <a href="#">My Profile </a>
               </li>
               <li>
                <img src="../img/order.png"/><a href="#">Order </a>
               </li>
               <li>
                <img src="../img/account.png"/> <a href="#">My Account </a>
              </li>
              <li>
               <img src="../img/logout.png"/> <a onClick={this.logout}>Log Out </a>
              </li>
             </ul>

            </div>
   </div>
</code>```

On clicking the logout I can see the console as shown in below image

答:
If the handleDropdownOptions is in a child component, you have to pass the logout function as a prop to the child component and call it inside handleDropdownOptions

```<code>handleDropdownOptions = () => {
    console.log("-------dropdown------");
    this.props.logout();
}
</code>```

Body:
I have a condition where I have simple dropdown menu

handleDropdown = (e) => {
    if (e.type === "focus") {
      console.log("inside dropdown focus");
      this.setState({ dropDownDis: "block" })
    } else if (e.type === "blur") {
      console.log("inside dropdown blur");
      this.setState({ dropDownDis: "none" })
    }
  }

 logout = (e) => {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    console.log("inside logout")
  }

When I click on Logout, The menu closes but logout method doesn't calls.

html

              <button
                type="button"
                className="dropdown-button"
                ref={this.myRef}
                onFocus={this.handleDropdown}
                onBlur={this.handleDropdown}
              >

              </button>

                 My Profile

                Order

                 My Account

                Log Out

On clicking the logout I can see the console as shown in below image

Body:
If the handleDropdownOptions is in a child component, you have to pass the logout function as a prop to the child component and call it inside handleDropdownOptions

handleDropdownOptions = () => {
    console.log("-------dropdown------");
    this.props.logout();
}


问:
Disable java doc auto formatting in Intellij Idea. 2019
I want my javadoc to look like this:

```<code>/**
* Date 10/01/2019
*
* Given a directed graph, find all strongly connected components in this graph.
* We are going to use Kosaraju's algorithm to find strongly connected       component.
*
* Algorithm
* Create a order of vertices by finish time in decreasing order.
* Reverse the graph
* Do a DFS on reverse graph by finish time of vertex and created strongly connected
* components.
*
* Runtime complexity - O(V + E)
* Space complexity - O(V)
*
* References
* https://en.wikipedia.org/wiki/Strongly_connected_component
* http://www.geeksforgeeks.org/strongly-connected-components/
*/
</code>```

But unfortunately my javadoc gets auto formatted to :

```<code>/**
* Given a directed acyclic graph, find all connected components in the graph.       We will be using
* Kosaraju’s algorithm for finding all connected components
*
* <p>Algorithm :
*
* <p>Do DFS on the graph, mark the adjacent vertices as visited and order the visited vertex
*
* <p>Reverse the graph - transpose<>
*
* <p>Do DFS on the reversed graph, by pop- ing elements from the stack and marking them as visited
*
* <p>Complexity:
*
* <p>Runtime - O(V+E) for DFS
*
* <p>Space = O(V) for the stack and visited vertices
*
* <p>Date : 15/02/20
*
*
* <p>Referances : https://www.youtube.com/watch?v=RpgcYiky7uw
* https://www.geeksforgeeks.org/strongly-connected-components/
*/
</code>```

If I add a line break manually and start writing on the next line, during code format the two lines gets merged into one. The only way that I can write on the next line is by adding two newlines, so during code format ide adds
 to the new line

Say suppose I want to split

"Do DFS on the graph, mark the adjacent vertices as visited and order the visited vertex"

into two lines, but as soon as I reformat my code the two lines gets merged into once

I am using google-java-format for code formatting.

I tried modifying Code Style -> Java -> JavaDoc options but somehow the changes. does't  seem to work

答: To avoid line merging in JavaDoc, you may open (Preferences | Editor | Code Style | Java | JavaDoc) and unmark the ”Wrap at right margin” checkbox.

Body:
I want my javadoc to look like this:

/**
* Date 10/01/2019
*
* Given a directed graph, find all strongly connected components in this graph.
* We are going to use Kosaraju's algorithm to find strongly connected       component.
*
* Algorithm
* Create a order of vertices by finish time in decreasing order.
* Reverse the graph
* Do a DFS on reverse graph by finish time of vertex and created strongly connected
* components.
*
* Runtime complexity - O(V + E)
* Space complexity - O(V)
*
* References
* https://en.wikipedia.org/wiki/Strongly_connected_component
* http://www.geeksforgeeks.org/strongly-connected-components/
*/

But unfortunately my javadoc gets auto formatted to :

/**
* Given a directed acyclic graph, find all connected components in the graph.       We will be using
* Kosaraju’s algorithm for finding all connected components
*
*
Algorithm :
*
*
Do DFS on the graph, mark the adjacent vertices as visited and order the visited vertex
*
*
Reverse the graph - transpose<>
*
*
Do DFS on the reversed graph, by pop- ing elements from the stack and marking them as visited
*
*
Complexity:
*
*
Runtime - O(V+E) for DFS
*
*
Space = O(V) for the stack and visited vertices
*
*
Date : 15/02/20
*
*
*
Referances : https://www.youtube.com/watch?v=RpgcYiky7uw
* https://www.geeksforgeeks.org/strongly-connected-components/
*/

If I add a line break manually and start writing on the next line, during code format the two lines gets merged into one. The only way that I can write on the next line is by adding two newlines, so during code format ide adds
 to the new line

Say suppose I want to split

"Do DFS on the graph, mark the adjacent vertices as visited and order the visited vertex"

into two lines, but as soon as I reformat my code the two lines gets merged into once

I am using google-java-format for code formatting.

I tried modifying Code Style -> Java -> JavaDoc options but somehow the changes. does't  seem to work


问:
SQL Query required where we should not used the group by and data count based on dep_id
Need your help in getting the SQL Query.
1. I have one table which is having following columns

```<code>Name         Null?    Type
------------ -------- ------------
EMP_ID       NOT NULL NUMBER(2)
DEP_ID                NUMBER(2)
SALARY                NUMBER(14,3)
NAME1                 VARCHAR2(50)
NAME2                 VARCHAR2(50)
JOINING_DATE          DATE
</code>```

Now I want the result - COUNT(1) based on DEP_ID without using GROUP BY .

EXAMPLE :

```<code>select DEP_ID,COUNT(1) from unipartemp group by DEP_ID;
</code>```

```<code>DEP_ID COUNT(1)
1       2
2       2
3       1
</code>```

What is the Query where we should get the same result but we should not use group by ...

Please suggest .

答: I am assuming that the result u r looking for is the count of the distinct dept_id. Try using the distinct(dept_id) to get the result.</p>

Body:
Need your help in getting the SQL Query.
1. I have one table which is having following columns

Name         Null?    Type
------------ -------- ------------
EMP_ID       NOT NULL NUMBER(2)
DEP_ID                NUMBER(2)
SALARY                NUMBER(14,3)
NAME1                 VARCHAR2(50)
NAME2                 VARCHAR2(50)
JOINING_DATE          DATE

Now I want the result - COUNT(1) based on DEP_ID without using GROUP BY .

EXAMPLE :

select DEP_ID,COUNT(1) from unipartemp group by DEP_ID;

DEP_ID COUNT(1)
1       2
2       2
3       1

What is the Query where we should get the same result but we should not use group by ...

Please suggest .


问:
How to fix empty semantic media wiki query results after restore?
After restoring a semantic media wiki installation from backup the SMW engine does no longer return any query results. I have (re)inserted all regular pages, all form pages, all property pages into the new MW instance. So all content is there but query results remain empty. It seems as the internal data structures maintained by SMW are not filled. How can this be fixed? Are there any specific scripts that need to be run manually?</p>

答:
Indeed the internal SMW cache is not filled after restore. The solution is simple: You need to go to extensions/SemanticMediaWiki/maintenance and run the script rebuildData.php which will reparse every single Wiki page and fill the SMW database accordingly.

Be aware that for this to work your Wiki needs to be configured properly. By default SMW will not process additional namespaces! You need to enable this manually for every single namespace you add yourself in LocalSettings.php after the line where you enable SMW in this file. (This configuration will only have effect if you do this after the line that enables SMW.)


问:
Switch Style Radio Button Using JavaScript
I would like to know how I can make a switch style function to change the website style between 2 styles. Here's what I have done so far. Please check. Thank you.

```<code>function switchcss() {
    document.write('<link rel="stylesheet" type"text/css" href="css/style1.css">');
    document.write('<link rel="stylesheet" type"text/css" href="css/style2.css">');
}
</code>```

http://jsfiddle.net/APbSm/

答:
You need to understand how one can use JavaScript to create/remove DOM elements, including link.

Please, read, e.g. dynamically loading / removing js and css

Also, it is not a good idea to use document.write() in most circumstances. I could write you a full correct solution, but there is no "common" universal couple of lines for that, and if you have to have a skin switcher, and need to support it in the future, it makes much more sense to understand the technology underneath.

Body:
I would like to know how I can make a switch style function to change the website style between 2 styles. Here's what I have done so far. Please check. Thank you.

function switchcss() {
    document.write('<link rel="stylesheet" type"text/css" href="css/style1.css">');
    document.write('<link rel="stylesheet" type"text/css" href="css/style2.css">');
}

http://jsfiddle.net/APbSm/


问:
Angular 2 slow initial load
When I enable cross origin resource sharing my app takes 8-9 sec to load. When its disabled takes like 1-2 sec. I am really new at this. Any ideas what could be the main problem? And how to speed it up? The project is in really early stage and 8 sec its really long time since the app is not making any requests for data now.

Here is my index.html

```<code><!DOCTYPE html>
<html>

  <head>
    <script src="https://unpkg.com/zone.js@0.6.21/dist/zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
    System.import('app/js/bootstrap')
      .catch(console.error.bind(console));
  </script>
   <script src="app/js/xml2json.js"></script>
    <script src="app/js/div.js"></script>
        <script src="app/js/divY.js"></script>

    <style>
  body,html{width:100%;height:100%;padding:5px;margin:0;}

  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="//cdn.jsdelivr.net/interact.js/1.2.6/interact.min.js"></script>
  </head>

  <body>
    <app>
    loading...
  </app>
  </body>

</html>
</code>```

And here is my config.js

```<code>System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {
    'app': "./app",
    'ng2-translate': 'npm:ng2-translate',
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

    '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',

    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.0.2/lib/typescript.js'
  },
  //packages defines our app package
  packages: {
    app: {
      main: './bootstrap.ts',
      defaultExtension: 'js'
    },
    rxjs: {
      defaultExtension: 'js'
    },
    'ng2-translate': {
      defaultExtension: 'js'
    }
  }

});
</code>```

答: The issue is related to zone.js, zone.js is causing an angular websites to have a poor loading and penalize by google speed as script valuation. Check your polyfill.ts and zone.js you can exclude from that file and load directly on the index.html as cloudflare cdn script.</p>

Title: Angular 2 slow initial load

Body:
When I enable cross origin resource sharing my app takes 8-9 sec to load. When its disabled takes like 1-2 sec. I am really new at this. Any ideas what could be the main problem? And how to speed it up? The project is in really early stage and 8 sec its really long time since the app is not making any requests for data now.

Here is my index.html

<!DOCTYPE html>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <app>
    loading...
  </app>

And here is my config.js

System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {
    'app': "./app",
    'ng2-translate': 'npm:ng2-translate',
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

    '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',

    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.0.2/lib/typescript.js'
  },
  //packages defines our app package
  packages: {
    app: {
      main: './bootstrap.ts',
      defaultExtension: 'js'
    },
    rxjs: {
      defaultExtension: 'js'
    },
    'ng2-translate': {
      defaultExtension: 'js'
    }
  }

});


问:
(Swift) How to get rid of "Left side of mutating operator isn't mutable"
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

```<code>func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}
</code>```

handleTap function :

```<code>@objc
func handleTap(_ someString: String) {
     someString += "my"
}
</code>```

答:
Short story: It's impossible to add custom parameters to (any) target/action

Either there is no parameter

```<code>@objc
func handleTap() { ...
</code>```

or the affected recognizer is the parameter

```<code>@objc
func handleTap(_ recognizer : UITapGestureRecognizer) { ...
</code>```

That's it. In both cases the corresponding declaration is

```<code>UITapGestureRecognizer(target: self, action: #selector(handleTap))
</code>```

You have to use a temporary variable to handle the string.

Body:
complete error:

Left side of mutating operator isn't mutable: 'abc' is a 'let' constant

Happens because I am trying to change value of a variable sent by parameter to function.

Can I get rid of this, or find some other solution?

Code(My code is much complex, but in effect doing the same as this):

func generateABC() {
var abc = "this"
abc += "is"

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(abc)) )
tapGesture.delegate = self
webView.addGestureRecognizer(tapGesture)

abc += "function"
}

handleTap function :

@objc
func handleTap(_ someString: String) {
     someString += "my"
}

Body:
Short story: It's impossible to add custom parameters to (any) target/action

Either there is no parameter

@objc
func handleTap() { ...

or the affected recognizer is the parameter

@objc
func handleTap(_ recognizer : UITapGestureRecognizer) { ...

That's it. In both cases the corresponding declaration is

UITapGestureRecognizer(target: self, action: #selector(handleTap))

You have to use a temporary variable to handle the string.


问:
GatsbyJs - make ImageSharp from multiple images referenced in csv
Using gatsby-transformer-csv and gatsby-transformer-sharp

given a CSV file with one cell that has multiple images (with a local path) referenced, how can I get them to be processed by imageSharp?

```<code>id,slug,images
615,prime-click-solid-2,./images/products/PC-019-S1.png, ./images/products/PC-019-S-1.png

</code>```

答:
It sounds like what you're trying to do here can be broken down to two steps:

Parse the CSV into an array of nodes, with each node containing an array of image URLs.

Iterate over these nodes at build time, and transform every URL in each node's URL array into an imageSharp node.

One way to approach this* would be to:

Configure gatsby-transformer-csv in your gatsby-config to give your CSV nodes a custom name.

Override onCreateNode in gatsby-node, add a conditional to trigger when your CSV nodes are created, extract the array of image URLs from the node, and iterate over those to create the imageSharp nodes from the filesystem.

Alternatively, you may be able to get by without the second step if you just parse out the image paths, then pass those into a file GraphQL query with file(relativePath: $path) { childImageSharp { /* ... */ } or similar, as outlined here for example. Keep in mind that dynamic queries in Gatsby can only be used in top-level "page" components, whereas static queries can be used anywhere.

*There may be better ways! As mentioned above, it's hard to say what the "best" solution is without knowing more about your use-case. Gatsby is very flexible with how you manage your data.

Body:
Using gatsby-transformer-csv and gatsby-transformer-sharp

given a CSV file with one cell that has multiple images (with a local path) referenced, how can I get them to be processed by imageSharp?

id,slug,images
615,prime-click-solid-2,./images/products/PC-019-S1.png, ./images/products/PC-019-S-1.png


问:
How to create a reusable Map
Is there a way to populate a Map once from the DB (through Mongo repository) data and reuse it when required from multiple classes instead of hitting the Database through the repository.</p>

答:
As per your comment, what you are looking for is a Caching mechanism. Caches are components which allow data to live in memory, as opposed to files, databases or other mediums so as to allow for the fast retrieval of information (against a higher memory footprint).

There are probably various tutorials online, but usually caches all have the following behaviour:
1. They are key-value pair structures.
2. Each entity living in the cache also has a Time To Live, that is, how long will it considered to be valid.

You can implement this in the repository layer, so the cache mechanism will be transparent to the rest of your application (but you might want to consider exposing functionality that allows to clear/invalidate part or all the cache).

So basically, when a query comes to your repository layer, check in the cache. If it exists in there, check the time to live. If it is still valid, return that.

If the key does not exist or the TTL has expired, you add/overwrite the data in the cache. Keep in mind that when updating the data model yourself, you also invalidate the cache accordingly so that new/fresh data will be pulled from the DB on the next call.

Title: How to create a reusable Map


问:
Reagent configuration for multi-page applications
My project.clj has,

```<code>  :cljsbuild {:builds
              {:app
               {:source-paths ["src/cljs" "src/cljc"]
                :compiler {:output-to "target/cljsbuild/public/js/app.js"
                           :output-dir "target/cljsbuild/public/js/out"
                           :main "my.core"
                           :asset-path "/js/out"
                           :optimizations :none
                           :source-map true
                           :pretty-print true}}}}
</code>```

and I include app.js in my list.html, using Selmer, like so,

```<code>{% block page-scripts %}
{% script "/js/app.js" %}
{% endblock %}
</code>```

at the end of my list.cljs, I have

```<code>(r/render [list] (.getElementById js/document "content"))
</code>```

so far so good.

Now, I would like to have another page, say detail.cljs, that I also like to render similarly,

```<code>(r/render [detail] (.getElementById js/document "content"))
</code>```

The problem is, I just have a single app.js and including that in detail.html will render list content there too. Btw, I want one url for list page, and another for detail.

Question:

How should I go about it?

答:
Using shadow-cljs, you can specify several modules with different init-fns in your build spec.

Your shadow-cljs.edn could contain something like this:

```<code>{:builds {:client {:target "browser"
                   :modules {:some-page {:init-fn org.example.foo/run}
                             :another-page {:init-fn org.example.bar/run
                                            :depends-on #{:some-page}}}}}}
</code>```

The names of the .js files are determined from the module name, here some-page.js and another-page.js.

Body:
My project.clj has,

  :cljsbuild {:builds
              {:app
               {:source-paths ["src/cljs" "src/cljc"]
                :compiler {:output-to "target/cljsbuild/public/js/app.js"
                           :output-dir "target/cljsbuild/public/js/out"
                           :main "my.core"
                           :asset-path "/js/out"
                           :optimizations :none
                           :source-map true
                           :pretty-print true}}}}

and I include app.js in my list.html, using Selmer, like so,

{% block page-scripts %}
{% script "/js/app.js" %}
{% endblock %}

at the end of my list.cljs, I have

(r/render [list] (.getElementById js/document "content"))

so far so good.

Now, I would like to have another page, say detail.cljs, that I also like to render similarly,

(r/render [detail] (.getElementById js/document "content"))

The problem is, I just have a single app.js and including that in detail.html will render list content there too. Btw, I want one url for list page, and another for detail.

Question:

How should I go about it?

Body:
Using shadow-cljs, you can specify several modules with different init-fns in your build spec.

Your shadow-cljs.edn could contain something like this:

{:builds {:client {:target "browser"
                   :modules {:some-page {:init-fn org.example.foo/run}
                             :another-page {:init-fn org.example.bar/run
                                            :depends-on #{:some-page}}}}}}

The names of the .js files are determined from the module name, here some-page.js and another-page.js.