问:
Using timers in swift
I am a complete beginner and am starting to learn the Swift programming language. I'm following a tutorial on Udemy and am having some problems with setting up a timer.

```<code>class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var timer1 = Timer()
var counter = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    label.text = String(counter)

}
@IBAction func start(_ sender: Any) {

    timer1 = Timer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)

}

@IBAction func pause(_ sender: Any) {

    timer1.invalidate()

}

@IBAction func restart(_ sender: Any) {

    timer1.invalidate()
    counter = 0
    label.text = String(counter)

}

@objc func tim() {

    counter += 1
    label.text = String(counter)

}
</code>```

}

This is my code but the timer is not working. Please tell me where im going wrong.

答:
You need to add timer to RunLoop

```<code>RunLoop.current.add(timer1, forMode: .commonModes)
</code>```

Or use scheduledTimer

```<code>timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)
</code>```

Also in your restart function you need to do it again, because now you are just invalidating it and not starting again.

Title: Using timers in swift

Body:
I am a complete beginner and am starting to learn the Swift programming language. I'm following a tutorial on Udemy and am having some problems with setting up a timer.

class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var timer1 = Timer()
var counter = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    label.text = String(counter)

}
@IBAction func start(_ sender: Any) {

    timer1 = Timer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)

}

@IBAction func pause(_ sender: Any) {

    timer1.invalidate()

}

@IBAction func restart(_ sender: Any) {

    timer1.invalidate()
    counter = 0
    label.text = String(counter)

}

@objc func tim() {

    counter += 1
    label.text = String(counter)

}

}

This is my code but the timer is not working. Please tell me where im going wrong.

Body:
You need to add timer to RunLoop

RunLoop.current.add(timer1, forMode: .commonModes)

Or use scheduledTimer

timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)

Also in your restart function you need to do it again, because now you are just invalidating it and not starting again.


来源: stackexchange

问:
Blazor - Sharing data between components using a service
I'm new to Blazor and have been looking at a way to share an instance of a class between components in my server side Blazor App.

Most of the searching I've done so far recommends doing this through a singleton service.

I have a Database class that almost all the components will use.

I'd like to initialise it when the webapp starts up and share this new instance between all the components.

I've created an AppData class:

```<code>public class AppData
    {
        public Database Database { get; set; }
    }
</code>```

I've added the class as a singleton in Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<Data.AppData>();
        }
</code>```

At this point, is there a way to set the Database property on startup e.g AppData.Database = new Database(...) so that it's already set when the other components come to use it?

As a follow on question I've also added a property to the AppData class to serve as a kind of global variable so I can pass data from one page to another

```<code>public class AppData
    {
        public WorkflowTask Task { get; set; }
        public Database Database { get; set; }
    }
</code>```

I don't want AppData to become a dumping ground of global variables just so I can pass objects/primitives between components - have I just got the wrong end of the stick? Is there a standard way of doing this?

Many Thanks

Nick

答:
Just create a constructor for your class:</p>

```<code>public AppData()
{
    // perform any initializations here
    Database = new Database();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Blazor and have been looking at a way to share an instance of a class between components in my server side Blazor App.

Most of the searching I've done so far recommends doing this through a singleton service.

I have a Database class that almost all the components will use.

I'd like to initialise it when the webapp starts up and share this new instance between all the components.

I've created an AppData class:

public class AppData
    {
        public Database Database { get; set; }
    }

I've added the class as a singleton in Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<Data.AppData>();
        }

At this point, is there a way to set the Database property on startup e.g AppData.Database = new Database(...) so that it's already set when the other components come to use it?

As a follow on question I've also added a property to the AppData class to serve as a kind of global variable so I can pass data from one page to another

public class AppData
    {
        public WorkflowTask Task { get; set; }
        public Database Database { get; set; }
    }

I don't want AppData to become a dumping ground of global variables just so I can pass objects/primitives between components - have I just got the wrong end of the stick? Is there a standard way of doing this?

Many Thanks

Nick

Body:
Just create a constructor for your class:

public AppData()
{
    // perform any initializations here
    Database = new Database();
}


问:
Sign extension from 16 to 32 bits in C
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

```<code>int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}
</code>```

The instruction (instr) is 32 bits and inside it I have a 16bit number.

答:
Why is wrong with:</p>

```<code>int16_t s = -890;
int32_t i = s;  //this does the job, doesn't it?
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sign extension from 16 to 32 bits in C

Body:
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}

The instruction (instr) is 32 bits and inside it I have a 16bit number.

Body:
Why is wrong with:

int16_t s = -890;
int32_t i = s;  //this does the job, doesn't it?


问:
How to handle NuGet dependency version resolution for the whole solution
I'm looking for a simple way to manage NuGet packages for the whole solution, to prevent conflicts between transitive NuGet packages when assembling all files into one installer.

When building a project all direct and indirect dependencies are analyzed and the NuGet resolution picks up the best matching version for each NuGet that is at least the same version as the lowest version and might also create binding redirects if necessary. (all good and fine)

The problem we have lately encountered was when we build the whole solution (200+ projects) at once, the resulting NuGet versions between all top level projects might not be identical. And due to the fact, that all resulting DLL and EXE files are installed into the same program files folder, the application can and will crash at runtime due to version mismatches when loading assemblies.

To better understand this issue I've created this sample repo.

The dependency graph looks like this:

Library1

Microsoft.IdentityModel.Tokens-5.2.1

Executable1

System.IdentityModel.Tokens.Jwt-5.3.0 (transitive reference: Microsoft.IdentityModel.Tokens-5.3.0)

Library1

results in: Microsoft.IdentityModel.Tokens-5.3.0

Executable2

Microsoft.IdentityModel.Tokens-5.2.1

results in: Microsoft.IdentityModel.Tokens-5.2.1

To demonstrate the problem, all projects compile to the same bin folder. When the whole solution is compiled and Executable2 is started, the application crashes, since the application expects Microsoft.IdentityModel.Tokens in version 5.2.1 but the actual version is 5.3.0.

For this constructed sample it is easy to find the problem and fix it with updating the Microsoft.IdentityModel.Tokens NuGet to the same version. (Manually, since Visual Studio Package Manager does not recognize this conflict in the consolidate tab).

But at a much greater scale it is far more complex to find those mismatches.

What we have found so far

Centrally managing NuGet package versions

Since it is not yet available, it cannot be used to solve the issue here.

Microsoft.Build.CentralPackageVersions

Unfortunately there is no IDE support for it, which makes managing NuGet packages very uncomfortable, which I would like to avoid if possible.

So my question is what is the best approach to avoid NuGet version conflicts between projects within the same solution?

答:
We've experienced the same problem with some of our projects. We've been using Paket package manager since a couple of years and this has resolved that issue for us.

In short: you define on your solution level which packages you want to use in a file called 'paket.dependencies'. You can be very specific about versions, or let packet use the latest greatest. Then you can specify per project which NuGet package you want to use within that project in a 'paket.references' file. As the name implies, you reference to a package in the paket.dependencies file.

This will make sure, all references packages in your project will use the same package version. I hope this suits your needs as well.


问:
geom_line with x-axis in order of appearance
this is the first question I post here, so please excuse if I don't provide all information right away.

I'm trying to build a line graph with two lines:

```<code>y1 <- c(1000,1500,1000,1500,2000,3000,4000)

y2 <- c(1100,1400,900,1500,2000,2500,3500)

x <- c(49,50,51,1,2,49,50)

df <- data.frame(y1,y2,x)
</code>```

Imagine x being calendar weeks, I skipped the weeks between 3 and 48 of the second year.
Now I want to build a line graph, which display the x-axis values (time series) in this order.

First I tried a really simple approach:

```<code>p <- ggplot()

p <- p + geom_line(data=df,aes(x=x,y=y1))

p <- p + geom_line(data=df,aes(x=x,y=y2), color = "red")

p
</code>```

Problem: R sorts the x values and also sums up same week numbers.

I then tried to change the x values to make them unique, e.g. 49/19,50/19, but R still changes the order. Same happens if I use geom_path instead of geom_line.

I then tried to change x to a factor and use x_scale_discrete, but I couldn't figure out, how to do it, either the lines or the x labels were always missing.

I hope you can give me some kind of advice.

Many thanks,

Andre

答:
One approach is to replace x with a sequence of integers and then apply the x-axis labels afterwards.

```<code>library(ggplot2)
ggplot(data = df, aes(x = seq(1,nrow(df)))) +
  geom_line(aes(y=y1)) +
  geom_line(aes(y=y2), color = "red") +
  scale_x_continuous(breaks = seq(1,nrow(df)),
                     labels = as.character(df$x)) +
  labs(x = "Week")
