问:
Laravel Nova Observe not connecting to tenant database
I have a multi tenant App. My system database I have models- User, Billing, FrontEnd ... and using policies I'm able to show, hide and prevent viewing and actions by tenant.

Each tenant has a database with models- Member, Event, Item ...
I set each model database based on the Auth::user()->dbname in the _construct method. This allows me to set my dbname to a clients database for tech support.

```<code>class Item extendsw Model {

    public function __construct() {
        parent::__construct();
        if(Auth::user()->dbname) {
            Config::set('database.connections.tenant.database', auth()->user()->dbname);
             $this->connection = 'tenant';
        }
    }
</code>```

This all works as planned until I add and Observer for a client model e.g. Member

I now get an error on any Observer call.

Trying to get property on non object Auth::user()->dbname.

Where should I be registering the Observer? I tried AppServiceProvider and NovaServiceProvider.

答:
I think that happens because the observer instantiates your User model before the request cycle has started and that means that your User instance does not exist yet neither has been bound in the Auth facade.

Thus, Auth::user() returns null and you are trying to get a property from it.
A way to solve the issue may be to check if the user instance exists or not:

public function __construct() {
    parent::__construct();

    if (optional(Auth::user())->dbname !== null) {
        Config::set('database.connections.tenant.database', auth()->user()->dbname);
         $this->connection = 'tenant';
    }
}
```

The optional helper return the value of the accessed property (dbname in your case) if and only if the argument is not null, otherwise the whole call will return a null value instead throwing an exception.

If that is not the case, maybe update the question with the error stacktrack and the code/action that triggers the error

Body:
I have a multi tenant App. My system database I have models- User, Billing, FrontEnd ... and using policies I'm able to show, hide and prevent viewing and actions by tenant.

Each tenant has a database with models- Member, Event, Item ...
I set each model database based on the Auth::user()->dbname in the _construct method. This allows me to set my dbname to a clients database for tech support.

class Item extendsw Model {

    public function __construct() {
        parent::__construct();
        if(Auth::user()->dbname) {
            Config::set('database.connections.tenant.database', auth()->user()->dbname);
             $this->connection = 'tenant';
        }
    }

This all works as planned until I add and Observer for a client model e.g. Member

I now get an error on any Observer call.

Trying to get property on non object Auth::user()->dbname.

Where should I be registering the Observer? I tried AppServiceProvider and NovaServiceProvider.

Body:
I think that happens because the observer instantiates your User model before the request cycle has started and that means that your User instance does not exist yet neither has been bound in the Auth facade.

Thus, Auth::user() returns null and you are trying to get a property from it.
A way to solve the issue may be to check if the user instance exists or not:

public function __construct() {
    parent::__construct();

    if (optional(Auth::user())->dbname !== null) {
        Config::set('database.connections.tenant.database', auth()->user()->dbname);
         $this->connection = 'tenant';
    }
}

The optional helper return the value of the accessed property (dbname in your case) if and only if the argument is not null, otherwise the whole call will return a null value instead throwing an exception.

If that is not the case, maybe update the question with the error stacktrack and the code/action that triggers the error


来源: stackexchange

问:
Add class to form field Django ModelForm
I am trying to write a Bootstrap Form with Django ModelForm. I have read the Django Documentation Django Documentation about Forms, so I have this code:

```<code><div class="form-group">
{{ form.subject.errors }}
<label for="{{ form.subject.id_for_label }}">Email subject:</label>
{{ form.subject }}</div>
</code>```

The {{form.subject}} is rendered by Django, for example in CharField field model, as input tag,

```<code><input type="text"....> etc.
</code>```

I need add "form-control" class to every input in order to get Bootstrap input appearance (without third-party packages). I found this solution Django add class to form <input ..> field. Is there any way to add a class to every field by default without specifying it in every attribute of the class of Form class?

```<code>class ExampleForm(forms.Form):
   name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
</code>```

and so on ..

答:
I found it easier to identify the element via css and add the styling there. With django forms you get a unique id for each form field (user form prefixes if you display the form multiple times in your template).

```<code># views.py
def my_view_function(request):
    form_a = MyForm(prefix="a")
    form_b = MyForm(prefix="b")
    context = {
        "form_a": form_a,
        "form_b": form_b
    }
    return render(request, "template/file.html", context)
</code>```

style

```<code>// file.css
form input#by_id {
  width: 100%;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a Bootstrap Form with Django ModelForm. I have read the Django Documentation Django Documentation about Forms, so I have this code:

{{ form.subject.errors }}
Email subject:
{{ form.subject }}

The {{form.subject}} is rendered by Django, for example in CharField field model, as input tag,

<input type="text"....> etc.

I need add "form-control" class to every input in order to get Bootstrap input appearance (without third-party packages). I found this solution Django add class to form <input ..> field. Is there any way to add a class to every field by default without specifying it in every attribute of the class of Form class?

class ExampleForm(forms.Form):
   name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
   country = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

and so on ..

Body:
I found it easier to identify the element via css and add the styling there. With django forms you get a unique id for each form field (user form prefixes if you display the form multiple times in your template).

# views.py
def my_view_function(request):
    form_a = MyForm(prefix="a")
    form_b = MyForm(prefix="b")
    context = {
        "form_a": form_a,
        "form_b": form_b
    }
    return render(request, "template/file.html", context)

style

// file.css
form input#by_id {
  width: 100%;
}


问:
Google maps not show in release mode android
I have a problem with my google maps API. In debug mode it's working fine. But when in release mode i got blank maps. i have tried to change SHA1 from debug keystore to release keystore. any idea for my problem?</p>

答:
In case someone is facing the same issue, I will share my solution...
I am creating an app and I finally got at the point to release it. So I tried to run on the release mode and I got the information that I needed to set the signingConfigs for the build variants release. Once I did it, and configured my proguard-rules.pro file the app was running, great! but the map wasn't showing.

I found people talking about the keystore and SHA1 credentials end everything but it wasn't clear for me yet. So I recorded that I has to set a key to make my map work on the build variants debug and everything came together.

So what I learned is that debug and release uses different SHA1 credentials and a Key can have more than one credential related to it.
When I set the key for the google maps following this link https://developers.google.com/maps/documentation/android-sdk/get-api-key I got the SHA1 credential for the debug, so to make my map work I had to get my SHA1 credential from release and add it to my key at the...

Google Cloud Platform Console >  "Select Your Project" > "Click on the Hamburger Icon on the Top Left" > APIs & Services > Credentials > "Click on your credential used for the debug mode" > Restrict usage to your Android apps > "add the new SHA1 credential from release mode"

Now the point is, how to get my SHA1 credential from release mode?
If you have already set you signingConfigs for the build variants release you probably got a keystore.jks file. With this file you can get your credential by going to your bash and type..

keytool -list -v -keystore YOUR.PATH.TO.THE.KEYSTORE.FILE -alias YOUR.KEYSTORE.ALIAS

Then they will ask you the keystore password and done!
Now you can copy and paste your SHA1 credential from release mode to your key at the Google Cloud Platform Console. =)

ContentLicense: CC BY-SA 3.0


问:
R dplyr function putting mutate, top_frac and ifelse together
Im looking for ways to mutate a new column to assign the top and bottom 20% of values using dplyr.

Here is my code and it isnt working well for me.

```<code>DF1 <- DF %>%
  group_by(Timepoint) %>%
  filter (!is.na (log2_Concentration)) %>%
  arrange (desc(log2_Concentration)) %>%
  mutate (top_bottom=ifelse (log2_Concentration=top_frac(.2), "TOP20PERC",
          ifelse (log2_Concentration=top_frac(-.2), "BOTTOM20PERC", "MID")))

ggplot(DF1, aes(x = Timepoint, y=log2_Concentration,fill=Timepoint)) +
  geom_boxplot() +
  geom_jitter(size=1,position=position_jitter(0.2), aes(col=DF1$top_bottom)) +
  scale_colour_manual(values = c("red", "gray", "blue"),
                      labels = c("TOP20PERC", "MID", "BOTTOM20PERC"))

</code>```

My hope is to assign per timepoint, the top 20%, bottom 20% and the rest as MID so I can either color these points in my ggplot.

[

Thanks a lot gurus!

答:
Probably, you can use quantile to get top and bottom 20%.

```<code>library(dplyr)

DF %>%
  filter(!is.na(log2_Concentration)) %>%
  group_by(Timepoint) %>%
  mutate(top_bottom= case_when(
           log2_Concentration > quantile(log2_Concentration, 0.8) ~"TOP20PERC",
           log2_Concentration < quantile(log2_Concentration, 0.2) ~"BOTTOM20PERC",
           TRUE ~ "MID"))
</code>```

Body:
Im looking for ways to mutate a new column to assign the top and bottom 20% of values using dplyr.

Here is my code and it isnt working well for me.

DF1 <- DF %>%
  group_by(Timepoint) %>%
  filter (!is.na (log2_Concentration)) %>%
  arrange (desc(log2_Concentration)) %>%
  mutate (top_bottom=ifelse (log2_Concentration=top_frac(.2), "TOP20PERC",
          ifelse (log2_Concentration=top_frac(-.2), "BOTTOM20PERC", "MID")))

ggplot(DF1, aes(x = Timepoint, y=log2_Concentration,fill=Timepoint)) +
  geom_boxplot() +
  geom_jitter(size=1,position=position_jitter(0.2), aes(col=DF1$top_bottom)) +
  scale_colour_manual(values = c("red", "gray", "blue"),
                      labels = c("TOP20PERC", "MID", "BOTTOM20PERC"))

My hope is to assign per timepoint, the top 20%, bottom 20% and the rest as MID so I can either color these points in my ggplot.

[

Thanks a lot gurus!

Body:
Probably, you can use quantile to get top and bottom 20%.

library(dplyr)

DF %>%
  filter(!is.na(log2_Concentration)) %>%
  group_by(Timepoint) %>%
  mutate(top_bottom= case_when(
           log2_Concentration > quantile(log2_Concentration, 0.8) ~"TOP20PERC",
           log2_Concentration < quantile(log2_Concentration, 0.2) ~"BOTTOM20PERC",
           TRUE ~ "MID"))


问:
What does it mean to pre-increment $#array?
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

```<code>$array [++$#array] = 'data';
</code>```

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

答:
A post-increment will return the variable first and then increment it.

If you used post-increment you would be modifing the last element, since its returned first, and then pushing an empty element onto the end.  On the second loop you would be modifing that empty value and pushing a new empty one for later.  So it wouldn't work like a push at all.

The pre-increment will increment the variable and then return it.  That way your example will always being writing to a new, last element of the array and work like push.  Example below:

```<code>my (@pre, @post);

$pre[$#pre++] = '1';
$pre[$#pre++] = '2';
$pre[$#pre++] = '3';

$post[++$#post] = '1';
$post[++$#post] = '2';
$post[++$#post] = '3';

print "pre keys: ".@pre."\n";
print "pre: @pre\n";
print "post keys: ".@post."\n";
print "post: @post\n";
</code>```

outputs:

```<code>pre keys: 3
pre: 2 3
post keys: 3
post: 1 2 3
</code>```

OwnerDisplayName: Paul Beckingham

ContentLicense: CC BY-SA 2.5

Body:
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

$array [++$#array] = 'data';

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

LastEditorDisplayName: brian d foy

Body:
A post-increment will return the variable first and then increment it.

If you used post-increment you would be modifing the last element, since its returned first, and then pushing an empty element onto the end.  On the second loop you would be modifing that empty value and pushing a new empty one for later.  So it wouldn't work like a push at all.

The pre-increment will increment the variable and then return it.  That way your example will always being writing to a new, last element of the array and work like push.  Example below:

my (@pre, @post);

$pre[$#pre++] = '1';
$pre[$#pre++] = '2';
$pre[$#pre++] = '3';

$post[++$#post] = '1';
$post[++$#post] = '2';
$post[++$#post] = '3';

print "pre keys: ".@pre."\n";
print "pre: @pre\n";
print "post keys: ".@post."\n";
print "post: @post\n";

outputs:

pre keys: 3
pre: 2 3
post keys: 3
post: 1 2 3


问:
Console Keyboard hit detection and interpretting
Hey so it's been reccomended to me that i should use the kdhit() function to detect a keypress in a console window:

"If it's Windows, the kbhit( ) function is the guy you want. If it's *nix, here's a kbhit( ) emulator. kbhit( ) returns immediately (no blocking) with a flag that says that there is or is not a keyboard character waiting to be read. You can test the flag to see if you should issue a keyboard read."

However i would like to know the easiest, hopefully standard way of reading the key buffer or what he calls the flag. Any tips? Thanks!

答:
There is no standard way to do this, because, as noted, there's no guarantee that your application is running on a machine that even has a keyboard device, and how one performs user interface functions like this even when there is a keyboard varies hugely from platform to platform.

On that score, whoever told you that kbhit() was a Windows function misinformed you.  kbhit(), getch() and their relatives are actually part of the (C language bindings to the) MS-DOS API.  Their presence in the runtime libraries for OS/2, Win32, and other C/C++ compilers is simply to be a porting aid for MS/PC/DR-DOS programs.  The library maps them onto whatever native mechanism exists for accessing the keyboard, if there is one at all, and usually only in the right way for TUI, not GUI, applications to access the keyboard.

If you're writing a new TUI application, don't use the MS-DOS API.  Use the proper, native, API for the platform that you're targetting, such as the Win32 Console API or the OS/2 Console API, or the POSIX General Terminal Interface (via ncurses or some such).


问:
Match everything except for specified strings
I know that the following regex will match "red", "green", or "blue".

```<code>red|green|blue
</code>```

Is there a straightforward way of making it match everything except several specified strings?

答:
Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.

Examples:

c# - Regex.Split(text, @"red|green|blue") or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x)) (see demo)

vb.net - Regex.Split(text, "red|green|blue") or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s)) (see demo, or this demo where LINQ is supported)

javascript - text.split(/red|green|blue/) (no need to use g modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)), see demo

java - text.split("red|green|blue"), or - to keep all trailing empty items - use text.split("red|green|blue", -1), or to remove all empty items use more code to remove them (see demo)

groovy - Similar to Java, text.split(/red|green|blue/), to get all trailing items use text.split(/red|green|blue/, -1) and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""}) (see demo)

kotlin - text.split(Regex("red|green|blue")) or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }, see demo

scala - text.split("red|green|blue"), or to keep all trailing empty items, use text.split("red|green|blue", -1) and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty) (see demo)

ruby - text.split(/red|green|blue/), to get rid of empty values use .split(/red|green|blue/).reject(&:empty?) (and to get both leading and trailing empty items, use -1 as the second argument, .split(/red|green|blue/, -1)) (see demo)

perl - my @result1 = split /red|green|blue/, $text;, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text; (see demo)

php - preg_split('~red|green|blue~', $text) or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY) to output no empty items (see demo)

python - re.split(r'red|green|blue', text) or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text))) (see demo)

go - Use regexp.MustCompile("red|green|blue").Split(text, -1), and if you need to remove empty items, use this code. See Go demo.

NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.

Body:
I know that the following regex will match "red", "green", or "blue".

red|green|blue

Is there a straightforward way of making it match everything except several specified strings?


问:
Finding the cumulative sum of a list
I'm trying to create a function that takes a list as an argument and then gives back a new list with the cumulative sum of that list. For example:

```<code>l = [1, 7, -3, 9, -2]
</code>```

would become:

```<code>[1, 8, 5, 14, 12]
</code>```

I am also trying to use a for loop for this function.

答:
Use itertools.accumulate:

```<code>>>> from itertools import accumulate
>>> list(accumulate([1, 7, -3, 9, -2]))
[1, 8, 5, 14, 12]
</code>```

Title: Finding the cumulative sum of a list

Body:
I'm trying to create a function that takes a list as an argument and then gives back a new list with the cumulative sum of that list. For example:

l = [1, 7, -3, 9, -2]

would become:

[1, 8, 5, 14, 12]

I am also trying to use a for loop for this function.

Body:
Use itertools.accumulate:

>>> from itertools import accumulate
>>> list(accumulate([1, 7, -3, 9, -2]))
[1, 8, 5, 14, 12]


问:
AWS ELB Logs not showing 5xx errors in
I am seeing an strange issues with AWS ELB, I am getting High-Sum-HTTP-5XX from ELB but when I go to log I do not see any request in access log which have 5XX errors.

Does elb access log does not have 5XX errors reported there. Where can I see which request were having 5XX error it will help me to find root cause. I do not see anything in my server log as well.

答:
I'm speculating, you are running a CLB (Classic Load Balancer). The access log with HTTP 5xx errors entries should be analyzed using elb_status_code and a backend_status_code
entries.

This could be off the topic but from AWS's documentation, it looks like some of these HTTP messages cannot be parsed by Classic Load Balancer (This could happen if there is reverse proxy in place on the instance that is sending an error that the ELB doesn't understand and hence are not recorded in the access logs. I could see the 404 errors in the access logs).

Title: AWS ELB Logs not showing 5xx errors in


问:
correct way to use the constructor with props?
When I print to console, it says that the auth isn't loaded and thus there is no auth.uid. Why?</p>

```<code>    constructor(props) {
        super(props);
        this.state = {
            auth : props,
            links : props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        };
    }

...

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);

</code>```

答: What I had to do was not use "this.state.auth.isLoaded" but instead "this.props.auth.isLoaded". I did not use a constructor or anything.</p>

Body:
When I print to console, it says that the auth isn't loaded and thus there is no auth.uid. Why?

    constructor(props) {
        super(props);
        this.state = {
            auth : props,
            links : props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        };
    }

...

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);


问:
How to get allocated GPU spec in Google Colab
I'm using Google Colab for deep learning and I'm aware that they randomly allocate GPU's to users. I'd like to be able to see which GPU I've been allocated in any given session. Is there a way to do this in Google Colab notebooks?

Note that I am using Tensorflow if that helps.

答:
This makes it easier to read</p>

```<code>!nvidia-smi -L
</code>```

Body:
This makes it easier to read

!nvidia-smi -L


问:
How to execute ffmpeg from with Batch For Loop
```<code>FOR %%A IN (%*) DO ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~dpA%%~nA.mov"
</code>```

This batch file is intended to take multiple files which are dragged and dropped onto it, and transcode them with ffmpeg. The command results in a whole bunch of prinouts that are similar to the command, but it does not execute. I have also tried using start cmd.exe /c, but that causes numerous windows to open which necessitates a computer reboot.

Edit: squashman has made it clear that this solution would not work anyway (Thanks!). However, I have edited the script to act on only a single file at once and it still does not execute as intended and causes a looping printout.

```<code>ffmpeg -y -i %%1 -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~dp1%%~n1.mov"
</code>```

How can I modify this script to execute ffmpeg properly?

Edit 2: Resolved by dragging and dropping a folder onto the batch script.

```<code>cd /d %1
md output
FOR /F %%A IN ('dir /B %1') do ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "output/%%~nA.mov"
pause
</code>```

答:
Expect all .mov files reside in current directory. if not, prepend path into both of "*.mov" and "%%~A.mov".

```<code>FOR /F "tokens=1,2 delims=." %%A IN ('dir /B *.mov') do ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~A.mov"
</code>```