</code>```

Body:
this is the first question I post here, so please excuse if I don't provide all information right away.

I'm trying to build a line graph with two lines:

y1 <- c(1000,1500,1000,1500,2000,3000,4000)

y2 <- c(1100,1400,900,1500,2000,2500,3500)

x <- c(49,50,51,1,2,49,50)

df <- data.frame(y1,y2,x)

Imagine x being calendar weeks, I skipped the weeks between 3 and 48 of the second year.
Now I want to build a line graph, which display the x-axis values (time series) in this order.

First I tried a really simple approach:

p <- ggplot()

p <- p + geom_line(data=df,aes(x=x,y=y1))

p <- p + geom_line(data=df,aes(x=x,y=y2), color = "red")

p

Problem: R sorts the x values and also sums up same week numbers.

I then tried to change the x values to make them unique, e.g. 49/19,50/19, but R still changes the order. Same happens if I use geom_path instead of geom_line.

I then tried to change x to a factor and use x_scale_discrete, but I couldn't figure out, how to do it, either the lines or the x labels were always missing.

I hope you can give me some kind of advice.

Many thanks,

Andre

Body:
One approach is to replace x with a sequence of integers and then apply the x-axis labels afterwards.

library(ggplot2)
ggplot(data = df, aes(x = seq(1,nrow(df)))) +
  geom_line(aes(y=y1)) +
  geom_line(aes(y=y2), color = "red") +
  scale_x_continuous(breaks = seq(1,nrow(df)),
                     labels = as.character(df$x)) +
  labs(x = "Week")


问:
typescript creating a method that takes any derived subclass instance as parameter
Based on the typescript docs https://www.typescriptlang.org/docs/handbook/classes.html, here's an example of simple inheritance:

```<code>abstract class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
    hello() {
        console.log(`hello`)
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}
</code>```

Let's say Animal is abstract, so it shouldn't be instantiated. How can one create a function that agnostically takes an instance of any of Animal's subclasses?

Something like

```<code>function printHello(subclass: //any subclass of Animal) {
    // whatever
}
</code>```

答:
How can one create a function that agnostically takes an instance of any of Animal's subclasses?

It can just accept Animal, since subclasses can be used as arguments for superclass parameters:

```<code>function printHello(subclass: Animal) {
    // whatever
}
</code>```

Playground link

Since Animal is abstract, you know the instance you're passed will be a subtype.

Body:
Based on the typescript docs https://www.typescriptlang.org/docs/handbook/classes.html, here's an example of simple inheritance:

abstract class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
    hello() {
        console.log(`hello`)
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}

Let's say Animal is abstract, so it shouldn't be instantiated. How can one create a function that agnostically takes an instance of any of Animal's subclasses?

Something like

function printHello(subclass: //any subclass of Animal) {
    // whatever
}

Body:
How can one create a function that agnostically takes an instance of any of Animal's subclasses?

It can just accept Animal, since subclasses can be used as arguments for superclass parameters:

function printHello(subclass: Animal) {
    // whatever
}

<a href="https://www.typescriptlang.org/play/index.html#code/IYIwzgLgTsDGEAJYBthjAgggOwJYFthkEBvAWACgFqFth8BTALgUil2wHMBuSmpAPbY2AV3gCoACggALBgDl6zVtA6cAlKQSzcYAHR1GCALza5ixtwQBfPjXwCAbg0kATXRGDZYDAJLYAWQYIBigwFmwRfBBQkwQABk1yKn4aWCEwAWQGPWQBTkkAAwASEh19QwZrBAdnVwRS90gvH38gkLDrfD1C9V4U6lsBhDlkPMkku1TBYSycvILC0bzeqZtKIcoUNAwAZToAawYEBgAPEOxXDBwCIlI19OFoMQgJSUqWNjUk1hEAB1C7yUfXWw1qLianm8fkCwVCGFMAFZJsN+I9MtlcvlJAAiXbIXCyUJqPSknF9Nb8MD-UJ6cFuDwtGHteEU4ZDTYUbboBAACQkYGOZwuVyweEIxGSaIyz3EUg+KnYXB+1IB8uBViG-HpkKZbThYTiABZkfdUWkMnMsQUcQBxIh5P4ksls6bUVW0nWM6H6jpgV00DmUSgAMxE3gguCECD+SogvIYYwEkmpIG54TFt2QKOls0xCxTIjTqHQBg1G2DFFjHHjifG2AYAHcEPtgEdcbt0GBDgxyX0gA" rel="nofollow noreferrer">Playground link

Since Animal is abstract, you know the instance you're passed will be a subtype.


问:
C#: Using a set of overridden functions in a generic one
What I want to do is the following:

Have several classes, one of which is a base one for the rest. All those classes are not self-made.

Have a function overridden for each of the classes including the base one.

Have a single generic function that uses the set of overridden functions. The generic function constrains its type parameter to be based on the base class.

Here's the code:

```<code>public class Program
{
    class Base
    {
    }

    class A : Base
    {
    }

    class B : Base
    {
    }

    private static int Id(Base obj)
    {
        return 0;
    }

    private static int Id(A obj)
    {
        return 1;
    }

    private static int Id(B obj)
    {
        return 2;
    }

    private static int GetId<T>(T obj) where T : Base
    {
        return Id(obj);
    }

    public static void Main(string[] args)
    {
        int idBase = GetId(new Base());
        int idA = GetId(new A());
        int idB = GetId(new B());
        // expected    | idBase=0, idA=1, idB=2
        // but getting | idBase=0, idA=0, idB=0
        Console.WriteLine($"idBase={idBase}, idA={idA}, idB={idB}");
    }
}
</code>```

Since C# doesn't support explicit specialization I cannot use a template function and specialize it for each of the instances, but probably it is needless to use such since a set of overridden such would do even better work. Yet, the correct overrides are not called but only the one for the base class. Even the IDE is giving me hints that the rest are not used. Tell me what I am missing.

答:
You can do this by using a generic type object, from there you can obtain the underlying type using the is keyword:

```<code>public class Program
{
    class Base
    {
    }

    class A : Base
    {
    }

    class B : Base
    {
    }

    private static int Id(object obj)
    {
        if (obj is A) return 1;
        if (obj is B) return 2;
        return 0;
    }

    private static int GetId<T>(T obj) where T : Base
    {
        return Id(obj);
    }

    public static void Main(string[] args)
    {
        int idBase = GetId(new Base());
        int idA = GetId(new A());
        int idB = GetId(new B());
        Console.WriteLine($"idBase={idBase}, idA={idA}, idB={idB}");
    }
}
</code>```

Body:
What I want to do is the following:

Have several classes, one of which is a base one for the rest. All those classes are not self-made.

Have a function overridden for each of the classes including the base one.

Have a single generic function that uses the set of overridden functions. The generic function constrains its type parameter to be based on the base class.

Here's the code:

public class Program
{
    class Base
    {
    }

    class A : Base
    {
    }

    class B : Base
    {
    }

    private static int Id(Base obj)
    {
        return 0;
    }

    private static int Id(A obj)
    {
        return 1;
    }

    private static int Id(B obj)
    {
        return 2;
    }

    private static int GetId<T>(T obj) where T : Base
    {
        return Id(obj);
    }

    public static void Main(string[] args)
    {
        int idBase = GetId(new Base());
        int idA = GetId(new A());
        int idB = GetId(new B());
        // expected    | idBase=0, idA=1, idB=2
        // but getting | idBase=0, idA=0, idB=0
        Console.WriteLine($"idBase={idBase}, idA={idA}, idB={idB}");
    }
}

Since C# doesn't support explicit specialization I cannot use a template function and specialize it for each of the instances, but probably it is needless to use such since a set of overridden such would do even better work. Yet, the correct overrides are not called but only the one for the base class. Even the IDE is giving me hints that the rest are not used. Tell me what I am missing.

Body:
You can do this by using a generic type object, from there you can obtain the underlying type using the is keyword:

public class Program
{
    class Base
    {
    }

    class A : Base
    {
    }

    class B : Base
    {
    }

    private static int Id(object obj)
    {
        if (obj is A) return 1;
        if (obj is B) return 2;
        return 0;
    }

    private static int GetId<T>(T obj) where T : Base
    {
        return Id(obj);
    }

    public static void Main(string[] args)
    {
        int idBase = GetId(new Base());
        int idA = GetId(new A());
        int idB = GetId(new B());
        Console.WriteLine($"idBase={idBase}, idA={idA}, idB={idB}");
    }
}


问:
checkboxes in php - problem with access
i need to reproduce with the code below something like:

```<code>myformdata[languages1]
myformdata[languages2]
myformdata[languages3]
</code>```

But with this code only reproduce myformdata[languages

```<code>    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n");
    }
    ?>
</code>```

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?

答:
```<code>    $i++;
echo nl2br ("<input type='checkbox' name='myformdata[languages$i]' value='$id' class='semLargura'>$data <img style='float:right; margin-top:5px; border:1px solid grey;' src='$flag'></img> \n")
</code>```

Title: checkboxes in php - problem with access

Body:
i need to reproduce with the code below something like:

myformdata[languages1]
myformdata[languages2]
myformdata[languages3]

But with this code only reproduce myformdata[languages

    <?php
    $sql=mysql_query("select id_spoken_languages, language, path from spoken_languages");
    $i=0;
    while($row=mysql_fetch_array($sql)) {
    $id=$row['id_spoken_languages'];
    $data=$row['language'];
    $flag=$row['path'];
    echo nl2br ("<input type='checkbox' name='myformdata[languages'.$i++.']' value='$id' class='semLargura'>$data  \n");
    }
    ?>

i already tried remove the increment and only access with $form_data_array["languages"][1] but in this case i get:

Notice:  Uninitialized string offset: 1 in C:\Users\fel\VertrigoServ\www\login\validation2.php on line 9

but if i use `$form_data_array["languages"][0], no error is showed, seems like all checkbox have the
index 0.

what is the best way to solve this problem?


问:
DNN Persona bar, error 500 on API/personaBar/localization/gettable?culture=en-US
After logging in DNN (v. 09.01.01 (129)) thru the /login interface,

The site makes space for the DNN bar, but the DNN bar does not actually appear.

After which in console we see this particular error

/API/personaBar/localization/gettable?culture=en-US:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)

We have tried all the suggestions in DNN's forums here,
But none seem to work (deleting the LocalResources.en-US file, checking Permissions..)

How ca nwe diagnose the actual issue, and how do we restore the persona Bar?

答:
Two ways to try to get additional details about the error. First try recreating it then connect to your SQL server to run a query or two.

You can try to query the EventLog table to try to find the specific error. From that table row, you'll need to grab the ExceptionHash value and then query the Exceptions table to try to get details.

```<code>select top 5 * from eventlog
where exceptionhash is not null
order by logcreatedate desc

select * from exceptions where exceptionhash = '###'
</code>```

(replace ### with the hash found in the first results)

From the exceptions table you'll want to look at the Message and StackTrace columns for any details that might point you in the direction of what the actual issue is.

You'll also likely find that upgrading to the most recent release may fix your problems.

Body:
Two ways to try to get additional details about the error. First try recreating it then connect to your SQL server to run a query or two.

You can try to query the EventLog table to try to find the specific error. From that table row, you'll need to grab the ExceptionHash value and then query the Exceptions table to try to get details.

select top 5 * from eventlog
where exceptionhash is not null
order by logcreatedate desc

select * from exceptions where exceptionhash = '###'

(replace ### with the hash found in the first results)

From the exceptions table you'll want to look at the Message and StackTrace columns for any details that might point you in the direction of what the actual issue is.

You'll also likely find that upgrading to the most recent release may fix your problems.


问:
Unable to join two tables with django rest framework
I am trying to join two tables and serialize them as an API. I have referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after trying so many times. I am trying to get a JSON file like

```<code>{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
    {'order': 1, 'title': 'Public Service Announcement'},
    {'order': 2, 'title': 'What More Can I Say'},
    {'order': 3, 'title': 'Encore'},
    ...
  ],
}
</code>```

But what I get is

```<code>{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
}
</code>```

This is the model file I am using

Model.py

```<code>from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICE = (
    ('simple', 'simple'),
    ('intermediate', 'intermediate'),
)

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=1000)
    video_id = models.ForeignKey("youtube.Youtube",  on_delete=models.CASCADE)
    questions_count = models.IntegerField(default=0)
    description = models.CharField(max_length=70, null=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()
    pass_mark = models.IntegerField()
    class Meta:
        ordering = ['created']
    def __str__(self):
        return self.quiz_name

class Category(models.Model):
    category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple')
    quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    def __str__(self):
        return self.category

class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()
    def __str__(self):
        return self.question

class Choice(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    choice_1 = models.CharField(max_length=1000)
    choice_2 = models.CharField(max_length=1000)
    choice_3 = models.CharField(max_length=1000)
    choice_4 = models.CharField(max_length=1000)
    answer = models.CharField(max_length=1000, default=choice_1)

    def __str__(self):
        return self.answer
</code>```

Serializer.py

```<code>from rest_framework import  serializers
from rest_framework.permissions import IsAuthenticated
from .models import Category, Quiz, Questions, Choice
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class QuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quiz
        fields = '__all__'

class QuestionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = '__all__'

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    quiz_name =  QuizSerializer(read_only=True)
    class Meta:
        model = Category
        fields = ['id','category','quiz_name']
</code>```

View.py

```<code>from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import CategorySerializer
from .models import Category

class ViewQuiz(generics.ListCreateAPIView):
    permission_classes = [
        permissions.AllowAny,
    ]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    def list(self, request):
        queryset = self.get_queryset()
        serializer = CategorySerializer(queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)
</code>```

答:
```<code>class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ['id','category','quiz_id']

    def to_representation(self, instance):
       response = super().to_representation(instance)
       response['quiz_id'] = QuizSerializer(instance.quiz_id).data
       return response
</code>```

This will produce the result you want, I made an change in how the serializer represent the data. I have some of my serializer doing the same, but my views are working a bit different from yours.

Body:
I am trying to join two tables and serialize them as an API. I have referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after trying so many times. I am trying to get a JSON file like

{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
    {'order': 1, 'title': 'Public Service Announcement'},
    {'order': 2, 'title': 'What More Can I Say'},
    {'order': 3, 'title': 'Encore'},
    ...
  ],
}

But what I get is

{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
}

This is the model file I am using

Model.py

from django.db import models
from django.contrib.auth.models import User

STATUS_CHOICE = (
    ('simple', 'simple'),
    ('intermediate', 'intermediate'),
)

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=1000)
    video_id = models.ForeignKey("youtube.Youtube",  on_delete=models.CASCADE)
    questions_count = models.IntegerField(default=0)
    description = models.CharField(max_length=70, null=True)
    created = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()
    pass_mark = models.IntegerField()
    class Meta:
        ordering = ['created']
    def __str__(self):
        return self.quiz_name

class Category(models.Model):
    category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple')
    quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    def __str__(self):
        return self.category

class Questions(models.Model):
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
    question = models.CharField(max_length=1000)
    mark = models.IntegerField()
    def __str__(self):
        return self.question