another way is to use PPX http://www.pirosa.co.uk/demo/wxargs/wxargs.html and speed-up whole process by utilizing all CPU cores

```<code>dir /b *.%required_file_extension% |ppx2 -P 4 -L 1 ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "{}.mov"
</code>```

Body:
FOR %%A IN (%*) DO ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~dpA%%~nA.mov"

This batch file is intended to take multiple files which are dragged and dropped onto it, and transcode them with ffmpeg. The command results in a whole bunch of prinouts that are similar to the command, but it does not execute. I have also tried using start cmd.exe /c, but that causes numerous windows to open which necessitates a computer reboot.

Edit: squashman has made it clear that this solution would not work anyway (Thanks!). However, I have edited the script to act on only a single file at once and it still does not execute as intended and causes a looping printout.

ffmpeg -y -i %%1 -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~dp1%%~n1.mov"

How can I modify this script to execute ffmpeg properly?

Edit 2: Resolved by dragging and dropping a folder onto the batch script.

cd /d %1
md output
FOR /F %%A IN ('dir /B %1') do ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "output/%%~nA.mov"
pause

Body:
Expect all .mov files reside in current directory. if not, prepend path into both of "*.mov" and "%%~A.mov".

FOR /F "tokens=1,2 delims=." %%A IN ('dir /B *.mov') do ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "%%~A.mov"

another way is to use PPX http://www.pirosa.co.uk/demo/wxargs/wxargs.html and speed-up whole process by utilizing all CPU cores

dir /b *.%required_file_extension% |ppx2 -P 4 -L 1 ffmpeg -y -i %%A -c:v prores_ks -profile:v 3 -c:a pcm_s16le "{}.mov"


问:
Pass connection string to .Net Core EF library from another library
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer

ASP.NET MVC web application

As it is right now, the configuration works, and I can access my database in my web application library. However, when I constructed my data access layer with EF Db first, I got a generic class, which looks something like this:

```<code>public partial class ClassContext: DbContext
{
    public ClassContext(DbContextOptions<ClassContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Entity> Entity{ get; set; }
    ....

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("ConnString");
        }
    }
}
</code>```

As you can see, the connection string is hardcoded into my OnConfiguring method, which is not recommended.

Therefore, I followed the following "guide" here, which suggest me to use the built in DI, to pass the connection string from my Web library.

This I did:

```<code>public void ConfigureServices(IServiceCollection services)
{
    //Add connectionstring to EF
    services.AddDbContext<ClassContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStringFromAppSettings")));
}
</code>```

According to the "guide" the connectionstring should be provided to the constructor of my ClassContext class - and it sort of does, however not with any connection string..

This means, that optionsBuilder.IsConfigured evaluates false, and wants to use the hard coded connectionstring.

Therefore, I would very much like to know, if I use the DI incorrect, since i cannot access the connection string in my ClassContext class

Update

I removed the OnConfiguring() method, and do now inject the context into my service class constructor in the business logic layer the following way:

```<code>public MasterService(ClassContext context)
{
    MinorService = new MinorService(context);
}

public Stuff AddStuffIntoDatabase(Stuff test)
{
    //business logic going before here
   MinorService.addstuffMethod(test)
}
</code>```

However, now I get the following error, when I want to do an operation in my database:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider.

This did not happen before, when I configured the connectionstring wrongly in my OnConfiguring() method.

答:
What about the appsettings.json? Is it like this?

```<code>"ConnectionStrings": {
    "ConnectionStringFromAppSettings": "your_connection_string"
  }
</code>```

Configuration.GetConnectionString always search for the section "ConnectionStrings"

https://learn.microsoft.com/it-it/dotnet/api/microsoft.extensions.configuration.configurationextensions.getconnectionstring?view=dotnet-plat-ext-3.1

Body:
I have an ASP.NET Core application, which is structured in three layers i.e.:

Data access layer (Entity Framework)

Business logic layer

ASP.NET MVC web application

As it is right now, the configuration works, and I can access my database in my web application library. However, when I constructed my data access layer with EF Db first, I got a generic class, which looks something like this:

public partial class ClassContext: DbContext
{
    public ClassContext(DbContextOptions<ClassContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Entity> Entity{ get; set; }
    ....

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("ConnString");
        }
    }
}

As you can see, the connection string is hardcoded into my OnConfiguring method, which is not recommended.

Therefore, I followed the following "guide" here, which suggest me to use the built in DI, to pass the connection string from my Web library.

This I did:

public void ConfigureServices(IServiceCollection services)
{
    //Add connectionstring to EF
    services.AddDbContext<ClassContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStringFromAppSettings")));
}

According to the "guide" the connectionstring should be provided to the constructor of my ClassContext class - and it sort of does, however not with any connection string..

This means, that optionsBuilder.IsConfigured evaluates false, and wants to use the hard coded connectionstring.

Therefore, I would very much like to know, if I use the DI incorrect, since i cannot access the connection string in my ClassContext class

Update

I removed the OnConfiguring() method, and do now inject the context into my service class constructor in the business logic layer the following way:

public MasterService(ClassContext context)
{
    MinorService = new MinorService(context);
}

public Stuff AddStuffIntoDatabase(Stuff test)
{
    //business logic going before here
   MinorService.addstuffMethod(test)
}

However, now I get the following error, when I want to do an operation in my database:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider.

This did not happen before, when I configured the connectionstring wrongly in my OnConfiguring() method.

Body:
What about the appsettings.json? Is it like this?

"ConnectionStrings": {
    "ConnectionStringFromAppSettings": "your_connection_string"
  }

Configuration.GetConnectionString always search for the section "ConnectionStrings"

https://learn.microsoft.com/it-it/dotnet/api/microsoft.extensions.configuration.configurationextensions.getconnectionstring?view=dotnet-plat-ext-3.1


问:
Filtering for two identical consecutive entries in a column
Imagine a snippet of the follow data frame:

```<code>       ID        ActivityName     Time         Type    Shape
1       1             Request    0.000       Type_1      767
2       1             Request  600.000       Type_1      767
3       1               Start  600.000       Type_1     1376
4       1               Start  600.000       Type_1     1376
5       1 Schedule Activities  600.000       Type_1       15
6       1 Schedule Activities 2062.295       Type_1       15
</code>```

What I'm trying to do is to create two new columns based on the repeating entries in ActivityName.

Specifically, I want to combine two subsequent rows for the same activity into one row with a start and
complete timestamp (from Time, in seconds.)

Given that not all entries in ActivityName have a matching second entry (however, max two consecutive entries are identical), I would also like to delete such "single-standing" rows.

P.s. Although not seen in the data frame snippet, all levels of ActivityName occur repeatedly, whether in consecutive-identical or in single fashion.

Any ideas for how to go about this will be highly appreciated.

答:
Supposing that ID is a variable that indicates which entries from ActivityName should be grouped, this should work:

```<code>library(tidyverse)

df %>%
  #Group by ID and ActivityName
  group_by(ID, ActivityName) %>%
  #Stay only with entries with more than 1 row
  filter(n() > 1) %>%
  #Put the min value of Time as Start and the max value as Timestamp
  summarize (Start = min(Time),
             Timestamp = max(Time))
</code>```

Body:
Imagine a snippet of the follow data frame:

       ID        ActivityName     Time         Type    Shape
1       1             Request    0.000       Type_1      767
2       1             Request  600.000       Type_1      767
3       1               Start  600.000       Type_1     1376
4       1               Start  600.000       Type_1     1376
5       1 Schedule Activities  600.000       Type_1       15
6       1 Schedule Activities 2062.295       Type_1       15

What I'm trying to do is to create two new columns based on the repeating entries in ActivityName.

Specifically, I want to combine two subsequent rows for the same activity into one row with a start and
complete timestamp (from Time, in seconds.)

Given that not all entries in ActivityName have a matching second entry (however, max two consecutive entries are identical), I would also like to delete such "single-standing" rows.

P.s. Although not seen in the data frame snippet, all levels of ActivityName occur repeatedly, whether in consecutive-identical or in single fashion.

Any ideas for how to go about this will be highly appreciated.

Body:
Supposing that ID is a variable that indicates which entries from ActivityName should be grouped, this should work:

library(tidyverse)

df %>%
  #Group by ID and ActivityName
  group_by(ID, ActivityName) %>%
  #Stay only with entries with more than 1 row
  filter(n() > 1) %>%
  #Put the min value of Time as Start and the max value as Timestamp
  summarize (Start = min(Time),
             Timestamp = max(Time))


问:
Stuck on Paper-Scissors-Rock game
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this</p>

```<code>#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```
</code>```

答:
The problem is you are setting player2 outside the loop, and not updating it; it will constantly be the same. Instead of converting it to an intermediary value by toupper, this is probably a typical case where converting it directly to an enum would be appropriate. Instead of a switch with if, this shrinks your problem space to 3 values, which fits in a lookup-table easily.

```<code>#include <stdlib.h>
#include <stdio.h> /* `printf` requires this. */
#include <time.h>

/* https://en.wikipedia.org/wiki/X_Macro just because I don't want to type. */
#define CHOICE(X)  X(ROCK), X(PAPER), X(SCISSORS)
#define OUTCOME(X) X(LOSS), X(TIE), X(WIN)
#define NAME(A) A
#define STR(A) #A
enum Choice { CHOICE(NAME) };
static const char *const choice_names[] = { CHOICE(STR) };
enum Outcome { OUTCOME(NAME) };
static const char *const outcome_names[] = { OUTCOME(STR) };
static enum Outcome choice_outcomes[][3] = {
    { TIE, LOSS,  WIN },
    { WIN,  TIE, LOSS },
    { LOSS, WIN,  TIE }
};

int main(void) { /* <- `void` should be used to prototype. */
    char input;
    enum Choice player1, player2;
    int score[] = { 0, 0, 0 }; /* <- Replace `cpuScore` and `userScore`. */
    int count = 0;

    srand ((int) time (NULL)); /* <- `srand` should precede `rand`. */

    while(count <= 10) {
        printf("\nEnter p for Paper, r for rock, or S for scissor: ");
        /* Ignores whitespace, (_viz_ enter); breaks on error, (_eg_ EOF.) */
        if(scanf(" %c", &input) != 1) break;
        /* Convert it to `player1` immediately. */
        switch(input) {
        case 'r': case 'R':
            player1 = ROCK; break;
        case 'p': case 'P':
            player1 = PAPER; break;
        case 's': case 'S':
            player1 = SCISSORS; break;
        default:
            printf("Unexpected input, '%c'.\n", input); continue;
        }
        player2 = rand() % 3;
        printf("User choses %s _vs_ Cpu choses %s: %s.\n",
            choice_names[player1], choice_names[player2],
            outcome_names[choice_outcomes[player1][player2]]);
        score[choice_outcomes[player1][player2]]++;
        printf("User Score: %d\n", score[WIN]);
        printf("CPU Score: %d\n", score[LOSS]);
        printf("Ties: %d\n", score[TIE]);
        count++;
    }
    /* One of the places was the `scanf` break, so check, (unlikely.) */
    if(ferror(stdin)) { perror("stdin"); return 1; }

    /* Print the winner. */
    if(score[WIN] == score[LOSS]) {
        printf("Draw game!\n");
    } else if(score[WIN] > score[LOSS]) {
        printf("You win!\n");
    } else {
        printf("CPU wins!\n");
    }
    return 0;
}
</code>```

I also put userScore and cpuScore into an array indexed by enum Outcome.

Title: Stuck on Paper-Scissors-Rock game

Body:
While loop iterates two times every time, and CPU only scores point when choosing 'S' for scissors. Another question is, how do I make it toupper and where do I add that function? I have to use characters 'r','s', and 'p', instead of 1,2,3 to accept user input. Not sure how to proceed to fix this

#include <stdlib.h>
#include<time.h>

int main () {

   char player1;
   int player2;
   int userScore = 0, cpuScore = 0;
   player2 = rand ( ) % 3 + 1;
   srand ((int) time (NULL));

int count = 0;
while(count <= 10) {
  printf("\nEnter p for Paper, r for rock, or S for scissor: ");
  scanf("%c", &player1);
   switch(player1) {
      case 'P' :
       if(player1 == 'P' && player2 == 1) {
         printf("Draw!");
         break;
       } else if(player1 == 'P' && player2 == 2) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'R':
         if(player1 == 'R' && player2 == 2) {
         printf("Draw!");
         break;
       } else if(player1 == 'R' && player2 == 3) {
         userScore++;
         printf("User won this one!");
         break;
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      case 'S':
        if(player1 == 'S' && player2 == 3) {
         printf("Draw!");
         break;
       } else if(player1 == 'S' && player2 == 1) {
         userScore++;
         break;
         printf("User won this one!");
       } else {
         cpuScore++;
         printf("CPU won this one!");
         break;
       }
      default :
         printf("\nInvalid Input");
         break;
   }
   printf("\nUser Score: %d", userScore);
   printf("\nCPU Score: %d", cpuScore);
   count++;
}
   if(userScore == cpuScore) {
     printf("\nDraw game!");
   } else if(userScore > cpuScore) {
     printf("\nYou win!");
   } else {
     printf("\nCPU wins!");
   }
   return 0;
} ```

Body:
The problem is you are setting player2 outside the loop, and not updating it; it will constantly be the same. Instead of converting it to an intermediary value by toupper, this is probably a typical case where converting it directly to an enum would be appropriate. Instead of a switch with if, this shrinks your problem space to 3 values, which fits in a lookup-table easily.

#include <stdlib.h>
#include <stdio.h> /* `printf` requires this. */
#include <time.h>

/* https://en.wikipedia.org/wiki/X_Macro just because I don't want to type. */
#define CHOICE(X)  X(ROCK), X(PAPER), X(SCISSORS)
#define OUTCOME(X) X(LOSS), X(TIE), X(WIN)
#define NAME(A) A
#define STR(A) #A
enum Choice { CHOICE(NAME) };
static const char *const choice_names[] = { CHOICE(STR) };
enum Outcome { OUTCOME(NAME) };
static const char *const outcome_names[] = { OUTCOME(STR) };
static enum Outcome choice_outcomes[][3] = {
    { TIE, LOSS,  WIN },
    { WIN,  TIE, LOSS },
    { LOSS, WIN,  TIE }
};

int main(void) { /* <- `void` should be used to prototype. */
    char input;
    enum Choice player1, player2;
    int score[] = { 0, 0, 0 }; /* <- Replace `cpuScore` and `userScore`. */
    int count = 0;

    srand ((int) time (NULL)); /* <- `srand` should precede `rand`. */

    while(count <= 10) {
        printf("\nEnter p for Paper, r for rock, or S for scissor: ");
        /* Ignores whitespace, (_viz_ enter); breaks on error, (_eg_ EOF.) */
        if(scanf(" %c", &input) != 1) break;
        /* Convert it to `player1` immediately. */
        switch(input) {
        case 'r': case 'R':
            player1 = ROCK; break;
        case 'p': case 'P':
            player1 = PAPER; break;
        case 's': case 'S':
            player1 = SCISSORS; break;
        default:
            printf("Unexpected input, '%c'.\n", input); continue;
        }
        player2 = rand() % 3;
        printf("User choses %s _vs_ Cpu choses %s: %s.\n",
            choice_names[player1], choice_names[player2],
            outcome_names[choice_outcomes[player1][player2]]);
        score[choice_outcomes[player1][player2]]++;
        printf("User Score: %d\n", score[WIN]);
        printf("CPU Score: %d\n", score[LOSS]);
        printf("Ties: %d\n", score[TIE]);
        count++;
    }
    /* One of the places was the `scanf` break, so check, (unlikely.) */
    if(ferror(stdin)) { perror("stdin"); return 1; }

    /* Print the winner. */
    if(score[WIN] == score[LOSS]) {
        printf("Draw game!\n");
    } else if(score[WIN] > score[LOSS]) {
        printf("You win!\n");
    } else {
        printf("CPU wins!\n");
    }
    return 0;
}

I also put userScore and cpuScore into an array indexed by enum Outcome.


问:
How to do Javascript Function which will change the style display of element?
```<code>function burgerMenu(){
            //alert(document.getElementById("hiddenMenuUL").style.display);
            if(document.getElementById("hiddenMenuUL").style.display="none"){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else if(document.getElementById("hiddenMenuUL").style.display="block"){
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }
</code>```

I want to toggle the burger menu icon. So if I press the icon the burgerMenu() function will be toggle and verify if its display: none then change to display:block and vice versa. hiddenMenuUL is the  for list of  links.
This line below is the button line in HTML:

```<code><button class="btn" onclick="burgerMenu()">☰</button>
</code>```

My CSS for hiddenMenuUL

```<code>#hiddenMenuUL{
        display: none;
        list-style: none;
        width: 100%;
        justify-content: center;
    }
</code>```

答:
When you are writing your if, you are not actually checking if the display === "none", you are trying to set it to none.

What you should be doing looks like this:

```<code>function burgerMenu(){
            let menuStyle = document.getElementById("hiddenMenuUL").style.display;
            if(menuStyle === 'none'){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else {
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }
</code>```

Edit:

It seems display rule is defined in CSS, and isn't inline.

.style can only reach inline styles, for example:

```<code><div id="hiddenMenuUL" style="display: none;"></div>
</code>```

Adding 'display: none' inline like in the example above should be the fastest and easiest way to 'fix' it in your particular scenario, although it probably wouldn't be considered the best practice.