class Choice(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    choice_1 = models.CharField(max_length=1000)
    choice_2 = models.CharField(max_length=1000)
    choice_3 = models.CharField(max_length=1000)
    choice_4 = models.CharField(max_length=1000)
    answer = models.CharField(max_length=1000, default=choice_1)

    def __str__(self):
        return self.answer

Serializer.py

from rest_framework import  serializers
from rest_framework.permissions import IsAuthenticated
from .models import Category, Quiz, Questions, Choice
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password

class QuizSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quiz
        fields = '__all__'

class QuestionsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = '__all__'

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    quiz_name =  QuizSerializer(read_only=True)
    class Meta:
        model = Category
        fields = ['id','category','quiz_name']

View.py

from rest_framework import generics, permissions, mixins
from rest_framework.response import Response
from .serializer import CategorySerializer
from .models import Category

class ViewQuiz(generics.ListCreateAPIView):
    permission_classes = [
        permissions.AllowAny,
    ]
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    def list(self, request):
        queryset = self.get_queryset()
        serializer = CategorySerializer(queryset, many=True)
        print(serializer.data)
        return Response(serializer.data)

Body:
class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ['id','category','quiz_id']

    def to_representation(self, instance):
       response = super().to_representation(instance)
       response['quiz_id'] = QuizSerializer(instance.quiz_id).data
       return response

This will produce the result you want, I made an change in how the serializer represent the data. I have some of my serializer doing the same, but my views are working a bit different from yours.


问:
How can I set a custom name for the EF core migration history table and have it used when generating migration scripts?
I have an ASP.NET Core project which uses EF Core, and migrations have already been run using the default migration history table (dbo.__EFMigrationsHistory). I want to store all migrations in a table with a different name and schema.

In ConfigureServices (within Startup.cs) I have the following code (as per the documentation):

serviceCollection.AddDbContext<DatabaseContext>(
    options =>
    {
        options.UseSqlServer(
            connectionString,
            x => x.MigrationsHistoryTable("__MigrationHistory", "MySchema"));
    });
```

I have manually created the MySchema.__MigrationHistory table, copied over all the data from dbo.__EFMigrationsHistory, and dropped dbo.__EFMigrationsHistory.

I was expecting this to mean that all future migrations would go into MySchema.__MigrationHistory but when I added a blank migration as a test and ran script-migration -from previousMigrationName (from the Visual Studio package manager console) the SQL it gave me adds the history record to dbo.__EFMigrationsHistory.

What else do I need to do in order to get EF Core to use MySchema.__MigrationHistory for all new migrations?

答:
It turns out that the reason for this problem was that I hadn't understood how EF Core is configured to run migrations when the DbContext is in a different assembly from the ASP.NET Core app.

The ASP.NET Core app has a Startup.cs which I'd modified, but I wasn't aware that the assembly containing the DbContext contained an implementation of IDesignTimeDbContextFactory. In this class there is another call to the UseSqlServer method, and I needed to add the options there too. This is what is actually being used for migrations, as they don't go through the ASP.NET Core app.

Body:
I have an ASP.NET Core project which uses EF Core, and migrations have already been run using the default migration history table (dbo.__EFMigrationsHistory). I want to store all migrations in a table with a different name and schema.

In ConfigureServices (within Startup.cs) I have the following code (as per the documentation):

serviceCollection.AddDbContext<DatabaseContext>(
    options =>
    {
        options.UseSqlServer(
            connectionString,
            x => x.MigrationsHistoryTable("__MigrationHistory", "MySchema"));
    });

I have manually created the MySchema.__MigrationHistory table, copied over all the data from dbo.__EFMigrationsHistory, and dropped dbo.__EFMigrationsHistory.

I was expecting this to mean that all future migrations would go into MySchema.__MigrationHistory but when I added a blank migration as a test and ran script-migration -from previousMigrationName (from the Visual Studio package manager console) the SQL it gave me adds the history record to dbo.__EFMigrationsHistory.

What else do I need to do in order to get EF Core to use MySchema.__MigrationHistory for all new migrations?


问:
Is it possible to install the latests Firebase Crashlytics iOS SDK manually?
I am trying to migrate Crashlytics from Fabric to Firebase and in the documentation Upgrade to the Firebase Crashlytics SDK there is only a description for Cocoapods. I am not using Cocoapods in my project and don't want to, but I haven't found any alternative for installing the Firebase Crashlytics SDK. Does anyone has the same issue and found already a solution?

I have found this post from Saravana How to add Firebase Crashlytics to iOS app, but it is over one year old, so the SDK offered there is probably not the latest one.

This is my first question, please be kind :) And thanks a lot in advance!

答: So, after further research, there is a documentation for the installation without Cocoapods: Add Firebase to your iOS project.</p>


问:
Submiting a form that is inside a div with AJAX
I'm trying to submit a form using AJAX to stop the browser from refreshing the page.
The form is located inside a secondary page, that is called into the main page div ( similar to using a master page and the content placeholder ).

I have been trying several methods but I always reach the same problem. Whenever I try to submit the form, the response is the secondary page with the form, and I can't place the awnser inside the content div of the mainpage like intended.

Any tips on how to make this work?

```<code>    Main Page

    <div id="content"> Secondary page content goes in here loaded using AJAX</div>

    Secondary Page

    <form runat="server" id="formuser">
            <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
            <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
            <a href="#" onclick="document.formuser.submit()"> Submit Form </a>
    </form>
</code>```

What I intend to do is Submit the above form, while staying in the Main Page and showing the response in the content div.
I need the form to be runat="server" so I can manipulate the data using the code-behind.

答: It seems that the method I was using for the content load was building a xmlHttpRquest and it was conflicting with the response that I got from the jquery.</p>

Body:
I'm trying to submit a form using AJAX to stop the browser from refreshing the page.
The form is located inside a secondary page, that is called into the main page div ( similar to using a master page and the content placeholder ).

I have been trying several methods but I always reach the same problem. Whenever I try to submit the form, the response is the secondary page with the form, and I can't place the awnser inside the content div of the mainpage like intended.

Any tips on how to make this work?

    Main Page

 Secondary page content goes in here loaded using AJAX

    Secondary Page

    <form runat="server" id="formuser">
            <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
            <asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
             Submit Form
    </form>

What I intend to do is Submit the above form, while staying in the Main Page and showing the response in the content div.
I need the form to be runat="server" so I can manipulate the data using the code-behind.


问:
TypeScript use noImplicitAny with Javascript sources
I want to enable the noImplicitAny flag in my compiler.
My problem is that I use lodash/fp and there is no typings so far.

So the compiler complains about the lack of definition file for lodash/fp.

Is there a way to allow implicit any only for external js files ? Or to whitelist a subdirectory like node_modules ?

答:
You can create a declaration file with ".d.ts" extension like ambient-modules.d.ts

Add the following line in this file

```<code>declare module '*';
</code>```

And you're done!

Now, you still get the benefits of noImplicitAny flag without worrying about the other js files which don't have any types available.

For more info, you can refer here

Body:
You can create a declaration file with ".d.ts" extension like ambient-modules.d.ts

Add the following line in this file

declare module '*';

And you're done!

Now, you still get the benefits of noImplicitAny flag without worrying about the other js files which don't have any types available.

For more info, you can refer here


问:
How to avoid Sass variable name repeat in _variables.scss?
I have _variables.scss which is structured like this following BEM naming conventions.

```<code>$slot-width: 100px;
$slot-height: 10px;
$slot-title-width: 80px;
$slot-title-height: 10px;
</code>```

I'm repeating variable names $slot-. Is there a way to do something like:

```<code>$slot {
  &-width: 100px;
  &-height: 10px;
  &-title {
    &-width: 80px;
    &-height: 10px;
  }
}
</code>```

And it compiles to the above?

答:
You could use a map :</p>

```<code>$slot: (
    "width": 100px,
    "height": 10px
);

.some_bem__selector { width: map-get($slot, width); }
</code>```

Body:
I have _variables.scss which is structured like this following BEM naming conventions.

$slot-width: 100px;
$slot-height: 10px;
$slot-title-width: 80px;
$slot-title-height: 10px;

I'm repeating variable names $slot-. Is there a way to do something like:

$slot {
  &-width: 100px;
  &-height: 10px;
  &-title {
    &-width: 80px;
    &-height: 10px;
  }
}

And it compiles to the above?

Body:
You could use a map :

$slot: (
    "width": 100px,
    "height": 10px
);

.some_bem__selector { width: map-get($slot, width); }


问:
Fail to update Firebase security rules
I have a database and got an email that my rules are not secure.
this is what i have now:

```<code>{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
</code>```

i wanted to change it to something like in the example in the site, so a user can read\write only to his record, but this doesn't work. i get denied.

what am i doing wrong?

how do i know if my key is $uid or $user_id?

the database structure is like:

```<code>root
  --uid
    -- all the data
</code>```

Rules:

```<code>{
  "rules": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }

  }
}
</code>```

sample of my data:

答:
These rules that you use in the playground screenshot:

```<code>{
  "rules": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }

  }
}
</code>```

In these rules the $uid is a variable, meaning that the rules under that node apply to any top-level node. These rules then you allow the user to read/write their own data, when the path ($uid) matches their own UID.

But in the same playground screenshow you're trying to read /uid, in which case uid is just a hard-coded value. Since the auth.uid is not the actual UID of your user, the read/write is denied.

With the user that you've set up in the playground screenshot, you can read/write location /c252019c-c9c3-461e-bb79-e8a346862f08 (the UID of the user).

Title: Fail to update Firebase security rules

Body:
I have a database and got an email that my rules are not secure.
this is what i have now:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

i wanted to change it to something like in the example in the site, so a user can read\write only to his record, but this doesn't work. i get denied.

what am i doing wrong?

how do i know if my key is $uid or $user_id?

the database structure is like:

root
  --uid
    -- all the data

Rules:

{
  "rules": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }

  }
}

sample of my data:

Body:
These rules that you use in the playground screenshot:

{
  "rules": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }

  }
}

In these rules the $uid is a variable, meaning that the rules under that node apply to any top-level node. These rules then you allow the user to read/write their own data, when the path ($uid) matches their own UID.

But in the same playground screenshow you're trying to read /uid, in which case uid is just a hard-coded value. Since the auth.uid is not the actual UID of your user, the read/write is denied.

With the user that you've set up in the playground screenshot, you can read/write location /c252019c-c9c3-461e-bb79-e8a346862f08 (the UID of the user).


问:
How do you add a compound / composite index on a PostgreSQL table with TimescaleDB installed?
How do you add a compound / composite index on a PostgreSQL table with TimescaleDB installed?</p>

答:
Following https://docs.timescale.com/latest/using-timescaledb/schema-management, you can add a compound / composite index to TimescaleDB by simply doing:

CREATE INDEX ON conditions (time DESC, cityid)
WHERE cityid IS NOT NULL;
```

time is a column with timestamps (The one used as primary key in TimescaleDB).
cityid is a column for a city identifier we might to often query for (As second parameter after the time series dates).

This can be done before or after converting the table to a hypertable.

To avoid bloating the index when the column cityid is often NULL, the statement WHERE cityid IS NOT NULL is for. Use this per default unless you are often searching for missing data (cityid IS NULL).

Body:
Following https://docs.timescale.com/latest/using-timescaledb/schema-management, you can add a compound / composite index to TimescaleDB by simply doing:

CREATE INDEX ON conditions (time DESC, cityid)
WHERE cityid IS NOT NULL;

time is a column with timestamps (The one used as primary key in TimescaleDB).
cityid is a column for a city identifier we might to often query for (As second parameter after the time series dates).

This can be done before or after converting the table to a hypertable.

To avoid bloating the index when the column cityid is often NULL, the statement WHERE cityid IS NOT NULL is for. Use this per default unless you are often searching for missing data (cityid IS NULL).


问:
Javascript get largest object in array of objects
I want to get the largest object in an array of objects, the code I'm using works fine, but I wonder if there is a better way of doing the same. This is the code I'm using.

data=[
    {group: "a", A: 65, N: 20},
    {group: "b", R: 52},
    {group: "c", N: 20, A: 2, R: 2},
    {group: "d", R: 15, N: 12},
]

len = []
for (var i in data){
    len.push(Object.keys(data[i]).length)
}

for (var i in data){
    if (Object.keys(data[i]).length==Math.max.apply(null, len)){
      subgroups = Object.keys(data[i]).slice(1).sort();
    }
}