Body:
function burgerMenu(){
            //alert(document.getElementById("hiddenMenuUL").style.display);
            if(document.getElementById("hiddenMenuUL").style.display="none"){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else if(document.getElementById("hiddenMenuUL").style.display="block"){
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }

I want to toggle the burger menu icon. So if I press the icon the burgerMenu() function will be toggle and verify if its display: none then change to display:block and vice versa. hiddenMenuUL is the  for list of  links.
This line below is the button line in HTML:

<button class="btn" onclick="burgerMenu()">☰</button>

My CSS for hiddenMenuUL

#hiddenMenuUL{
        display: none;
        list-style: none;
        width: 100%;
        justify-content: center;
    }

Body:
When you are writing your if, you are not actually checking if the display === "none", you are trying to set it to none.

What you should be doing looks like this:

function burgerMenu(){
            let menuStyle = document.getElementById("hiddenMenuUL").style.display;
            if(menuStyle === 'none'){
                document.getElementById("hiddenMenuUL").style.display="block";
            }
            else {
                document.getElementById("hiddenMenuUL").style.display="none";
            }
    }

Edit:

It seems display rule is defined in CSS, and isn't inline.

.style can only reach inline styles, for example:

<div id="hiddenMenuUL" style="display: none;"></div>

Adding 'display: none' inline like in the example above should be the fastest and easiest way to 'fix' it in your particular scenario, although it probably wouldn't be considered the best practice.


问:
Handling an interactive script from another script , using python
I have a shell script and this one is interactive and I am creating some automation to provide inputs to this shell scripts. The automation is done using Python. example,

the shell script waits for an input like, "what is the domain name?"
now the python should be able to provide the input and press ENTER.

Please provide solutions to handle this kind of session with some example.

答:
pexpect: http://pypi.python.org/pypi/pexpect/

it comes with a bunch of examples.  e.g. this one for ftp:

```<code>import pexpect
import sys

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # Escape character defaults to ^]
# At this point this script blocks until the user presses the escape character
# or until the child exits. The human user and the child should be talking
# to each other now.

# At this point the script is running again.
print 'Left interactve mode.'

# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
if child.isalive():
    child.sendline('bye') # Try to ask ftp child to exit.
    child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
    print 'Child did not exit gracefully.'
else:
    print 'Child exited gracefully.'
</code>```

Body:
pexpect: http://pypi.python.org/pypi/pexpect/

it comes with a bunch of examples.  e.g. this one for ftp:

import pexpect
import sys

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # Escape character defaults to ^]
# At this point this script blocks until the user presses the escape character
# or until the child exits. The human user and the child should be talking
# to each other now.

# At this point the script is running again.
print 'Left interactve mode.'

# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
if child.isalive():
    child.sendline('bye') # Try to ask ftp child to exit.
    child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
    print 'Child did not exit gracefully.'
else:
    print 'Child exited gracefully.'


问:
Execution failed for task ':app:mergeDexDebug'. Firestore | Flutter
Trying to use Firestore in my project. My project is a brand new one, but having problems running the app on my device without getting an error:
Execution failed for task ':app:mergeDexDebug'.

My app is using AndroidX. I've added my google-services.json file, followed the steps etc.

Yaml file:

```<code>dependencies:
  cloud_firestore: ^0.13.3
</code>```

android/build.gradle:

```<code>com.google.gms:google-services:4.3.3
</code>```

Full error:

FAILURE: Build failed with an exception.

What went wrong:
      Execution failed for task ':app:mergeDexDebug'.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
       The number of method references in a .dex file cannot exceed 64K.
       Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

答:
The problem is with multidex builder. Actually, this often happens when you have imported a lot of packages in your yaml file which cannot fit into a single .dex built hence you have to enable multidex.

Go to android/app/build.gradle and add the following lines of code:

```<code>dependencies {
  implementation 'com.android.support:multidex:2.0.1' //enter the latest multidex version
}
android {
    defaultConfig {
        multiDexEnabled true
    }
}
</code>```

Body:
Trying to use Firestore in my project. My project is a brand new one, but having problems running the app on my device without getting an error:
Execution failed for task ':app:mergeDexDebug'.

My app is using AndroidX. I've added my google-services.json file, followed the steps etc.

Yaml file:

dependencies:
  cloud_firestore: ^0.13.3

android/build.gradle:

com.google.gms:google-services:4.3.3

Full error:

FAILURE: Build failed with an exception.

What went wrong:
      Execution failed for task ':app:mergeDexDebug'.
  A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
  com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
       The number of method references in a .dex file cannot exceed 64K.
       Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

Body:
The problem is with multidex builder. Actually, this often happens when you have imported a lot of packages in your yaml file which cannot fit into a single .dex built hence you have to enable multidex.

Go to android/app/build.gradle and add the following lines of code:

dependencies {
  implementation 'com.android.support:multidex:2.0.1' //enter the latest multidex version
}
android {
    defaultConfig {
        multiDexEnabled true
    }
}


问:
regex unicode character in vim
I'm being an idiot.

Someone cut and pasted some text from microsoft word into my lovely html files.

I now have these unicode characters instead of regular quote symbols, (i.e. quotes appear as <92> in the text)

I want to do a regex replace but I'm having trouble selecting them.

```<code>:%s/\u92/'/g
:%s/\u5C/'/g
:%s/\x92/'/g
:%s/\x5C/'/g
</code>```

...all fail. My google-fu has failed me.

答:
This solution might not address the problem as originally stated, but it does address a different but very closely related one and I think it makes a lot of sense to place it here.

I don't know in which version of Vim it was implemented, but I was working on 7.4 when I tried it.

When in Edit mode, the sequence to output unicode characters is: ctrl-v u xxxx where xxxx is the code point. For instance outputting the euro sign would be ctrl-v u 20ac.

I tried it in Command mode as well and it worked. That is, to replace all instances of "20 euro" in my document with "20 €", I'd do:

```<code>:%s/20 euro/20 <ctrl-v u 20ac>/gc
</code>```

In the above <ctrl-v u 20ac> is not literal, it's the sequence of keys that will output the € character.

Title: regex unicode character in vim

Body:
I'm being an idiot.

Someone cut and pasted some text from microsoft word into my lovely html files.

I now have these unicode characters instead of regular quote symbols, (i.e. quotes appear as <92> in the text)

I want to do a regex replace but I'm having trouble selecting them.

:%s/\u92/'/g
:%s/\u5C/'/g
:%s/\x92/'/g
:%s/\x5C/'/g

...all fail. My google-fu has failed me.

Body:
This solution might not address the problem as originally stated, but it does address a different but very closely related one and I think it makes a lot of sense to place it here.

I don't know in which version of Vim it was implemented, but I was working on 7.4 when I tried it.

When in Edit mode, the sequence to output unicode characters is: ctrl-v u xxxx where xxxx is the code point. For instance outputting the euro sign would be ctrl-v u 20ac.

I tried it in Command mode as well and it worked. That is, to replace all instances of "20 euro" in my document with "20 €", I'd do:

:%s/20 euro/20 <ctrl-v u 20ac>/gc

In the above <ctrl-v u 20ac> is not literal, it's the sequence of keys that will output the € character.


问:
IntelliJ IDEA underlines variables when using += in JAVA
Since the new update (2018.2) IntelliJ IDEA underlines variables, when they are "unnecessarily" reassigned - this includes, however, each use of "+=".

Is this a mistake in the IDE or am I getting it wrong?

Please see this basic method as an example. (It just adds a list of numbers.)

答: Hope this screenshot would help.

Body: Hope this screenshot would help.


问:
How to get the content/type of a file at runtime
I am trying to determine dynamically the content/type of a input file. If I would be in a windows application I could write code like this (from this blog)

```<code>private string GetContentType(string fileName) {
    string contentType = "application/octetstream";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (registryKey != null && registryKey.GetValue("Content Type") != null)
        contentType = registryKey.GetValue("Content Type").ToString();
    return contentType;
}
</code>```

What other methods are more suitable for an MVC application?

I would like to use the param within the Controller.File(...) method that receive a filepath and a contentype.

答:
.NET CORE
Using  Microsoft.AspNetCore.StaticFiles

```<code>var provider = new FileExtensionContentTypeProvider();
string contentType;
if(!provider.TryGetContentType(fileName, out contentType))
{
    contentType = "application/octet-stream";
}
</code>```

Body:
I am trying to determine dynamically the content/type of a input file. If I would be in a windows application I could write code like this (from this blog)

private string GetContentType(string fileName) {
    string contentType = "application/octetstream";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (registryKey != null && registryKey.GetValue("Content Type") != null)
        contentType = registryKey.GetValue("Content Type").ToString();
    return contentType;
}

What other methods are more suitable for an MVC application?

I would like to use the param within the Controller.File(...) method that receive a filepath and a contentype.

Body:
.NET CORE
Using  Microsoft.AspNetCore.StaticFiles

var provider = new FileExtensionContentTypeProvider();
string contentType;
if(!provider.TryGetContentType(fileName, out contentType))
{
    contentType = "application/octet-stream";
}


问:
I'm working on a C++ application to convert binary to decimal numbers
i'm working on a C++ application, to convert binary's to decimal numbers, and currently i have a working application, but the problem arises now that it have to have intermediate results.

Since i know the conversation on paper, and i know the basics of C++ i didn't believe this would be very difficult, but i need some help, i don't need you to write it for me, i need someone to help point me in the right direction, so i can solve it by myself.
The intermediate results would have to be something like this if i convert 1100 to decimal:

```<code>---------------
0 * 2⁰ = 0
0 * 2¹ = 0
1 * 2² = 4
1 * 2³ = 8
-----------------
</code>```

which would end up being 12 (8 + 4 + 0 + 0 = 12)

the code so far can be found here: https://paste.ubuntu.com/p/fP2GfT5Pzq/
and below

```<code>#include <iostream>
#include <cmath>

using namespace std;

int binary_to_decimal(long long);

int main()
{
    long long number;
    cout << "Please enter the Binary you wish to convert: " << endl;
    cin >> number;

    cout << "In binary : '" << number << "' In decimal: '" << binary_to_decimal(number) << "'" << endl;
}

int binary_to_decimal(long long number)
{
    int decimal_number = 0, i = 0, remainder;
    while (number != 0)
    {
        remainder = number % 10;

        // Number = number divided by then
        number /= 10;

        // decimal_number = decimal_number + remainder to the power of 2
        decimal_number += remainder * pow(2, i);
        ++i;
    }
    return decimal_number;
}
</code>```

Hope you can help :)

答:
If you just want to print intermediate results, then you are very close. Since you are very close, the only hint I could give you is: you need to print stuff inside that while loop. Here's the code, you don't have to look at it if you don't want to :)

cout << "---------------" << endl;
while (number != 0)
{
    remainder = number % 10;

    number /= 10;

    int digit = remainder * pow(2,i);
    decimal_number += digit;

    cout << remainder << " * (2^" << i << ") = " << digit << endl;
    ++i;
}
cout << "---------------" << endl;
```

Body:
i'm working on a C++ application, to convert binary's to decimal numbers, and currently i have a working application, but the problem arises now that it have to have intermediate results.

Since i know the conversation on paper, and i know the basics of C++ i didn't believe this would be very difficult, but i need some help, i don't need you to write it for me, i need someone to help point me in the right direction, so i can solve it by myself.
The intermediate results would have to be something like this if i convert 1100 to decimal:

---------------
0 * 2⁰ = 0
0 * 2¹ = 0
1 * 2² = 4
1 * 2³ = 8
-----------------

which would end up being 12 (8 + 4 + 0 + 0 = 12)

the code so far can be found here: https://paste.ubuntu.com/p/fP2GfT5Pzq/
and below

#include <iostream>
#include <cmath>

using namespace std;

int binary_to_decimal(long long);

int main()
{
    long long number;
    cout << "Please enter the Binary you wish to convert: " << endl;
    cin >> number;

    cout << "In binary : '" << number << "' In decimal: '" << binary_to_decimal(number) << "'" << endl;
}

int binary_to_decimal(long long number)
{
    int decimal_number = 0, i = 0, remainder;
    while (number != 0)
    {
        remainder = number % 10;

        // Number = number divided by then
        number /= 10;

        // decimal_number = decimal_number + remainder to the power of 2
        decimal_number += remainder * pow(2, i);
        ++i;
    }
    return decimal_number;
}

Hope you can help :)


问:
How to run a code in an Amazone's EC2 instance?
I understand nearly nothing to the functioning of EC2. I created an Amazon Web Service (AWS) account. Then I launched an EC2 instance.

And now I would like to execute a Python code in this instance, and I don't know how to proceed. Is it necessary to load the code somewhere in the instance? Or in Amazon's S3 and to link it to the instance?

Where is there a guide that explain the usages of instance that are possible? I feel like a man before a flying saucer's dashboard without user's guide.

答:
You have a variety of options. You can browse through a large library of AMIs here.

You can import a vm, instructions are here.

This is a general article about AWS and python.

And in this article, the author takes you through a more advanced system with a combination of datastores in python using the highly recommend django framework.


问:
' Sequence contains no elements' exception when initializing ninject
I have a problem with Ninject which I have not seen before and don't know how to fix. I am using the MVC NuGet package for MVC 5.

In my NinjectWebCommon.cs, there is the following method:

```<code>    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }
</code>```

However, it falls over when trying to execute the last line, complaining that the "sequence contains no elements". I was previously using Unity for DI but have changed to Ninject.

Any ideas?

Thanks in advance, M

答:
An additional explanation detail to extend the helpful answer by @Greg_B:

A reference to another project in the solution that also uses Ninject. Removing this reference solves the problem.

Body:
I have a problem with Ninject which I have not seen before and don't know how to fix. I am using the MVC NuGet package for MVC 5.

In my NinjectWebCommon.cs, there is the following method:

    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

However, it falls over when trying to execute the last line, complaining that the "sequence contains no elements". I was previously using Unity for DI but have changed to Ninject.

Any ideas?

Thanks in advance, M


问:
How to copy whole columns from one sheet to the next if it finds a match in the header in sheet 2
I'm working with two sheets. One sheet has the full raw data while the other has a select few headers from sheet 1. If it finds a match on the header, i need it to copy the full column from sheet one to sheet 2

and it copies it to sheet 2

Here is my code so far but i can't figure out how to break the loop so that it goes through every column on sheet 1 until it finds a match:

```<code>Private Sub CommandButton1_Click()

Dim ShtOne As Worksheet, ShtTwo As Worksheet
Dim shtOneHead As Range, shtTwoHead As Range`enter code here`
Dim headerOne As Range, headerTwo As Range

Set ShtOne = Sheets("Sheet1")
Set ShtTwo = Sheets("Sheet2")
'row count
Dim b As Long
b = ShtOne.Cells(Rows.Count, 1).End(xlUp).Row
'column count in sheet 1
Dim a As Long
a = ShtOne.Cells(1, Columns.Count).End(xlToLeft).Column
'column count in sheet 2
Dim c As Long
c = ShtTwo.Cells(1, Columns.Count).End(xlToLeft).Column

Dim lastCol As Long
'get all of the headers in the first sheet, assuming in row 1
lastCol = ShtOne.Cells(1, Columns.Count).End(xlToLeft).Column
Set shtOneHead = ShtOne.Range("A1", ShtOne.Cells(1, lastCol))

'get all of the headers in second sheet, assuming in row 1
lastCol = ShtTwo.Cells(1, Columns.Count).End(xlToLeft).Column
Set shtTwoHead = ShtTwo.Range("A1", ShtTwo.Cells(1, lastCol))

'stops the visual flickering of files opening and closing - run at the background
Application.ScreenUpdating = False

'start loop from first row to last row
'For i = 1 To a
i = 1
j = 0
'actually loop through and find values
For Each headerOne In shtOneHead
j = j + 1
    For Each headerTwo In shtTwoHead
    'copy and paste each value
            If headerTwo.Value = headerOne.Value Then

    'copies one row at a time (a bit slow)
               ' headerOne.Offset(i, 0).Copy
               ' headerTwo.Offset(i, 0).PasteSpecial xlPasteAll

    'copies whole rows at a time
            ShtOne.Columns(i).Copy ShtTwo.Columns(j)
            i = i + 1
                Application.CutCopyMode = False
        Exit For
        End If
    Next headerTwo
Next headerOne

'Next

End Sub
</code>```

答:
Assuming your headers are on row 1 for both sheets and that you will always be pasting on the second row on Sheet2.

Only loop through your column headers on the second sheet. Use Range.Find to search for each header on Sheet1. If the header is found, copy and paste accordingly

```<code>Sub Headerz()

Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")

Dim LC As Long, i As Long, LR As Long
Dim Found As Range

LC = ws2.Cells(1, ws2.Columns.Count).End(xlToLeft).Column

For i = 1 To LC
    Set Found = ws1.Rows(1).Find(ws2.Cells(1, i).Value)

    If Not Found Is Nothing Then

        LR = ws1.Cells(ws1.Rows.Count, Found.Column).End(xlUp).Row
        ws1.Range(ws1.Cells(2, Found.Column), ws1.Cells(LR, Found.Column)).Copy
        ws2.Cells(2, i).PasteSpecial xlPasteValues

    End If

    Set Found = Nothing
Next i

End Sub
</code>```

Body:
I'm working with two sheets. One sheet has the full raw data while the other has a select few headers from sheet 1. If it finds a match on the header, i need it to copy the full column from sheet one to sheet 2

and it copies it to sheet 2

Here is my code so far but i can't figure out how to break the loop so that it goes through every column on sheet 1 until it finds a match:

Private Sub CommandButton1_Click()

Dim ShtOne As Worksheet, ShtTwo As Worksheet
Dim shtOneHead As Range, shtTwoHead As Range`enter code here`
Dim headerOne As Range, headerTwo As Range

Set ShtOne = Sheets("Sheet1")
Set ShtTwo = Sheets("Sheet2")
'row count
Dim b As Long
b = ShtOne.Cells(Rows.Count, 1).End(xlUp).Row
'column count in sheet 1
Dim a As Long
a = ShtOne.Cells(1, Columns.Count).End(xlToLeft).Column
'column count in sheet 2
Dim c As Long
c = ShtTwo.Cells(1, Columns.Count).End(xlToLeft).Column

Dim lastCol As Long
'get all of the headers in the first sheet, assuming in row 1
lastCol = ShtOne.Cells(1, Columns.Count).End(xlToLeft).Column
Set shtOneHead = ShtOne.Range("A1", ShtOne.Cells(1, lastCol))

'get all of the headers in second sheet, assuming in row 1
lastCol = ShtTwo.Cells(1, Columns.Count).End(xlToLeft).Column
Set shtTwoHead = ShtTwo.Range("A1", ShtTwo.Cells(1, lastCol))

'stops the visual flickering of files opening and closing - run at the background
Application.ScreenUpdating = False

'start loop from first row to last row
'For i = 1 To a
i = 1
j = 0
'actually loop through and find values
For Each headerOne In shtOneHead
j = j + 1
    For Each headerTwo In shtTwoHead
    'copy and paste each value
            If headerTwo.Value = headerOne.Value Then

    'copies one row at a time (a bit slow)
               ' headerOne.Offset(i, 0).Copy
               ' headerTwo.Offset(i, 0).PasteSpecial xlPasteAll

    'copies whole rows at a time
            ShtOne.Columns(i).Copy ShtTwo.Columns(j)
            i = i + 1
                Application.CutCopyMode = False
        Exit For
        End If
    Next headerTwo
Next headerOne

'Next

End Sub

Body:
Assuming your headers are on row 1 for both sheets and that you will always be pasting on the second row on Sheet2.

Only loop through your column headers on the second sheet. Use Range.Find to search for each header on Sheet1. If the header is found, copy and paste accordingly

Sub Headerz()

Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")

Dim LC As Long, i As Long, LR As Long
Dim Found As Range

LC = ws2.Cells(1, ws2.Columns.Count).End(xlToLeft).Column

For i = 1 To LC
    Set Found = ws1.Rows(1).Find(ws2.Cells(1, i).Value)

    If Not Found Is Nothing Then

        LR = ws1.Cells(ws1.Rows.Count, Found.Column).End(xlUp).Row
        ws1.Range(ws1.Cells(2, Found.Column), ws1.Cells(LR, Found.Column)).Copy
        ws2.Cells(2, i).PasteSpecial xlPasteValues

    End If

    Set Found = Nothing
Next i

End Sub


问:
How do I make my zsh prompt look like sh/bash end with $ instead of %?
Can anyone show how to modify the following zsh prompt environment var assignment to make its emitted string end with $ (followed by a space), instead of %?

```<code>export PROMPT='%F{111}%m:%F{2}%~ %#%f '
</code>```

macOS Catalina changed the default shell to zsh, and I saw an article that encouraged a switch. I assumed backward compatibility but prompt logic changed.

答:
```<code>export PROMPT='%F{111}%m:%F{2}%~ $%f '
</code>```

For more options on zsh prompt string customization - http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Login-information

Body:
Can anyone show how to modify the following zsh prompt environment var assignment to make its emitted string end with $ (followed by a space), instead of %?

export PROMPT='%F{111}%m:%F{2}%~ %#%f '

macOS Catalina changed the default shell to zsh, and I saw an article that encouraged a switch. I assumed backward compatibility but prompt logic changed.

Body:
export PROMPT='%F{111}%m:%F{2}%~ $%f '

For more options on zsh prompt string customization - http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Login-information


问:
Use random name generator after getting input from keyboard
```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package username;