console.log(subgroups);```

答:
You can just sort the array using the criteria you used for filling the len array.

```<code>data.sort((x, y) => {
  return Object.keys(y).length - Object.keys(x).length
});
</code>```

Result:

```<code>0: {group: "c", N: 20, A: 2, R: 2}
1: {group: "a", A: 65, N: 20}
2: {group: "d", R: 15, N: 12}
3: {group: "b", R: 52}
</code>```

Body:
You can just sort the array using the criteria you used for filling the len array.

data.sort((x, y) => {
  return Object.keys(y).length - Object.keys(x).length
});

Result:

0: {group: "c", N: 20, A: 2, R: 2}
1: {group: "a", A: 65, N: 20}
2: {group: "d", R: 15, N: 12}
3: {group: "b", R: 52}


问:
What is the point of making a test for Pageable?
I should write a test with Mockito for this method:

```<code>public Optional<Page<User>> getAllByPage(Integer pageSize, Integer page) {
    Pageable pageable = PageRequest.of(page, pageSize);
    return userRepository.findAll(pageable);
}
</code>```

I cannot understand for the longest time, what should be the test? What is the point of testing a Pageable, this method returns all users, so I should maybe just check if the method returns all users? Am I making a mistake somewhere in the logic?

答:
You should only unit test code that you implement. Since in that method that is almost none, I wouldn't unit test it. But I would make sure that Integration and System testing covered that method in all possible iterations to increase my trust on it.

Also, imagine that you provide a wrong page size or page number? what would happen? Can you know without testing it?

Body:
I should write a test with Mockito for this method:

public Optional<Page<User>> getAllByPage(Integer pageSize, Integer page) {
    Pageable pageable = PageRequest.of(page, pageSize);
    return userRepository.findAll(pageable);
}

I cannot understand for the longest time, what should be the test? What is the point of testing a Pageable, this method returns all users, so I should maybe just check if the method returns all users? Am I making a mistake somewhere in the logic?


问:
How to extract a substring from a string in a column, that matches another string in a list in python
I have a dataframe which is as follows:

```<code>     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP
</code>```

With a list similar to:

```<code>[Stevenage, Essex, Coventry, Chester]
</code>```

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

```<code>city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')
</code>```

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

```<code>     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry
</code>```

I have tried:

```<code>pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))
</code>```

But this returned an error saying 456 inputs when expecting 1.

Also:

```<code>df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)
</code>```

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

答:
Thanks for your last replied, try this</p>

```<code>def aux_func(address):
    aux_list = ['Stevenage', 'Essex', 'Coventry', 'Chester']

    # remove commas
    address = address.split(',')

    # avoide matches with the first part of the address
    if len(address)>1:
        # remove the first element of the address
        address = address[1:]

    for v in aux_list:
        for chunk in address:
            if v in chunk:
                return v

    return ""

df['col 3'] = [aux_func(address) for address in df['col 2']]
</code>```

Body:
I have a dataframe which is as follows:

     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP

With a list similar to:

[Stevenage, Essex, Coventry, Chester]

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry

I have tried:

pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))

But this returned an error saying 456 inputs when expecting 1.

Also:

df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

Body:
Thanks for your last replied, try this

def aux_func(address):
    aux_list = ['Stevenage', 'Essex', 'Coventry', 'Chester']

    # remove commas
    address = address.split(',')

    # avoide matches with the first part of the address
    if len(address)>1:
        # remove the first element of the address
        address = address[1:]

    for v in aux_list:
        for chunk in address:
            if v in chunk:
                return v

    return ""

df['col 3'] = [aux_func(address) for address in df['col 2']]


问:
Package android. support.v4.content does not exist
I am getting this error please help
It error become when i convert ionic to apk in android studio.
I have tried a lot but cant solve still.</p>

答:
This was my problem too. this is caused because of Google servers is blocking you. follow these steps:

use a VPN (crucial)

run your CMD and navigate to project root (only CMD)

run ionic cordova build android

inform me of the result. Good Luck!


问:
PL/SQL not functioning
Im currently trying to implement a row trigger that fires when the new Employee number inserted into the table is not continuous.

"Continuous" in a relationship to the Employee number means the first record inserted will have the Employee number 1, the second record will have the employee number 2, and each next position must have a number greater by one that a number of the previous position.

I have successfully created the trigger,  however when I inserted a new record that have an Employee number that is not continuous, my trigger is not fired.

Im unsure where I went wrong and hope I can get some explanation and corrections on my code.

```<code>CREATE OR REPLACE TRIGGER CONTENUM

AFTER INSERT ON TRKEMPLOYEE
FOR EACH ROW

DECLARE
continuous_value EXCEPTION;
PRAGMA exception_init(continuous_value, -20111);

PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN

IF (:NEW.E# > :OLD.E# + 1) THEN
    RAISE_APPLICATION_ERROR (-20111,'The value of  Employee number must be continuous');

END IF;

END CONTENUM;
/
</code>```

Here is the format of my sample TRKEMPLOYEE table

```<code> CREATE TABLE TRKEMPLOYEE(
    E#              NUMBER(12)      NOT NULL,
    NAME            VARCHAR(50)     NOT NULL,
    DOB             DATE                    ,
    ADDRESS         VARCHAR(300)    NOT NULL,
    HIREDATE        DATE            NOT NULL,
    CONSTRAINT TRKEMPLOYEE_PKEY PRIMARY KEY(E#) );
</code>```

Here is my insert statement.
Currently in my table TRKEMPLOYEE there is only 15 rows thus with my insert statement, the trigger should fire but it is not happening.

```<code>INSERT INTO TRKEMPLOYEE VALUES( 17, 'David', NULL, 'GB',sysdate );
</code>```

Thank you.

答:
First of all you are checking AFTER INSERT ON TRKEMPLOYEE which will be executed after the row is inserted.

Secondly, you cannot check :OLD.E# since you are not updating and you are not using a old value.

Also you should drop the trigger at all and use SEQUENCES and let Oracle take care of the auto-increment values every time you add a new employee.

If you want to continue with your current logic, fixes that can be applied:

Change AFTER INSERT ON TRKEMPLOYEE to BEFORE INSERT ON TRKEMPLOYEE

Logic should be changed as below:

```<code>CREATE OR REPLACE TRIGGER contenum BEFORE
    INSERT ON trkemployee
    FOR EACH ROW
DECLARE
    continuous_value EXCEPTION;
    PRAGMA exception_init ( continuous_value, -20111 );
    PRAGMA autonomous_transaction;
    max_e# INTEGER;
BEGIN
    SELECT
        nvl(MAX(e#), 0)
    INTO max_e#
    FROM
        trkemployee;

    IF ( :new.e# > max_e# + 1 ) THEN
        raise_application_error(-20111, 'The value of  Employee number must be continuous');
    END IF;
END contenum;
/
</code>```

I do not recommend this solution because it will start to become slower as your table starts to grow.

Title: PL/SQL not functioning

Body:
Im currently trying to implement a row trigger that fires when the new Employee number inserted into the table is not continuous.

"Continuous" in a relationship to the Employee number means the first record inserted will have the Employee number 1, the second record will have the employee number 2, and each next position must have a number greater by one that a number of the previous position.

I have successfully created the trigger,  however when I inserted a new record that have an Employee number that is not continuous, my trigger is not fired.

Im unsure where I went wrong and hope I can get some explanation and corrections on my code.

CREATE OR REPLACE TRIGGER CONTENUM

AFTER INSERT ON TRKEMPLOYEE
FOR EACH ROW

DECLARE
continuous_value EXCEPTION;
PRAGMA exception_init(continuous_value, -20111);

PRAGMA AUTONOMOUS_TRANSACTION;

BEGIN

IF (:NEW.E# > :OLD.E# + 1) THEN
    RAISE_APPLICATION_ERROR (-20111,'The value of  Employee number must be continuous');

END IF;

END CONTENUM;
/

Here is the format of my sample TRKEMPLOYEE table

 CREATE TABLE TRKEMPLOYEE(
    E#              NUMBER(12)      NOT NULL,
    NAME            VARCHAR(50)     NOT NULL,
    DOB             DATE                    ,
    ADDRESS         VARCHAR(300)    NOT NULL,
    HIREDATE        DATE            NOT NULL,
    CONSTRAINT TRKEMPLOYEE_PKEY PRIMARY KEY(E#) );

Here is my insert statement.
Currently in my table TRKEMPLOYEE there is only 15 rows thus with my insert statement, the trigger should fire but it is not happening.

INSERT INTO TRKEMPLOYEE VALUES( 17, 'David', NULL, 'GB',sysdate );

Thank you.

Body:
First of all you are checking AFTER INSERT ON TRKEMPLOYEE which will be executed after the row is inserted.

Secondly, you cannot check :OLD.E# since you are not updating and you are not using a old value.

Also you should drop the trigger at all and use SEQUENCES and let Oracle take care of the auto-increment values every time you add a new employee.

If you want to continue with your current logic, fixes that can be applied:

Change AFTER INSERT ON TRKEMPLOYEE to BEFORE INSERT ON TRKEMPLOYEE

Logic should be changed as below:

CREATE OR REPLACE TRIGGER contenum BEFORE
    INSERT ON trkemployee
    FOR EACH ROW
DECLARE
    continuous_value EXCEPTION;
    PRAGMA exception_init ( continuous_value, -20111 );
    PRAGMA autonomous_transaction;
    max_e# INTEGER;
BEGIN
    SELECT
        nvl(MAX(e#), 0)
    INTO max_e#
    FROM
        trkemployee;

    IF ( :new.e# > max_e# + 1 ) THEN
        raise_application_error(-20111, 'The value of  Employee number must be continuous');
    END IF;
END contenum;
/

I do not recommend this solution because it will start to become slower as your table starts to grow.


问:
How to change table border-collapse property for specific table row?
I have an example on the snippet which has table and applied border-collapse:seperate property.But I dont want second row to have this rule.Is there anyway to turn this off for specific row?

<!DOCTYPE html>

border-collapse: separate

    Firstname
    Lastname

    Peter
    Griffin

    Lois
    Griffin

```

答: You can use some CSS selector such as nth-child or nth-of-type to turn on/off effect for specific row.</p>


问:
Move child elements if parent is duplicate
Just staring to lean js here. Is it possible to move child elements from one parent under another parent if parent name is duplicate?

Example:

How to put Something else & Something like under a single Composition parent, and Someone else under one Content, and delete the duplicates.
Is this possible with javascript or jquery? Thank you!

```<code><li>
  <h4>Composition</h4>
  <p>Something</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something else</p>
</li>
<li>
  <h4>Composition</h4>
  <p>Something like</p>
</li>

<li>
  <h4>Content</h4>
  <p>Someone</p>
</li>
  <h4>Content</h4>
  <p>Someone else</p>
</li>
</code>```

here is the js I got so far, I'm stuck at moving p items to the first element that repeats, each under it's parent. thing is parent elements don't have certain id's or classes:

```<code>const $technicalProp = $("[data-surface-prop]");
const technicalVal = $("[data-surface-val]");
let duplicate = {};

$technicalProp.each(function() {
  let txt = $(this).text();

  if (duplicate[txt]) {
     $(this).remove(); // this only removes the dulicate names I also need to move chlidren
  }
  else {
    duplicate[txt] = true;
  }
});
</code>```

答:
yes you can i dont know if this is the best way but this works, my approach is by making an arrayobject (js) as a new model of what you want

the logic is i extract the text of h4 and check if the data variable has been registered there, if not registered yet then i push it to the data and the child text (p)
if registered already then i push the child text only

```<code>let data = [];
        const lists = document.querySelectorAll('li').forEach( (li, liIdx) => {
            let parentName = li.querySelector('h4').innerHTML;
            let childName = li.querySelector('p').innerHTML;
            let isRegistered = data.find( x => x.parentName === parentName);
            if(!isRegistered) {
                childName = [childName];
                data.push({ parentName, childName});
            }else {
                console.log(isRegistered)
                isRegistered.childName.push(childName);
            }
        });
</code>```

and this is what we got

```<code>0:
childName: (3) ["Something", "Something else", "Something like"]
parentName: "Composition"
1:
childName: (2) ["Someone", "Someone else"]
parentName: "Content"
</code>```

then reset the ol tag and rebuild its item

```<code>let ol = document.querySelector('ol');
ol.innerHTML = '';

        data.map( d => {
            let p = d.childName.map( c => `<p>${c}</p>`).join('');
            ol.insertAdjacentHTML('beforeend', `
                <li>
                    <h4>${d.parentName}</h4>
                    ${p}
                </li>
            `);
        })
</code>```

Body:
Just staring to lean js here. Is it possible to move child elements from one parent under another parent if parent name is duplicate?

Example:

How to put Something else & Something like under a single Composition parent, and Someone else under one Content, and delete the duplicates.
Is this possible with javascript or jquery? Thank you!

Composition

Something

Composition

Something else

Composition

Something like

Content

Someone

Content

Someone else

here is the js I got so far, I'm stuck at moving p items to the first element that repeats, each under it's parent. thing is parent elements don't have certain id's or classes:

const $technicalProp = $("[data-surface-prop]");
const technicalVal = $("[data-surface-val]");
let duplicate = {};

$technicalProp.each(function() {
  let txt = $(this).text();

  if (duplicate[txt]) {
     $(this).remove(); // this only removes the dulicate names I also need to move chlidren
  }
  else {
    duplicate[txt] = true;
  }
});

Body:
yes you can i dont know if this is the best way but this works, my approach is by making an arrayobject (js) as a new model of what you want

the logic is i extract the text of h4 and check if the data variable has been registered there, if not registered yet then i push it to the data and the child text (p)
if registered already then i push the child text only

let data = [];
        const lists = document.querySelectorAll('li').forEach( (li, liIdx) => {
            let parentName = li.querySelector('h4').innerHTML;
            let childName = li.querySelector('p').innerHTML;
            let isRegistered = data.find( x => x.parentName === parentName);
            if(!isRegistered) {
                childName = [childName];
                data.push({ parentName, childName});
            }else {
                console.log(isRegistered)
                isRegistered.childName.push(childName);
            }
        });

and this is what we got

0:
childName: (3) ["Something", "Something else", "Something like"]
parentName: "Composition"
1:
childName: (2) ["Someone", "Someone else"]
parentName: "Content"

then reset the ol tag and rebuild its item

let ol = document.querySelector('ol');
ol.innerHTML = '';

        data.map( d => {
            let p = d.childName.map( c => `<p>${c}</p>`).join('');
            ol.insertAdjacentHTML('beforeend', `
                <li>
                    <h4>${d.parentName}</h4>
                    ${p}
                </li>
            `);
        })


问:
Can we configure SSO (Single Sign On) in Azure without using Azure Active Directory?
Can we configure SSO (Single Sign-On) in Azure without using the Azure Active Directory? Or using any Code.</p>

答: If you need to log in with Azure AD users then SSO is required for Azure AD. If you have your own database of users to login and then you don't require Azure AD.</p>


答:
I'm afraid this is going to be pretty much opinion-based.

The problem is you're looking at the implementation. If you have an IDE, use code folding to see just the method signature. Then, look at what the requirements for this method are.

Now, you can test it. Just write code to check if the method conforms to requirements (if specific input parameters produce desired output, what happens for illegal parameters). And you're done. Later on someone can change how the method is implemented. If the tests work anyway, you are sure no-one broke anything by changing the implementation.

So, ideally you would supply a mocked repository with part of desired behavior implemented, so it returns the data you want when queried with Pageable.

This way you can just assert on returned data, and your tests are solid - i.e. if someone changes to another implementation, but it still produces desired output, your tests pass.

Compare that to calling verify. This test is brittle, since on changed implementation it will fail. Why should it? Which business requirement was broken so that the test failed? Well, none.

And if you have a test-suite to prove your mocked data layer behaves the same way as the real one (to the desired level), you can have insanely fast pseudo-integration tests, which can be easily run before the real ones. And you're testing the real stuff, the functionality, in implementation-agnostic way.

Title: What is the point of making a test for Pageable?


问:
Add a summary information to WiX generated MSI
How to add (or change a default values) a summary page information to a WiX-generated MSI file?

Summary page is the tab page which is visible if you right click on the MSI file in the Windows Explorer and includes following text fields:

Title,
Subject,
Author,
Category,
Keywords,
Comments

alt text http://img151.imagevenue.com/img.php?image=13824_msi_summary_122_495lo.jpg

答:
That information is set in the <Package> element, for example:

```<code><Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
  <Product
  UpgradeCode="SOMEGUID-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  Name='MyApp'
  Id='????????-????-????-????-????????????'
  Language='1033'
  Codepage='1252'
  Version='1.0.0'
  Manufacturer='MyCompany'>
    <Package
    Id="*"
    Keywords="keyword1, keyword2, keyword3"
    Description="summary of application"
    Comments="some comments"
    Manufacturer="mycompany"
    InstallerVersion="300"
    Languages="1033"
    Compressed="yes"
    SummaryCodepage="1252"/>
</code>```

OwnerDisplayName: AlexWendy

ContentLicense: CC BY-SA 2.5

Body:
That information is set in the <Package> element, for example:

<Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
  <Product
  UpgradeCode="SOMEGUID-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  Name='MyApp'
  Id='????????-????-????-????-????????????'
  Language='1033'
  Codepage='1252'
  Version='1.0.0'
  Manufacturer='MyCompany'>
    <Package
    Id="*"
    Keywords="keyword1, keyword2, keyword3"
    Description="summary of application"
    Comments="some comments"
    Manufacturer="mycompany"
    InstallerVersion="300"
    Languages="1033"
    Compressed="yes"
    SummaryCodepage="1252"/>

OwnerDisplayName: Stefan


答:
You could use Sass Maps:

```<code>$slot: (
  "width": 100px,
  "height": 10px,
  "title": (
    "width": 80px,
    "height": 10px
  )
);
</code>```

Additionally, here's a good article on getting values out of deep Sass maps.

However, it may be easier to continue using regular variables with hyphens, as you already have.

Title: How to avoid Sass variable name repeat in _variables.scss?

Body:
You could use Sass Maps:

$slot: (
  "width": 100px,
  "height": 10px,
  "title": (
    "width": 80px,
    "height": 10px
  )
);

Additionally, here's a good article on getting values out of deep Sass maps.

However, it may be easier to continue using regular variables with hyphens, as you already have.


问:
Parse string in nodejs to an array
How can I convert following string into an array in nodejs?

```<code>"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"
</code>```

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

答:
Given string is not JSON strigyfied, So try with following replace with having keys as strings.

y =
  "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]";

y = `{${y}}`;
y = y.replace("},]", "}]");
y = y.replace(/Content/g, '"Content"');
y = y.replace(/id/g, '"id"');
y = y.replace(/value/g, '"value"');
y = y.replace(/number/g, '"number"');

str = JSON.parse(y);

console.log(str);```

Title: Parse string in nodejs to an array

Body:
How can I convert following string into an array in nodejs?

"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?


问:
bootstrap input group sizing
I have a series of bootstrap 4 input groups and would like them to be of the same size. In the docs, they add classes like input-group-sm or input-group-lg and even though the text sizes are changed, the overall width of the input group stays the same.

That doesn't work for me:

Fiddle: https://jsfiddle.net/efx7rp4n/

Source:

```<code><div class="container">

  <div class="input-group mb-3">
      <div class="input-group-prepend">
        <span class="input-group-text">Long descriptive text:</span>
      </div>
      <div class="input-group-text">
        <input type="checkbox" aria-label="Checkbox for following text input">
      </div>
    </div>

    <div class="input-group mb-3">
      <div class="input-group-prepend">
        <span class="input-group-text">Short:</span>
      </div>
      <div class="input-group-text">
        <input type="checkbox" aria-label="Checkbox for following text input">
      </div>
    </div>
</div>
</code>```

How can I force my input groups to be of the same width ?

As this is bootstrap, there are of course tons of related questions. This one Bootstrap input group sizes recommends adding size=50 as attribute. No effect for me.

This one Bootstrap input group field not sizing correctly looked very similar to my problem. But I already tried adding a fixed width over css, it only makes it worse,
 leads to:

答:
Try something like this:</p>

```<code><div class="input-group mb-3">
<div class="input-group-prepend flex-colunm col-4">
    <label class="input-group-text flex-fill ">{{ field.label }}</label>
</div>
{{ field }}
</div>
</code>```

Title: bootstrap input group sizing

Body:
I have a series of bootstrap 4 input groups and would like them to be of the same size. In the docs, they add classes like input-group-sm or input-group-lg and even though the text sizes are changed, the overall width of the input group stays the same.

That doesn't work for me:

Fiddle: https://jsfiddle.net/efx7rp4n/

Source:

        Long descriptive text:

        <input type="checkbox" aria-label="Checkbox for following text input">

        Short:

        <input type="checkbox" aria-label="Checkbox for following text input">

How can I force my input groups to be of the same width ?

As this is bootstrap, there are of course tons of related questions. This one Bootstrap input group sizes recommends adding size=50 as attribute. No effect for me.

This one Bootstrap input group field not sizing correctly looked very similar to my problem. But I already tried adding a fixed width over css, it only makes it worse,
 leads to:

Body:
Try something like this:

<div class="input-group mb-3">
<div class="input-group-prepend flex-colunm col-4">
    <label class="input-group-text flex-fill ">{{ field.label }}</label>
</div>
{{ field }}
</div>


问:
LINQ - Will FirstOrDefault() always return the same record?
if I have the following 'User' table

```<code>UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

</code>```

and the following linq query:

```<code>_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();
</code>```

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?

答:
I read the following in Enumerable.OrderBy

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.

So, since this is a stable sort, the result of an IEnumerable OrderBy will always be the same.

However, although you didn't tell so, because you are using _context.User, I assume that the table is in a database management system. The result depends on your DBMS.

Queryable.OrderBy says:

The query behavior that occurs as a result of executing an expression tree that represents calling OrderBy(IQueryable, Expression>) depends on the implementation of the type of the source parameter. The expected behavior is that it sorts the elements of source based on the key obtained by invoking keySelector on each element of source.

This is a difficult way to say the the result of sorting two elements depends on the DBMS that you use. If you want to be certain that you have always the same sorted result, you'll have to order ThenBy a 2nd element, and if needed a 3rd, until you are certain that you are sorting on unique values.

Body:
if I have the following 'User' table

UserName UserID
-------- ------
abc      1
xyz      2
pqr      2

and the following linq query:

_context.User.OrderByDescending(x => x.UserID).FirstOrDefault();

will the result always be consistent?

as in will I always get either user with UserName 'xyz' or user with UserName 'pqr' or will it be random?


问:
Binding to nested properties where observables in the chain can be null
I just read about KnockoutJS and when I try to bind to sub-properties on objects that can be null I get binding errors, e.g.:

```

<p>So once you call <code>ko.applyBindings</code> it tries to evaluate the above expression and if <code>selectedAccount</code> is null (which it is by default) it throws an error. I know that I can create a <code>dependentObservable</code> like so:</p>

```viewModel.docLength = ko.dependentObservable(function () {
    return selectedAccount() ? selectedAccount().DocumentList().length : null;
})
```

But I was wondering if there's a solution other than putting properties in the ViewModel simply because I get a binding error.

答:
A couple thoughts:

If you don't want to bother with the dependentObservable, then you can place your statement directly in the text binding like:

```<code><div data-bind="text: selectedAccount() ? selectedAccount().DocumentList().length : null"></div>
</code>```

or even shorter:

```<code><div data-bind="text: selectedAccount() && selectedAccount().DocumentList().length"></div>
</code>```

Depending on your scenario, you can also use the template binding to your advantage when dealing with potentially null values.  It would be like this:

```<code><div data-bind="template: { name: 'accountTmpl', data: selectedAccount }"></div>

<script id="accountTmpl" type="text/html">
    ${DocumentList().length}
</script>
</code>```

Additionally, in the 1.3 release of Knockout there will be some control flow bindings that could be helpful to you.  Particularly the "if" or "with" bindings would work for this situation.  They are described here:  https://groups.google.com/d/topic/knockoutjs/pa0cPkckvE8/discussion

Body:
I just read about KnockoutJS and when I try to bind to sub-properties on objects that can be null I get binding errors, e.g.:

So once you call ko.applyBindings it tries to evaluate the above expression and if selectedAccount is null (which it is by default) it throws an error. I know that I can create a dependentObservable like so:

viewModel.docLength = ko.dependentObservable(function () {
    return selectedAccount() ? selectedAccount().DocumentList().length : null;
})

But I was wondering if there's a solution other than putting properties in the ViewModel simply because I get a binding error.

Body:
A couple thoughts:

If you don't want to bother with the dependentObservable, then you can place your statement directly in the text binding like:

<div data-bind="text: selectedAccount() ? selectedAccount().DocumentList().length : null"></div>

or even shorter:

<div data-bind="text: selectedAccount() && selectedAccount().DocumentList().length"></div>

Depending on your scenario, you can also use the template binding to your advantage when dealing with potentially null values.  It would be like this:

<div data-bind="template: { name: 'accountTmpl', data: selectedAccount }"></div>

<script id="accountTmpl" type="text/html">
    ${DocumentList().length}
</script>

Additionally, in the 1.3 release of Knockout there will be some control flow bindings that could be helpful to you.  Particularly the "if" or "with" bindings would work for this situation.  They are described here:  https://groups.google.com/d/topic/knockoutjs/pa0cPkckvE8/discussion


答:
I think one loop is sufficient to do this.

var data=[
{group: "a", A: 65, N: 20},
{group: "b", R: 52},
{group: "c", N: 20, A: 2, R: 2},
{group: "d", R: 15, N: 12},
],

max = Object.keys(data[0]).length,
largestObj = data[0];

data.forEach(i=>{
  if(Object.keys(i).length> max){
    max = Object.keys(i).length;
    largestObj = i;
  }
});

console.log(max);
console.log(largestObj);```

Title: Javascript get largest object in array of objects

Body:
I want to get the largest object in an array of objects, the code I'm using works fine, but I wonder if there is a better way of doing the same. This is the code I'm using.

data=[
    {group: "a", A: 65, N: 20},
    {group: "b", R: 52},
    {group: "c", N: 20, A: 2, R: 2},
    {group: "d", R: 15, N: 12},
]

len = []
for (var i in data){
    len.push(Object.keys(data[i]).length)
}

for (var i in data){
    if (Object.keys(data[i]).length==Math.max.apply(null, len)){
      subgroups = Object.keys(data[i]).slice(1).sort();
    }
}

console.log(subgroups);


问:
Is there any API in GCP to get the resource usage details..?
I am looking for some API's in GCP that can fetch the usage of resource in terms of usage hours, storage usage etc</p>

答:
If you are interested in obtaining the information about the use of Compute Engine resources so that correlate actual consumption with billing, you can use on the resource usage reports.

Once you set it up, usage reports will be delivered into a preconfigured Cloud Storage Bucket. There are two types of reports that are generated on a regular basis:

Daily usage reports

Monthly rollup report

The supported metrics cover resources in question:

Virtual machines

Persistent disks

Images

Snapshots

Static IP addresses

Load balancers

The generated reports contain quantity of consumed resources measured in units (count, seconds, hours, etc) specific for a resource type.

You can manage the usage reports feature with Cloud Console, gcloud and API.

Please see Compute Engine > Doc > Viewing usage reports for more details.


问:
Can't create custom widget in tray menu with python pyside2
Not much info I've found, but looks like this snippet should works:

import sys

from PySide2.QtWidgets import QApplication, QMenu, QPushButton, QSystemTrayIcon, QWidgetAction

app = QApplication(sys.argv)
menu = QMenu()
button = QPushButton("yoba")
action = QWidgetAction(menu)
action.setDefaultWidget(button)
menu.addAction(action)
menu.addAction("Quit").triggered.connect(sys.exit)
tray = QSystemTrayIcon()
tray.setContextMenu(menu)
tray.show()
sys.exit(app.exec_())
```

But, I see only Quit item and empty item above, no push button appear. So, the question is "how to add custom widgets to tray menu?"

答:
Ok, looks like this is a bug: https://bugreports.qt.io/browse/QTBUG-26840

Since if call menu.show() instead of tray.show() everything is fine.

Body:
Not much info I've found, but looks like this snippet should works:

import sys

from PySide2.QtWidgets import QApplication, QMenu, QPushButton, QSystemTrayIcon, QWidgetAction

app = QApplication(sys.argv)
menu = QMenu()
button = QPushButton("yoba")
action = QWidgetAction(menu)
action.setDefaultWidget(button)
menu.addAction(action)
menu.addAction("Quit").triggered.connect(sys.exit)
tray = QSystemTrayIcon()
tray.setContextMenu(menu)
tray.show()
sys.exit(app.exec_())

But, I see only Quit item and empty item above, no push button appear. So, the question is "how to add custom widgets to tray menu?"


问:
Centering Google Doc Export CSS
here's a common thing we do all the time: export from Google docs as 'html' but the end result is a mass of CSS definitions that have a fixed width and is not centered.

I've tried several common HTML fixes and nothing seems to work such as

```<code>P.blocktext {
    margin-left: auto;
    margin-right: auto;
    width: 8em
}
...
<P class="blocktext">
</code>```

even the good old fashioned table does nothing

```<code><table><tr><td align='center'>
and
<table align='center'><tr><td>
</code>```

For some reason, everything still seems to have the same left-justified text when exported from google doc.

What I'm looking for is CSS code that will perhaps make it more !important than the rest of the CSS so that my document can at least be in the middle of the page.

The actual body content of the Google Doc starts like this:

```<code><body class="c29" >
<p class="c14"><span class="c8">
</code>```

I do not want to go into the class definitions because there are hundreds of them.  What we want is a snippet of code that simply aligns the whole thing in the horizontal middle of the screen.

Ideas?

答:
Place this BEFORE the  (or whatever number it happens to be) and your Google Doc export will be perfectly centered. Thanks to Junaid on my dev team for figuring this out!</p>

```<code><style>
body{
margin:0 auto;
}
</style>
</code>```

Title: Centering Google Doc Export CSS

Body:
here's a common thing we do all the time: export from Google docs as 'html' but the end result is a mass of CSS definitions that have a fixed width and is not centered.

I've tried several common HTML fixes and nothing seems to work such as

P.blocktext {
    margin-left: auto;
    margin-right: auto;
    width: 8em
}
...

even the good old fashioned table does nothing

and

For some reason, everything still seems to have the same left-justified text when exported from google doc.

What I'm looking for is CSS code that will perhaps make it more !important than the rest of the CSS so that my document can at least be in the middle of the page.

The actual body content of the Google Doc starts like this:

I do not want to go into the class definitions because there are hundreds of them.  What we want is a snippet of code that simply aligns the whole thing in the horizontal middle of the screen.

Ideas?

Body:
Place this BEFORE the  (or whatever number it happens to be) and your Google Doc export will be perfectly centered. Thanks to Junaid on my dev team for figuring this out!

<style>
body{
margin:0 auto;
}
</style>


问:
Vue.js Failed to mount component: template or render function not defined
I'm learning to use Vue.js with Laravel from this series the narrator doesn't get any error but I've encountered the following error while I click to change the route.

[Vue warn]: Failed to mount component: template or render function not defined.

Below code is from my app.js:

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue')
  }
]

const router = new VueRouter({
  routes
})

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

const app = new Vue({
  el: '#app',
  router
});```
</div>
</div>
</p>

<p>Code snippet from my <code>Dashboard.vue</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Dashboard Component</div>

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

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

Code snippet from my master.blade.php layout:

//sidebar

    <router-link to="/dashboard" class="nav-link">Dashboard

    <router-link to="/profile" class="nav-link">Profile

//content

  <router-view></router-view>

```

I'm running app at localhost:3000with browserSync and npm run watch. Does it has anything to do with error ?

答:
// Just add "import Vue from 'vue'" and the component will be shown !

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue')
  }
]

const router = new VueRouter({
  routes
})

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

const app = new Vue({
  el: '#app',
  router
});```

Body:
I'm learning to use Vue.js with Laravel from this series the narrator doesn't get any error but I've encountered the following error while I click to change the route.

[Vue warn]: Failed to mount component: template or render function not defined.

Below code is from my app.js:

require('./bootstrap');

window.Vue = require('vue');

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [{
    path: '/dashboard',
    component: require('./components/Dashboard.vue')
  },
  {
    path: '/profile',
    component: require('./components/Profile.vue')
  }
]

const router = new VueRouter({
  routes
})

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

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

Code snippet from my Dashboard.vue:

<template>

Dashboard Component

                        I'm an example component.

</template>

Code snippet from my master.blade.php layout:

//sidebar

    <router-link to="/dashboard" class="nav-link">Dashboard

    <router-link to="/profile" class="nav-link">Profile

//content

  <router-view></router-view>

I'm running app at localhost:3000with browserSync and npm run watch. Does it has anything to do with error ?


问:
Javascript get largest object in array of objects
I want to get the largest object in an array of objects, the code I'm using works fine, but I wonder if there is a better way of doing the same. This is the code I'm using.

data=[
    {group: "a", A: 65, N: 20},
    {group: "b", R: 52},
    {group: "c", N: 20, A: 2, R: 2},
    {group: "d", R: 15, N: 12},
]

len = []
for (var i in data){
    len.push(Object.keys(data[i]).length)
}

for (var i in data){
    if (Object.keys(data[i]).length==Math.max.apply(null, len)){
      subgroups = Object.keys(data[i]).slice(1).sort();
    }
}

console.log(subgroups);```

答:
An example using Array.prototype.reduce

```<code>const [biggestObject] = data.reduce(
  ([acc, length], entry) => {
    const len = Object.keys(entry).length;
    return length > len ? [acc, length] : [entry, len];
  },
  [{}, 0]
);
</code>```

Body:
An example using Array.prototype.reduce

const [biggestObject] = data.reduce(
  ([acc, length], entry) => {
    const len = Object.keys(entry).length;
    return length > len ? [acc, length] : [entry, len];
  },
  [{}, 0]
);


问:
How to implement infinity in Java?
Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?

E.g.

```<code>int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity
</code>```

I have tried using very large numbers, but I want a proper, easy solution.

答:
I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean and double types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3

Positive zero and negative zero compare equal; thus the result of the
  expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But
  other operations can distinguish positive and negative zero; for
  example, 1.0/0.0 has the value positive infinity, while the value of
  1.0/-0.0 is negative infinity.

It looks ugly, but it works.

```<code>public class Main {

    public static void main(String[] args) {
        System.out.println(1.0/0.0);
        System.out.println(-1.0/0.0);
    }

}
</code>```

Title: How to implement infinity in Java?

Body:
Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?

E.g.

int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity

I have tried using very large numbers, but I want a proper, easy solution.

Body:
I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean and double types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3

Positive zero and negative zero compare equal; thus the result of the
  expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But
  other operations can distinguish positive and negative zero; for
  example, 1.0/0.0 has the value positive infinity, while the value of
  1.0/-0.0 is negative infinity.

It looks ugly, but it works.

public class Main {

    public static void main(String[] args) {
        System.out.println(1.0/0.0);
        System.out.println(-1.0/0.0);
    }

}


问:
AttributeError: 'str' object has no attribute 'json'
I wrote little script on python 3.7 to receive actual browser version

Here is it:

```<code>import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]
</code>```

Also, json file exists, but it does not matter now.

Received:

```<code>AttributeError: 'str' object has no attribute 'json'.
</code>```

In row

```<code>last_version = repr(res.json()['latest']['client'][browser_name]['version'])
</code>```

Please, tell me what is my mistake?

答:
Ok, the problem is here:

```<code>    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
</code>```

A JSON object is basically a dictionary. So when you do json['key'] it returns the content, not a json object.

Here res is a string, not a json object and thus does not have the .json() attribute.

Edit:

If you want a string to be return in your situation:

```<code>res = json.loads(f['global']['link_to_latest_browser_version'])
last_version = res['latest']['client'][browser_name]['version']

return last_version
</code>```

Body:
I wrote little script on python 3.7 to receive actual browser version

Here is it:

import json

def json_open():
    file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
    return json.load(file_json)

def get_last_version(browser_name):
    f = json_open()
    res = (f['global']['link_to_latest_browser_version'])
    last_version = repr(res.json()['latest']['client'][browser_name]['version'])
    #print(last_version[1:-1])
    return last_version[1:-1]

Also, json file exists, but it does not matter now.

Received:

AttributeError: 'str' object has no attribute 'json'.

In row

last_version = repr(res.json()['latest']['client'][browser_name]['version'])

Please, tell me what is my mistake?

Body:
Ok, the problem is here:

    last_version = repr(res.json()['latest']['client'][browser_name]['version'])

A JSON object is basically a dictionary. So when you do json['key'] it returns the content, not a json object.

Here res is a string, not a json object and thus does not have the .json() attribute.

Edit:

If you want a string to be return in your situation:

res = json.loads(f['global']['link_to_latest_browser_version'])
last_version = res['latest']['client'][browser_name]['version']

return last_version


问:
can multiple producers send message to Queue at the same time from different java applications
I have 2 applications A and B, trying to send messages from both to one queue.
Placed a while loop at both places which is sending message to queue.
if i start application A and start while loop it starts sending message to queue and consumer consumes message sent from A, now at same time if i start while loop from B application it doesn't publish messages to queue as consumer doesn't consumes any message sent from B.

So can someone clear the doubt if messages are being sent at same time from multiple producers to single queue or not.

PS- using IBM queue and using a single consumer.

答:
Yes, we can have multiple producers for single queue.
Multiple producers can also publish messages at the same time.</p>