import java.util.Scanner;
import java.util.Random;

public class UserName {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String user_Name1;
        System.out.print("Please enter the first username: ");
        user_Name1 = input.nextLine();
            if (user_Name1.equals("")) {
                String[] randoms = {"Luke", "Leia", "Sophia", "David"};
                name = randoms[((int) Math.random()*randoms.length)];
            }

            System.out.println("" + user_Name1);

    }

}
</code>```

答:
This should do the job:</p>

```<code>// Starting in main function after the System.out.println()

String name = scanner.nextLine();
scanner.close(); // optional but recommended

if (name == null || name.equals("") {
    // Do random pick as you did before and assign it to name
    String[] randoms = {"Luke", "Leia", "Sophia", "David"}; // Add all names here
    name = randoms[((int) Math.random()*randoms.length)]; // Pick random name
}

System.out.println("Your name is " + name);

// The rest of the class with closing brackets
</code>```

Body:
This should do the job:

// Starting in main function after the System.out.println()

String name = scanner.nextLine();
scanner.close(); // optional but recommended

if (name == null || name.equals("") {
    // Do random pick as you did before and assign it to name
    String[] randoms = {"Luke", "Leia", "Sophia", "David"}; // Add all names here
    name = randoms[((int) Math.random()*randoms.length)]; // Pick random name
}

System.out.println("Your name is " + name);

// The rest of the class with closing brackets


问:
Serenity how to run on tests chrome emulator (mobile mode in chrome web browser)
I am new to Serenity and I wanted to run the test in the mobile mode present in the chome web browser, it is called as mobile emulation. I have refered this link and using selenium java i have managed to do it.
https://chromedriver.chromium.org/mobile-emulation

I need to do the same with Serenity.

Can anybody tell me what needs to be done ? It can be added to the property file, if yes then how ?

答:
The link you provided gives you the Java code:

```<code>Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Nexus 5");

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
WebDriver driver = new ChromeDriver(chromeOptions);
</code>```

A trivial search for "serenity chrome options" leads to (first hit!) this page, which says:

In Serenity, you would pass these using properties prefixed with the chrome_preferences prefix

So perhaps something like:

```<code>chrome_preferences.mobileEmulation.deviceName = "Nexus 5"
</code>```

Body:
The link you provided gives you the Java code:

Map<String, String> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceName", "Nexus 5");

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
WebDriver driver = new ChromeDriver(chromeOptions);

A trivial search for "serenity chrome options" leads to (first hit!) this page, which says:

In Serenity, you would pass these using properties prefixed with the chrome_preferences prefix

So perhaps something like:

chrome_preferences.mobileEmulation.deviceName = "Nexus 5"


问:
can't initialized Vue in laravel 5.4
i can't make run a simple Vue on my Laravel 5.4 project

i have the dependeces in package.json

```<code> "devDependencies": {
    "axios": "^0.15.3",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^3.2.3",
    "jquery": "^3.1.1",
    "laravel-mix": "^0.8.3",
    "lodash": "^4.17.4",
    "vue": "^2.1.10"
  },
</code>```

I have the app.js placed on the webpack.mix

```<code>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js');
</code>```

In my app.js i have:

```<code>/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#contenedorPrincipal'
});
</code>```

Example.vue

```<code><template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Component</div>

                    <div class="panel-body">
                        I'm an example component!
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>
</code>```

And in my view, i have a div with id = contenedorPrincipal, in the layout and i call example in a single view..

app.blade.php

```<code><div class="content-page" id="contenedorPrincipal">
    <div class="content">
        @yield('content')

    </div>
</code>```

in the vie myview.blade.php

```<code>@extends('layouts.app')

@section('content')
<div>
   <example></example>
</div>
@stop
</code>```

The npm run watch is working all the time....

When i open this view, nothing display, no error, no vue components detected from vue inspector....

i don't know what is the problem..

答:
Fixed, i forget in my app.blade.php

```<code><script src="{{ asset('js/app.js') }}"></script>
</code>```

Thank you everyone!

Title: can't initialized Vue in laravel 5.4

Body:
i can't make run a simple Vue on my Laravel 5.4 project

i have the dependeces in package.json

 "devDependencies": {
    "axios": "^0.15.3",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^3.2.3",
    "jquery": "^3.1.1",
    "laravel-mix": "^0.8.3",
    "lodash": "^4.17.4",
    "vue": "^2.1.10"
  },

I have the app.js placed on the webpack.mix

let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js');

In my app.js i have:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#contenedorPrincipal'
});

Example.vue

<template>

Example Component

                        I'm an example component!

</template>

And in my view, i have a div with id = contenedorPrincipal, in the layout and i call example in a single view..

app.blade.php

        @yield('content')

in the vie myview.blade.php

@extends('layouts.app')

@section('content')

   <example></example>

@stop

The npm run watch is working all the time....

When i open this view, nothing display, no error, no vue components detected from vue inspector....

i don't know what is the problem..

Body:
Fixed, i forget in my app.blade.php

<script src="{{ asset('js/app.js') }}"></script>

Thank you everyone!


问:
Media queries running weird because of non-integer width
Can't say is it a real problem or I'm just being paranoid but this behavior of media queries is really driving me crazy for last couple of hours.

Let's consider this really simple CSS.

```<code> body {background:yellow}

 @media (max-width:399px) {
   body {background:red}
 }

 @media (min-width:400px) {
   body {background:blue}
 }
</code>```

Problem happens when width is 399.333px! (or any float-value between 399 and 400 integers)

My logic says that by using this CSS style page will never turn yellow, right? It should be red when viewport size is shorter than 400px in width and blue when it's 400px and over.

Weird behavior happens with Opera browser (I'm using 36.0 at the moment) on Windows when page is zoomed-in. I understand that viewport width is calculated using real viewport width and current zoom-level and this value should always be integer. But...

Looks like Opera doesn't round/floor/ceil that value which affects on entire page. I'm getting yellow background when Opera finds out that viewport-width is not 399px or 400px but it's 399.333px!? So none of media queries fulfills condition.

I've already tried to find an answer here and web-wide but nothing is close enough to this problem. This problem already happened to me when I was using em units so I could work around and turn them to pixels, but I can't affect user's decision about using browser's zoom feature.

Is there something I can do to prevent this or that's just the way it is?

The easiest way to simulate this behavior is hitting CTRL,+ three times and than easily move vertical slider in Object Inspector.

update:

Yes, I can fix it with "mobile/desktop first" approach by linking each media break-point to previous one but that's not part of my question. Also, default body style is here as visual aid only and changing that really doesn't solve problem.

答:
Similar layout

The answer to this question should be to avoid the problem altogether, and simply leave one of the media queries out, and let one media query override the other:

body {background: red;}

@media (min-width: 400px)
{
    body {background: blue;}
}
```

<p>However, when you need a fundamentally different layout, this would cause a lot of additional code simply to reset one case from the other. As is the case in the following example:</p>

<pre class="lang-css prettyprint-override"><code>.some-element {background-color: red;border-left: 30px;}

@media (max-width: 399px)
{
    .some-element {border-left: none;padding-bottom: 40px;}
}
</code>```

Whereas it would be shorter and more elegant to write:

.some-element {background-color: red;}

@media (min-width: 400px)
{
    .some-element {border-left: 30px;}
}

@media (max-width: 399px)
{
    .some-element {padding-bottom: 40px;}
}
```

<p>But neither of the media-queries in the last example code will take effect if the width is for instance <code>399.5px</code>. Read the next part of this answer, if you still wish to write such code with perfect coverage.</p>

<h1>Use floating-point numbers</h1>

<p>Unfortunately the media queries for min-width and max-width values are always inclusive. A browser uses fractional pixels when it has zooming capabilities. Therefore, a simple solution to this problem is to increment your threshold pixel value of <code>400px</code> with the lowest possible fraction, for instance to <code>400.00001px</code>. However, the crucial question then remains, what is the lowest possible fraction?</p>

<p>The CSS specification does not say anything about which data types are used to store numbers:</p>

<blockquote>
  <p>A <code><number></code> can either be an <code><integer></code>, or it can be zero or more digits followed by a dot (.) followed by one or more digits.</p>
</blockquote>

<p>But according to the answer to 'Why does Bootstrap use a 0.02px difference between screen size thresholds in its media queries?':</p>

<blockquote>
  <p>Indeed, cross-browser compatibility is the reason: according to Bootstrap's source, 0.02px is used "rather than 0.01px to work around a current rounding bug in Safari.</p>
</blockquote>

<p>Apparently, bootstrap being a widely used framework, it seems that 0.02 would be the correct value to use in this specific case.</p>

<p>In your case, to get a perfect coverage of your media queries - and thereby prevent a yellow background, the solution would look like this:</p>

<pre class="lang-css prettyprint-override"><code>body {background: yellow;}

@media (max-width:400px) {
    body {background: red;}
}

@media (min-width:400.02px) {
    body {background: blue;}
}
</code>```

Use CSS4

As of CSS4 you may use intuitive operators for media queries such as >= and <= instead of min- and max-, and more importantly, additionally you may use exclusive operators such as > and < which immediately solves the problem (see here).

However, it may not be widely supported. Unfortunately, this feature is not yet on Can I Use to check browser support. You may check it yourself using this codepen. It seems to work in the latest version of Firefox.

The solution would then be as simple as:

body {background: yellow;}

@media (width <= 400px) {
    body {background: red;}
}

@media (width > 400px) {
    body {background: blue;}
}
```

Body:
Can't say is it a real problem or I'm just being paranoid but this behavior of media queries is really driving me crazy for last couple of hours.

Let's consider this really simple CSS.

 body {background:yellow}

 @media (max-width:399px) {
   body {background:red}
 }

 @media (min-width:400px) {
   body {background:blue}
 }

Problem happens when width is 399.333px! (or any float-value between 399 and 400 integers)

My logic says that by using this CSS style page will never turn yellow, right? It should be red when viewport size is shorter than 400px in width and blue when it's 400px and over.

Weird behavior happens with Opera browser (I'm using 36.0 at the moment) on Windows when page is zoomed-in. I understand that viewport width is calculated using real viewport width and current zoom-level and this value should always be integer. But...

Looks like Opera doesn't round/floor/ceil that value which affects on entire page. I'm getting yellow background when Opera finds out that viewport-width is not 399px or 400px but it's 399.333px!? So none of media queries fulfills condition.

I've already tried to find an answer here and web-wide but nothing is close enough to this problem. This problem already happened to me when I was using em units so I could work around and turn them to pixels, but I can't affect user's decision about using browser's zoom feature.

Is there something I can do to prevent this or that's just the way it is?

The easiest way to simulate this behavior is hitting CTRL,+ three times and than easily move vertical slider in Object Inspector.

update:

Yes, I can fix it with "mobile/desktop first" approach by linking each media break-point to previous one but that's not part of my question. Also, default body style is here as visual aid only and changing that really doesn't solve problem.

Body:
Similar layout

The answer to this question should be to avoid the problem altogether, and simply leave one of the media queries out, and let one media query override the other:

body {background: red;}

@media (min-width: 400px)
{
    body {background: blue;}
}

However, when you need a fundamentally different layout, this would cause a lot of additional code simply to reset one case from the other. As is the case in the following example:

.some-element {background-color: red;border-left: 30px;}

@media (max-width: 399px)
{
    .some-element {border-left: none;padding-bottom: 40px;}
}

Whereas it would be shorter and more elegant to write:

.some-element {background-color: red;}

@media (min-width: 400px)
{
    .some-element {border-left: 30px;}
}

@media (max-width: 399px)
{
    .some-element {padding-bottom: 40px;}
}

But neither of the media-queries in the last example code will take effect if the width is for instance 399.5px. Read the next part of this answer, if you still wish to write such code with perfect coverage.

Use floating-point numbers

Unfortunately the media queries for min-width and max-width values are always inclusive. A browser uses fractional pixels when it has zooming capabilities. Therefore, a simple solution to this problem is to increment your threshold pixel value of 400px with the lowest possible fraction, for instance to 400.00001px. However, the crucial question then remains, what is the lowest possible fraction?

The CSS specification does not say anything about which data types are used to store numbers:

A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits.

But according to the answer to 'Why does Bootstrap use a 0.02px difference between screen size thresholds in its media queries?':

Indeed, cross-browser compatibility is the reason: according to Bootstrap's source, 0.02px is used "rather than 0.01px to work around a current rounding bug in Safari.

Apparently, bootstrap being a widely used framework, it seems that 0.02 would be the correct value to use in this specific case.

In your case, to get a perfect coverage of your media queries - and thereby prevent a yellow background, the solution would look like this:

body {background: yellow;}

@media (max-width:400px) {
    body {background: red;}
}

@media (min-width:400.02px) {
    body {background: blue;}
}

Use CSS4

As of CSS4 you may use intuitive operators for media queries such as >= and <= instead of min- and max-, and more importantly, additionally you may use exclusive operators such as > and < which immediately solves the problem (see here).

However, it may not be widely supported. Unfortunately, this feature is not yet on Can I Use to check browser support. You may check it yourself using this codepen. It seems to work in the latest version of Firefox.

The solution would then be as simple as:

body {background: yellow;}

@media (width <= 400px) {
    body {background: red;}
}

@media (width > 400px) {
    body {background: blue;}
}


问:
convert a character column into numeric in R
I wonder why my conversion of the "t5" column was not successful--

The "t5" column is all characters, I want to convert it into a numeric column, leave non-numeric value as NA, named as "t5.num" in the tibble.

My code below:
first of all I assigned the name, then trying to mutate the column, but it did  not work--

```<code>d <- tibble(id = c(3, 7, 1, 10,100), t5 = c("10", "<1", "NA", "8","78"))
convert_column <- function(data, col_name) {
    new_col_name <- paste0(rlang::enquo(col_name),".num")
    data %>%
        mutate(new_col_name = as.numeric(!!col_name))
     }
d %>% convert_column("t5")
</code>```

Can someone point out what is wrong with my code? thanks for your help!

答:
To get new_col_name you don't need enquo. To assign new_col_name as name of the column use !!  + :=. As you are passing col_name as a string we need to convert it to symbol (sym) and then evaluate (!!).

```<code>library(dplyr)
library(rlang)

convert_column <- function(data, col_name) {

   new_col_name <- paste0(col_name,".num")
   data %>% mutate(!!new_col_name := as.numeric(!!sym(col_name)))
}

d %>% convert_column("t5")

# A tibble: 5 x 3
#     id t5    t5.num
#  <dbl> <chr>  <dbl>
#1     3 10        10
#2     7 <1        NA
#3     1 NA        NA
#4    10 8          8
#5   100 78        78
</code>```

Returns a warning while  converting "<1" to numeric before turning it to NA.

Body:
I wonder why my conversion of the "t5" column was not successful--

The "t5" column is all characters, I want to convert it into a numeric column, leave non-numeric value as NA, named as "t5.num" in the tibble.

My code below:
first of all I assigned the name, then trying to mutate the column, but it did  not work--

d <- tibble(id = c(3, 7, 1, 10,100), t5 = c("10", "<1", "NA", "8","78"))
convert_column <- function(data, col_name) {
    new_col_name <- paste0(rlang::enquo(col_name),".num")
    data %>%
        mutate(new_col_name = as.numeric(!!col_name))
     }
d %>% convert_column("t5")

Can someone point out what is wrong with my code? thanks for your help!

Body:
To get new_col_name you don't need enquo. To assign new_col_name as name of the column use !!  + :=. As you are passing col_name as a string we need to convert it to symbol (sym) and then evaluate (!!).

library(dplyr)
library(rlang)

convert_column <- function(data, col_name) {

   new_col_name <- paste0(col_name,".num")
   data %>% mutate(!!new_col_name := as.numeric(!!sym(col_name)))
}

d %>% convert_column("t5")

# A tibble: 5 x 3
#     id t5    t5.num
#  <dbl> <chr>  <dbl>
#1     3 10        10
#2     7 <1        NA
#3     1 NA        NA
#4    10 8          8
#5   100 78        78

Returns a warning while  converting "<1" to numeric before turning it to NA.


问:
stackoverflow search api
I would like to use the search method of stackoverflow API to return the json structure of results based on a search keyword and then display those results (title, description and the url) in the SearchResults div.

I am new to C# and my first attempt went something like this:

```<code>    protected void searchStockOverflow(string y)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{ \"intitle\": \"" + y + "\"}";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            SearchResults.InnerHtml += "<div style='border:1px solid blue;margin:5px;'>";
            SearchResults.InnerHtml += responseText + "<br />";
            SearchResults.InnerHtml += "</div><br style='clear:both;' />";
        }
    }
</code>```

The issue is that what is returned looks like dingbats rubbish - i guess because it is serialized and need to be deserialized?

答: Also Take a look at Stacky StackApps .Net Client Library which is REST-based API that provides access to stackoverflow family of websites.</p>

Title: stackoverflow search api

Body:
I would like to use the search method of stackoverflow API to return the json structure of results based on a search keyword and then display those results (title, description and the url) in the SearchResults div.

I am new to C# and my first attempt went something like this:

    protected void searchStockOverflow(string y)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{ \"intitle\": \"" + y + "\"}";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            SearchResults.InnerHtml += "
";
            SearchResults.InnerHtml += responseText + "
";
            SearchResults.InnerHtml += "

";
        }
    }

The issue is that what is returned looks like dingbats rubbish - i guess because it is serialized and need to be deserialized?


问:
Replace non zero values in a single column, pandas dataframe
I have this pandas dataframe:
rls[20, 34, 21, 19]
censored[260, 0, 0, 380]
I am trying to replace non zero values in the censored column with 1s. I tried many different methods, but all of them either return the same copy of the dataframe or change both rls and censored colums which is not what I want. It feels that replace method should work, but I don't know how to specify non zero values data_rls.censored.replace([(!=0), 0], [1, 0], inplace=True)</p>

答:
Welcome to SO. Please review how to produce a reproducible example.

You can use the pd.where() function for your problem.

```<code>import pandas as pd
df = pd.DataFrame({'a':[1,3,4,0,0,4,5],'b':[1,3,4,0,0,4,5]})
df.head()

     a  b
0    1  1
1    3  3
2    4  4
3    0  0
4    0  0

df['a'] = df['a'].where(df['a'] == 0, 1)
df

    a   b
0   1   1
1   1   3
2   1   4
3   0   0
4   0   0
5   1   4
6   1   5
</code>```

Body:
Welcome to SO. Please review how to produce a reproducible example.

You can use the pd.where() function for your problem.

import pandas as pd
df = pd.DataFrame({'a':[1,3,4,0,0,4,5],'b':[1,3,4,0,0,4,5]})
df.head()

     a  b
0    1  1
1    3  3
2    4  4
3    0  0
4    0  0

df['a'] = df['a'].where(df['a'] == 0, 1)
df

    a   b
0   1   1
1   1   3
2   1   4
3   0   0
4   0   0
5   1   4
6   1   5