问:
Can't get dynamic variable name to get result on document.getElementById, only returning the string
I'm new to JS and been trying for some time already to solve this myself, but after lots of searching (found lots of information on different ways to concat or otherwise make variables dynamic but not how to use these variables to retrieve properties) and trying I finally decided to ask for help.

I have been trying to use dynamic variables to get properties of an object, first outputting my information to JS objects, and after that getting values from dropdown select elements and a string, combining all that information to one string, and after that using that string as object.property. But what I finally get as a result is just output string which seems correct, but it's printed out just as a string, not working as object.property. Propably this is just something small I just can't figure out, or perhaps my approach is just totally wrong. Also already tried the same by outputting to hidden table elements, and then changing hidden=false, but the result was more or less the same. By hardcoding the string to work as the object.property I get the result I'm looking for, this done just to test my objects.

Using object constructor that seems working ok:

```<code> function myCar(carClass, id, brandType, price) {
     this.carClass = carClass;
     this.id = id;
     this.brandType = brandType;
     this.price = price;
 };
</code>```

When fetching database information myCar or object variable name gets to be for example "sedan_car_audi", and other information goes in their respective places.

The dropdown information comes from here:

```<code><fieldset>
<p>
<span>myCarType Title: <select name="myCarType" id="myCarTypeId" onchange="clearSelectionOutput()" >
 <option value="sedan" > sedan
 <option value="hatchback" > hatchback
 <option value="convertible" > convertible
 <option value="customized" > customized
 </select></span>

<select name="vehicleType" id="vehicleType" hidden>
<option value="car">
</select>

<span>myCarBrand Title: <select name="myCarBrand"id="myCarBrandId" onchange="clearSelectionOutput()" >
 <option value="audi" > Audi
 <option value="bmw"   > BMW
 <option value="mercedenz" > Mercedenz
 <option value="volvo"    > Volvo
 </select></span>
 <input type="submit" onclick="myCarBrandAndTypeFunction()" value="Submit">
 </p>
 </fieldset>
</code>```

And script where I try to make the combined variable( or actually here are couple of ways I've tried) and use document.getElementById to get the result for example sedan_car_audi.price , but what I get is only the string "sedan_car_audi.price" as the result, not the price property value.. (which works ok for showing it on the "demo10":

```<code>    <script>

function myCarBrandAndTypeFunction(){
 var myCarTypeIdVariable =document.getElementById("myCarTypeId");
 var myCarBrandIdVariable =document.getElementById("myCarBrandId");
 var vehicleTypeVariable =document.getElementById("vehicleType");

 var underscore ="_";
 var priceAddendum = ".price";

 var myCarPriceCheckBuilder = {
     first: myCarTypeIdVariable.value,
     second: underscore,
     third: vehicleType.value,
     fourth: underscore,
     fifth: myCarBrandIdVariable.value,
     sixth: priceAddendum,
     seventh: function () {return this.first + this.second + this.third + this.fourth + this.fifth + this.sixth}
             };

     var myCarPriceCheckBuilderAlltogether =  myCarTypeId.value + underscore + vehicleType.value + underscore + myCarBrandId.value + priceAddendum;
     var myCarPriceCheckBuilderStraight = myCarTypeId.value + "_" + vehicleType.value + "_" + myCarBrandId.value;
     var myCarPriceCheckBuilderObjectNew = {one : ""};
        myCarPriceCheckBuilderObjectNew.one = myCarPriceCheckBuilder['seventh'] ;

         document.getElementById("demo10").innerHTML = sedan_car_audi.price + " €";
         document.getElementById("demo11").innerHTML = "Your car price is " + myCarPriceCheckBuilderAlltogether + " €";
         document.getElementById("demo13").innerHTML = "My New Car's price is " + myCarPriceCheckBuilder.seventh + " €"  ;
      };

         function clearSelectionOutput(){
         document.getElementById("demo10").innerHTML = "";
         document.getElementById("demo11").innerHTML = "";
         document.getElementById("demo12").innerHTML = "";
         document.getElementById("demo13").innerHTML = "";
         document.getElementById("demo14").innerHTML = "";
      };
     </script>
</code>```

I hope this is clear enough, this is modified version of my real code, but should be accurately copied/modified.

Sleepless nights and grayed hair would hugely appreciate any help.

答:
I am not entirely sure of what you want but here is my solution:

```<code>myCarPriceCheckBuilderObjectNew.one = eval(myCarPriceCheckBuilder['seventh']());
</code>```

You also would need to define the objects sedan_car_audi and similar to get values else it will throw an error. Hope that answers!

Body:
I'm new to JS and been trying for some time already to solve this myself, but after lots of searching (found lots of information on different ways to concat or otherwise make variables dynamic but not how to use these variables to retrieve properties) and trying I finally decided to ask for help.

I have been trying to use dynamic variables to get properties of an object, first outputting my information to JS objects, and after that getting values from dropdown select elements and a string, combining all that information to one string, and after that using that string as object.property. But what I finally get as a result is just output string which seems correct, but it's printed out just as a string, not working as object.property. Propably this is just something small I just can't figure out, or perhaps my approach is just totally wrong. Also already tried the same by outputting to hidden table elements, and then changing hidden=false, but the result was more or less the same. By hardcoding the string to work as the object.property I get the result I'm looking for, this done just to test my objects.

Using object constructor that seems working ok:

 function myCar(carClass, id, brandType, price) {
     this.carClass = carClass;
     this.id = id;
     this.brandType = brandType;
     this.price = price;
 };

When fetching database information myCar or object variable name gets to be for example "sedan_car_audi", and other information goes in their respective places.

The dropdown information comes from here:

<fieldset>

myCarType Title: <select name="myCarType" id="myCarTypeId" onchange="clearSelectionOutput()" >
 <option value="sedan" > sedan
 <option value="hatchback" > hatchback
 <option value="convertible" > convertible
 <option value="customized" > customized
 </select>

<select name="vehicleType" id="vehicleType" hidden>
<option value="car">
</select>

myCarBrand Title: <select name="myCarBrand"id="myCarBrandId" onchange="clearSelectionOutput()" >
 <option value="audi" > Audi
 <option value="bmw"   > BMW
 <option value="mercedenz" > Mercedenz
 <option value="volvo"    > Volvo
 </select>
 <input type="submit" onclick="myCarBrandAndTypeFunction()" value="Submit">

 </fieldset>

And script where I try to make the combined variable( or actually here are couple of ways I've tried) and use document.getElementById to get the result for example sedan_car_audi.price , but what I get is only the string "sedan_car_audi.price" as the result, not the price property value.. (which works ok for showing it on the "demo10":

I hope this is clear enough, this is modified version of my real code, but should be accurately copied/modified.

Sleepless nights and grayed hair would hugely appreciate any help.

Body:
I am not entirely sure of what you want but here is my solution:

myCarPriceCheckBuilderObjectNew.one = eval(myCarPriceCheckBuilder['seventh']());

You also would need to define the objects sedan_car_audi and similar to get values else it will throw an error. Hope that answers!


来源: stackexchange

问:
Using 2 different data to show in chart laravel
I am currently using chartTV to create a chart but my chart doesn't seem to appear inside my blade for some reason, the title can be seen but not the graph. I want to create an areaspline chart where it will show number of people hired and not hired this week. I tried doing something like this but it not working. Can someone guide me in doing it correctly? How should I do it?

My dashboardController:

```<code>$user1s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('Evaluation_Status', '=', 'No')
             ->get();
$user2s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('evaluations.Evaluation_Status', '=', 'Yes')
             ->get();

Charts::Database($user1s, $user2s, 'areaspline', 'highcharts')
       ->title('My nice chart')
       ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
       ->dataset('Hired', [$user1s])
       ->dataset('Not Hired', [$user2s]);

return view('dashboard', ['chart' => $chart]);
</code>```

My dashboard.blade.php

```<code>{!! Charts::assets() !!}
{!! $chart->render() !!}
</code>```

答:
I assume the problem are these 2 lines:

```<code>->dataset('Hired', [$user1s])
->dataset('Not Hired',  [$user2s]);
</code>```

Both $user1s and $user2s are already arrays. Since both array contain objects you also might have to map them to scalar values (numbers or strings) to get the values you want to use.

So you could do something like this, if you want to map the names:

```<code>$hiredUsernames = array_map(
    function ($user) {
        return $user->name;
    },
    $user1s
);
// The result will be something like: ['Max', 'Jane', ...]

->dataset('Hired', $hiredUsernames)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently using chartTV to create a chart but my chart doesn't seem to appear inside my blade for some reason, the title can be seen but not the graph. I want to create an areaspline chart where it will show number of people hired and not hired this week. I tried doing something like this but it not working. Can someone guide me in doing it correctly? How should I do it?

My dashboardController:

$user1s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('Evaluation_Status', '=', 'No')
             ->get();
$user2s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('evaluations.Evaluation_Status', '=', 'Yes')
             ->get();

Charts::Database($user1s, $user2s, 'areaspline', 'highcharts')
       ->title('My nice chart')
       ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
       ->dataset('Hired', [$user1s])
       ->dataset('Not Hired', [$user2s]);

return view('dashboard', ['chart' => $chart]);

My dashboard.blade.php

{!! Charts::assets() !!}
{!! $chart->render() !!}

Body:
I assume the problem are these 2 lines:

->dataset('Hired', [$user1s])
->dataset('Not Hired',  [$user2s]);

Both $user1s and $user2s are already arrays. Since both array contain objects you also might have to map them to scalar values (numbers or strings) to get the values you want to use.

So you could do something like this, if you want to map the names:

$hiredUsernames = array_map(
    function ($user) {
        return $user->name;
    },
    $user1s
);
// The result will be something like: ['Max', 'Jane', ...]

->dataset('Hired', $hiredUsernames)


问:
Combinations with repetition of letters with weight from list
I have four letters with different weights as

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
</code>```

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

```<code>comb_w2 = ['CC','NN','NC','O','S']
</code>```

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

答:
Create all combinations of the letters and use filter function to remove all combinations with combined weight not equal to 2.

```<code>from itertools import combinations_with_replacement
letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
y=dict(zip(letters,weights_of_l))   #Creates a dict of the two list letters
#and weights_of_l
print(list(map(lambda x:''.join(x),filter(lambda
x:y[x[0]]+y[x[1]]==2,combinations_with_replacement(letters,2)))))
</code>```

Or you can initially filter all letters in the letters list to include those which has weight less than 2 or the weight you require and then create all combinations.

Body:
I have four letters with different weights as

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

comb_w2 = ['CC','NN','NC','O','S']

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

Body:
Create all combinations of the letters and use filter function to remove all combinations with combined weight not equal to 2.

from itertools import combinations_with_replacement
letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
y=dict(zip(letters,weights_of_l))   #Creates a dict of the two list letters
#and weights_of_l
print(list(map(lambda x:''.join(x),filter(lambda
x:y[x[0]]+y[x[1]]==2,combinations_with_replacement(letters,2)))))

Or you can initially filter all letters in the letters list to include those which has weight less than 2 or the weight you require and then create all combinations.


问:
Pycharm - no log file is generated when running from Run/Debug config
I have Pycharm Community Edition 2017.2 for Windows. I've set up a simple logger like this.

```<code>def configure_logging():
    logger = logging.getLogger("debuglogger")
    logger.setLevel(logging.DEBUG)
    # create a file handler
    filepath = join(getcwd(), 'debug.log')
    file_handler = logging.FileHandler(filepath, mode='w', encoding='UTF-8')
    file_handler.setLevel(logging.DEBUG)
    # create a logging format
    formatter = logging.Formatter(
        '[%(levelname).3s][%(module)20.20s:%(funcName)-20.20s]-> %(message)s')
    file_handler.setFormatter(formatter)
    # add the handler to the logger
    logger.addHandler(file_handler)
    return logger
</code>```

main.py

```<code>if __name__ == "__main__":
    # configure the logger
    logger = configure_logging()
    logger.info("logging configured\n")
</code>```

If I run main.py from PyCharm's Run/Debug option then the log file is not created. But, if I run the script from a terminal window in PyCharm then the log file is generated. What do I need to do to make loggging work with the Run/Debug window? As you can see I have give the full path to the log file but it still doesn't work.

答:
You can set the "running directory" per run or per project.
Per run:   run -> edit configurations -> add run/debug configuration for your script

You can also set a default option under "defaults"

Per project: file -> settings -> build, execution, deployment -> console -> python console

Body:
I have Pycharm Community Edition 2017.2 for Windows. I've set up a simple logger like this.

def configure_logging():
    logger = logging.getLogger("debuglogger")
    logger.setLevel(logging.DEBUG)
    # create a file handler
    filepath = join(getcwd(), 'debug.log')
    file_handler = logging.FileHandler(filepath, mode='w', encoding='UTF-8')
    file_handler.setLevel(logging.DEBUG)
    # create a logging format
    formatter = logging.Formatter(
        '[%(levelname).3s][%(module)20.20s:%(funcName)-20.20s]-> %(message)s')
    file_handler.setFormatter(formatter)
    # add the handler to the logger
    logger.addHandler(file_handler)
    return logger

main.py

if __name__ == "__main__":
    # configure the logger
    logger = configure_logging()
    logger.info("logging configured\n")

If I run main.py from PyCharm's Run/Debug option then the log file is not created. But, if I run the script from a terminal window in PyCharm then the log file is generated. What do I need to do to make loggging work with the Run/Debug window? As you can see I have give the full path to the log file but it still doesn't work.


问:
chaining c# async / await tasks, recreating them as they complete
Aesthetic question really.

Given this code (polling unavoidable):

```<code>protected override async Task ExecuteAsync(CancellationToken ct)
{
    // move the loop here somehow?
    await Task.WhenAll(
        Task.Run(async () => await this.PollA(ct), ct),
        Task.Run(async () => await this.PollB(ct), ct),
        Task.Run(async () => await this.PollC(ct), ct))
        .ConfigureAwait(false);
}
</code>```

the polling methods look like this at the moment, each one has a different delay.

```<code>private async Task Poll(CancellationToken ct)
{
    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(Math.Max(1000, CONFIGA), ct);
        this._logger.StartAction("poll A status");
        this._logger.StopAction("poll A status");
    }
}
</code>```

Is there a way to structure a continuation that removes the loop in each of the Poll methods

```<code>private async Task Poll(CancellationToken ct)
{
    await Task.Delay(Math.Max(1000, CONFIGA), ct);
    this._logger.StartAction("poll A status");
    this._logger.StopAction("poll A status");
}
</code>```

This might not even be the right pattern, but it seems better than having three infinite loops.

```<code>Task.WhenAny([A,B,C]) =>
// recreate any complete task as soon as it returns
// and await the new "continuation"?
</code>```

答:
You can use Task.WhenAny like this:

```<code>private async Task<Tuple<string, int>> Poll(string type, int delay, CancellationToken ct) {
    await Task.Delay(Math.Max(1000, delay), ct);
    Console.WriteLine($"poll {type} status");
    // return input arguments back
    return Tuple.Create(type, delay);
}

private async Task PollAll(CancellationToken ct) {
    var tasks = new []
    {
        Poll("A", 3000, ct),
        Poll("B", 2000, ct),
        Poll("C", 1000, ct)
    };
    while (!ct.IsCancellationRequested) {
        var completed = await Task.WhenAny(tasks);
        var index = Array.IndexOf(tasks, completed);
        // await to throw exceptions if any
        await completed;
        // replace with new task with the same arguments
        tasks[index] = Poll(completed.Result.Item1, completed.Result.Item2, ct);
    }
}
</code>```

Body:
Aesthetic question really.

Given this code (polling unavoidable):

protected override async Task ExecuteAsync(CancellationToken ct)
{
    // move the loop here somehow?
    await Task.WhenAll(
        Task.Run(async () => await this.PollA(ct), ct),
        Task.Run(async () => await this.PollB(ct), ct),
        Task.Run(async () => await this.PollC(ct), ct))
        .ConfigureAwait(false);
}

the polling methods look like this at the moment, each one has a different delay.

private async Task Poll(CancellationToken ct)
{
    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(Math.Max(1000, CONFIGA), ct);
        this._logger.StartAction("poll A status");
        this._logger.StopAction("poll A status");
    }
}

Is there a way to structure a continuation that removes the loop in each of the Poll methods

private async Task Poll(CancellationToken ct)
{
    await Task.Delay(Math.Max(1000, CONFIGA), ct);
    this._logger.StartAction("poll A status");
    this._logger.StopAction("poll A status");
}

This might not even be the right pattern, but it seems better than having three infinite loops.

Task.WhenAny([A,B,C]) =>
// recreate any complete task as soon as it returns
// and await the new "continuation"?

Body:
You can use Task.WhenAny like this:

private async Task<Tuple<string, int>> Poll(string type, int delay, CancellationToken ct) {
    await Task.Delay(Math.Max(1000, delay), ct);
    Console.WriteLine($"poll {type} status");
    // return input arguments back
    return Tuple.Create(type, delay);
}

private async Task PollAll(CancellationToken ct) {
    var tasks = new []
    {
        Poll("A", 3000, ct),
        Poll("B", 2000, ct),
        Poll("C", 1000, ct)
    };
    while (!ct.IsCancellationRequested) {
        var completed = await Task.WhenAny(tasks);
        var index = Array.IndexOf(tasks, completed);
        // await to throw exceptions if any
        await completed;
        // replace with new task with the same arguments
        tasks[index] = Poll(completed.Result.Item1, completed.Result.Item2, ct);
    }
}


问:
Java and windows?

Possible Duplicates:

  Compiling a java program into an exe

  How can I convert my java program to an .exe file ?

hi everyone . there are many programs such intellij idea or jedit which they have written in JAVA ,
How they have compiled the code into the exe file ?
How can ,I compile my java code to exe file and run it on windows?
And Why javac give us class file ? what is it ?

答:
mkoryak took care of how to create an .exe for a Java program, but let me address "What is a Class file"?

In general, you don't have to compile Java down to byte code in the form of an exe (or anything else). You compile .java files into .class files. These files can't be run by an OS directly - rather, they are run by the Java Virtual Machine (JVM). The JVM is essentially a layer between your Java program and the underlying OS. The JVM will, on your behalf, interpret your .class files and pass the instructions contained in them to the underlying OS (Windows, OS X, Linux, etc).

So what does this do for you?

For one, it makes Java a little slower than other languages that are compiled right down to byte code. This was initially a big knock against Java but, as JVM interpreters have gotten better and people have migrated to slower platforms (i.e. Web Apps), this minor latency issue has become less and less of a problem.

On the flip side, however, you can write your Java code for a single OS - the JVM. You don't need to write one version of your app that targets Windows and another that targets OS X, and another, and another... Rather, you write one version of your application and you target that single OS (the JVM). The fact that there are versions of the JVM for every major OS out there means that, as soon as you write a Java program, you can run it on any platform (in theory, anyway).

That's one of the really cool things about Java, and also the meaning behind the often-heard tagline: "Write once, run anywhere."

So that's what the .class files are all about.

In Java, you write .java files and use a Java compiler (such as javac) to create .class files. These .class files are then run by a Java runtime (such as java), which executes your program on the JVM.

I hope that helps and, maybe, you don't need to compile your Java program down to an exe, at all.

ContentLicense: CC BY-SA 2.5

Title: Java and windows?


问:
Removing width styling from certain tabs in shiny
I have the following ui.R file:

```<code>library("shiny")
library("plotly")
library("shinythemes")
library("shinyjs")

shinyUI <- fluidPage(title = "LoL Analysis", theme = shinytheme('sandstone'),

            tags$head(
            tags$link(rel = "stylesheet", type = "text/css", href = "style.css")
            ),

             navbarPage(strong("League of Legends"),
               tabPanel("Project Overview"),
               tabPanel("Player Analysis",
                 sidebarLayout(
                   sidebarPanel(
                     selectInput(inputId = "role",
                       label = "Choose a role:",
                       choice = c("Top", "Jungle","Middle", "ADC", "Support",
                       selected = "Middle")),
                     br(),
                     uiOutput("firstdropdown"),
                     br(),
                     uiOutput("seconddropdown")
                   ),
                   mainPanel(
                     h2("Overview"),
                     p("Some long paragraph")

                   )
                 )
               ),
               tabPanel("How to win more games?", class =  "two",
                        mainPanel(
                          h2("Overview"),
                          p("Some long paragraph"),
                        )),
               tabPanel("Sources/Contact Us")
             )
)
</code>```

And here is the style.css:

```<code>.col-sm-8{
    width: 100%;
}
h2{
    color: white;
    background: slategray;
    padding: 10px;
}
</code>```

The problem I am having is that because I have a sidebar layout under the tab "Player Analysis", I do not want the width to be 100%. (Just the default width for the main panel is fine). However, for the "Project Overview" and the "How to win more tab" Ill like the width to be 100% because there are no side panels. I don't know much about CSS, but I tried create a class called "two" and tried two.col-sm-8{} in CSS instead, which did not work. Any help is really appreciated!

答:
Hi you have some different choices. Your problem comes from that mainPanel creates a div with class col-sm-8.

The first solution would be to skip the mainPanel altogether and just put the content in a fluidRow for example this will give the the full width of the screen.

The second solution if you want to keep mainPanel but want to use the whole width of the screen anyway and you know the app will almost always run on a big screen you can add the class col-md-12 to the mainPanel this class will overrule the col-sm-8 class on medium to large screens and will give you the whole width of the screen. I have implemented both in the example below

```<code>library(shinythemes)
library(shinyjs)
library(shiny)
ui <- fluidPage(title = "LoL Analysis", theme = shinytheme('sandstone'),

                     tags$head(
                       tags$link(rel = "stylesheet", type = "text/css", href = "style.css")
                     ),

                     navbarPage(strong("League of Legends"),
                                tabPanel("Project Overview",
                                         fluidRow(
                                           div("sometext")
                                         )),
                                tabPanel("Player Analysis",
                                         sidebarLayout(
                                           sidebarPanel(
                                             selectInput(inputId = "role",
                                                         label = "Choose a role:",
                                                         choice = c("Top", "Jungle","Middle", "ADC", "Support",
                                                                    selected = "Middle")),
                                             br(),
                                             uiOutput("firstdropdown"),
                                             br(),
                                             uiOutput("seconddropdown")
                                           ),
                                           mainPanel(
                                             h2("Overview"),
                                             p("Some long paragraph")

                                           )
                                         )
                                ),
                                tabPanel("How to win more games?", class =  "two",
                                         mainPanel(
                                           class = "col-md-12 col-sm-12",
                                           h2("Overview"),
                                           p("Some long paragraph")
                                         )),
                                tabPanel("Sources/Contact Us")
                     )
)

srv <- function(input, output){

}

shinyApp(ui, srv)
</code>```

Hope this helps!

Body:
I have the following ui.R file:

library("shiny")
library("plotly")
library("shinythemes")
library("shinyjs")

shinyUI <- fluidPage(title = "LoL Analysis", theme = shinytheme('sandstone'),

            tags$head(
            tags$link(rel = "stylesheet", type = "text/css", href = "style.css")
            ),

             navbarPage(strong("League of Legends"),
               tabPanel("Project Overview"),
               tabPanel("Player Analysis",
                 sidebarLayout(
                   sidebarPanel(
                     selectInput(inputId = "role",
                       label = "Choose a role:",
                       choice = c("Top", "Jungle","Middle", "ADC", "Support",
                       selected = "Middle")),
                     br(),
                     uiOutput("firstdropdown"),
                     br(),
                     uiOutput("seconddropdown")
                   ),
                   mainPanel(
                     h2("Overview"),
                     p("Some long paragraph")

                   )
                 )
               ),
               tabPanel("How to win more games?", class =  "two",
                        mainPanel(
                          h2("Overview"),
                          p("Some long paragraph"),
                        )),
               tabPanel("Sources/Contact Us")
             )
)

And here is the style.css:

.col-sm-8{
    width: 100%;
}
h2{
    color: white;
    background: slategray;
    padding: 10px;
}

The problem I am having is that because I have a sidebar layout under the tab "Player Analysis", I do not want the width to be 100%. (Just the default width for the main panel is fine). However, for the "Project Overview" and the "How to win more tab" Ill like the width to be 100% because there are no side panels. I don't know much about CSS, but I tried create a class called "two" and tried two.col-sm-8{} in CSS instead, which did not work. Any help is really appreciated!

Body:
Hi you have some different choices. Your problem comes from that mainPanel creates a div with class col-sm-8.

The first solution would be to skip the mainPanel altogether and just put the content in a fluidRow for example this will give the the full width of the screen.

The second solution if you want to keep mainPanel but want to use the whole width of the screen anyway and you know the app will almost always run on a big screen you can add the class col-md-12 to the mainPanel this class will overrule the col-sm-8 class on medium to large screens and will give you the whole width of the screen. I have implemented both in the example below

library(shinythemes)
library(shinyjs)
library(shiny)
ui <- fluidPage(title = "LoL Analysis", theme = shinytheme('sandstone'),

                     tags$head(
                       tags$link(rel = "stylesheet", type = "text/css", href = "style.css")
                     ),

                     navbarPage(strong("League of Legends"),
                                tabPanel("Project Overview",
                                         fluidRow(
                                           div("sometext")
                                         )),
                                tabPanel("Player Analysis",
                                         sidebarLayout(
                                           sidebarPanel(
                                             selectInput(inputId = "role",
                                                         label = "Choose a role:",
                                                         choice = c("Top", "Jungle","Middle", "ADC", "Support",
                                                                    selected = "Middle")),
                                             br(),
                                             uiOutput("firstdropdown"),
                                             br(),
                                             uiOutput("seconddropdown")
                                           ),
                                           mainPanel(
                                             h2("Overview"),
                                             p("Some long paragraph")

                                           )
                                         )
                                ),
                                tabPanel("How to win more games?", class =  "two",
                                         mainPanel(
                                           class = "col-md-12 col-sm-12",
                                           h2("Overview"),
                                           p("Some long paragraph")
                                         )),
                                tabPanel("Sources/Contact Us")
                     )
)

srv <- function(input, output){

}

shinyApp(ui, srv)

Hope this helps!


问:
Reference External Javascript Library in .html files with angular-cli
Receiving error 404 referencing a legacy javascript library in angular application. My question is why?

These are the characteristics of my build environment

Angular CLI: 1.6.0

Node: 7.10.0

OS: win32 x64

Angular: 4.4.6

The image below shows the  tag in the index.html referencing the chart.js javascript file that was installed using node. I have checked the path and determined that the file is present at that location and would like to understand why I can't reference the javascript file directly in my html with the location in node_modules.

The image below shows the error that I receive trying to reference the javascript file in my html using the script tag

If a workaround is the answer, can the answer also contain the reason why the workaround is necessary using angular?

答:
This is possible using Angular Cli

Taking example of jssha js library

Step One

```<code>npm install jssha --save [using jssha for this demo]
If it is your own custom file place it in the scripts array of angular-cli.json skip this step 1
</code>```

Step two

```<code>Add the jssha scripts file in .angular-cli.json file
"scripts": [ "../node_modules/jssha/src/sha.js" ]
</code>```

Step three
     Adding a var in component to be used as a global variable

```<code>//using external js modules in Angular Component
declare var jsSHA: any; // place this above the component decorator
shaObj:any;
hash:string;
this.shaObj = new jsSHA("SHA-512", "TEXT");
this.shaObj.update("This is a Test");
this.hash = this.shaObj.getHash("HEX")
</code>```

Take a look @ this link. details for the same with typings and without it. I have used bootstrap and jquery with Angular in that project, you can check the repo too.

Working example

Body:
This is possible using Angular Cli

Taking example of jssha js library

Step One

npm install jssha --save [using jssha for this demo]
If it is your own custom file place it in the scripts array of angular-cli.json skip this step 1

Step two

Add the jssha scripts file in .angular-cli.json file
"scripts": [ "../node_modules/jssha/src/sha.js" ]

Step three
     Adding a var in component to be used as a global variable

//using external js modules in Angular Component
declare var jsSHA: any; // place this above the component decorator
shaObj:any;
hash:string;
this.shaObj = new jsSHA("SHA-512", "TEXT");
this.shaObj.update("This is a Test");
this.hash = this.shaObj.getHash("HEX")

Take a look @ this link. details for the same with typings and without it. I have used bootstrap and jquery with Angular in that project, you can check the repo too.

Working example


问:
Why creating an emptyRDD using parallelize method is not recommended?
I am learning apache- spark and trying to create an empty RDD.
I got the following ways to create an empty RDD:

```<code>1. JavaRDD<String> emptyRDD = sc.emptyRDD();
2. List<String> emptyList = new ArrayList<String>();
   JavaRDD<String> emptyParallelRDD = sc.parallelize(emptyList, 1);
</code>```

And the code works perfectly fine in both cases, no error and no exception.

But as of the documentation of parallelize method:

avoid using parallelize(Seq()) to create an empty RDD. Consider emptyRDD for an RDD with no partitions

for which i did not find any reason.
Any help, why shouldn't we use parallelize for creating emptyRDD?

答:
An EmptyRDD has zero partitions

```<code>sc.emptyRDD[Int].getNumPartitions
// Int = 0
</code>```

Whereas the following will have a default number of partitions with no data :

```<code>sc.parallelize(Seq[Int]()).getNumPartitions
// Int = 2
</code>```

My guess would be, in the first case, any job involving the empty RDD should be quicker because no partitions will result in no job getting executed at all.

For instance, saveAsTextFile will not generate a part file in the first case but would generate two empty part files in the second one.

```<code>scala> sc.emptyRDD[Int].saveAsTextFile("emptyRDDTest")

scala> sc.parallelize(Seq[Int]()).saveAsTextFile("emptySeqTest")

$ hdfs dfs -ls empty*
Found 1 items
hadoop          0 2017-12-07 02:38 emptyRDDTest/_SUCCESS
Found 3 items
hadoop          0 2017-12-07 02:39 emptySeqTest/_SUCCESS
hadoop          0 2017-12-07 02:39 emptySeqTest/part-00000
hadoop          0 2017-12-07 02:39 emptySeqTest/part-00001
</code>```

Body:
I am learning apache- spark and trying to create an empty RDD.
I got the following ways to create an empty RDD:

1. JavaRDD<String> emptyRDD = sc.emptyRDD();
2. List<String> emptyList = new ArrayList<String>();
   JavaRDD<String> emptyParallelRDD = sc.parallelize(emptyList, 1);

And the code works perfectly fine in both cases, no error and no exception.

But as of the documentation of parallelize method:

avoid using parallelize(Seq()) to create an empty RDD. Consider emptyRDD for an RDD with no partitions

for which i did not find any reason.
Any help, why shouldn't we use parallelize for creating emptyRDD?

Body:
An EmptyRDD has zero partitions

sc.emptyRDD[Int].getNumPartitions
// Int = 0

Whereas the following will have a default number of partitions with no data :

sc.parallelize(Seq[Int]()).getNumPartitions
// Int = 2

My guess would be, in the first case, any job involving the empty RDD should be quicker because no partitions will result in no job getting executed at all.

For instance, saveAsTextFile will not generate a part file in the first case but would generate two empty part files in the second one.

scala> sc.emptyRDD[Int].saveAsTextFile("emptyRDDTest")

scala> sc.parallelize(Seq[Int]()).saveAsTextFile("emptySeqTest")

$ hdfs dfs -ls empty*
Found 1 items
hadoop          0 2017-12-07 02:38 emptyRDDTest/_SUCCESS
Found 3 items
hadoop          0 2017-12-07 02:39 emptySeqTest/_SUCCESS
hadoop          0 2017-12-07 02:39 emptySeqTest/part-00000
hadoop          0 2017-12-07 02:39 emptySeqTest/part-00001


问:
How to echo out decrypt data in PHP
First, i have use aes_encrypt to encrypt the password

Then i have use aes_decrypt to decrypt the password

The issue is when i try to echo out the data in a table using
<?php echo $row['pass'];?>,  there'll be an error

"Undefined index: pass in"

SQL insert

insert into username (userName,pass) values('$userName',
  aes_encrypt('$pass','k'))

SQL select

SELECT UserNameID,userName,aes_decrypt(pass,'k') from username

What went wrong?

答:
Don't you need to use an alias here?

```<code>SELECT aes_decrypt(pass, 'k') AS pass_decrypted FROM ...
</code>```

And then access it with

```<code>echo $row['pass_decrypted'];
</code>```

Title: How to echo out decrypt data in PHP

Body:
Don't you need to use an alias here?

SELECT aes_decrypt(pass, 'k') AS pass_decrypted FROM ...

And then access it with

echo $row['pass_decrypted'];


问:
Akka http redirect but change method from POST to GET
I have endpoint using POST method ( registering token for example ), after job done I want to redirect client to "/" url, but using GET not POST.
How to achieve this ?

For now I have:

```<code>redirect("/", StatusCodes.PermanentRedirect)
</code>```

答:
What you want in this case is not a redirect with status code PermanentRedirect, but rather SeeOther (303). So you would have instead: redirect("/", StatusCodes.SeeOther)

You can check in RFC 7231, section 6.4.4: 303 See Other that this guarantees the behavior you describe.

Body:
I have endpoint using POST method ( registering token for example ), after job done I want to redirect client to "/" url, but using GET not POST.
How to achieve this ?

For now I have:

redirect("/", StatusCodes.PermanentRedirect)


问:
AND/OR operator between numbers in Python
How do and/or operators work between numbers (or even strings)?

```<code>5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
</code>```

How does the and operator work in such cases?

答:
When and is used with integers, it will give you the last value if all value are non-zero, or zero if there's at least one.

```<code>1 and 2 and 3 #3
1 and 0 and 3 #0
</code>```

Body:
How do and/or operators work between numbers (or even strings)?

5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21

How does the and operator work in such cases?

Body:
When and is used with integers, it will give you the last value if all value are non-zero, or zero if there's at least one.

1 and 2 and 3 #3
1 and 0 and 3 #0


问:
require()'ing a CoffeeScript file from a JavaScript file or REPL
I'm using Node.js and wanting to incorporate CoffeeScript into my workflow. I have two use-cases:

I want to be able to write JavaScript files which require() CoffeeScript modules

I want to be able to load CoffeeScript modules from within the node REPL

For case #1: I can just compile from .coffee to .js and require() the .js module, as a workaround.

For case #2: Right now I'm eval()ing the output of coffee-script.compile().

Is there a better, more unified way to do this?

答:
The coffee-script module registers its extension once required.

```<code>$ echo 'console.log "works"' > module.coffee

$ echo '
> require("coffee-script")
> require("./module")
> ' > test.js

$ node test.js
works

$ node
> require('coffee-script'); require('./module')
works
{}
</code>```

Edit: This behaviour has changed with the relase of CoffeeScript 1.7.0. Now you need to do:

```<code>require('coffee-script/register');
</code>```

Body:
The coffee-script module registers its extension once required.

$ echo 'console.log "works"' > module.coffee

$ echo '
> require("coffee-script")
> require("./module")
> ' > test.js

$ node test.js
works

$ node
> require('coffee-script'); require('./module')
works
{}

Edit: This behaviour has changed with the relase of CoffeeScript 1.7.0. Now you need to do:

require('coffee-script/register');


问:
Debian: gpg: error reading '[stdin]': General error
I'm creating a new workspace for a project and use Debian 9 inside the VB in a MacBook Pro, El Capitan. For the Java 8, I have the instructions like,

```<code>--------------------------------------------------------------------
Create /etc/apt/sources.list.d/java8.list with this content:

deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main
deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main
--------------------------------------------------------------------
</code>```

So, I went to the terminal and type,

```<code>sudo gedit /etc/apt/sources.list.d/java8.list
</code>```

Then, I paste the mentioned content into the file, saved and closed. Afterwards, when I execute the command,

```<code>apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
</code>```

I get this error stack,

```<code>apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
Executing: /tmp/apt-key-gpghome.Nrr9YiY2yQ/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
gpg: failed to start the dirmngr '/usr/bin/dirmngr': No such file or directory
gpg: connecting dirmngr at '/run/user/1000/gnupg/d.efsrb3uyo6fh5yhoikm7bucx/S.dirmngr' failed: No such file or directory
gpg: keyserver receive failed: No dirmngr
</code>```

I use the command apt-get install dirmngr to install the dirmngr and tried again in the terminal. This time I have the error,

```<code>Executing: /tmp/apt-key-gpghome.A4f5OjYwxw/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
gpg: key C2518248EEA14886: public key "Launchpad VLC" imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg: no writable keyring found: Not found
gpg: error reading '[stdin]': General error
gpg: import from '[stdin]' failed: General error
gpg: Total number processed: 0
</code>```

I have next to zero knowledge about Linux/ Debian, so, what to do in this context? It seems that the dirmngr issue is gone for now

答:
Try running command with sudo

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886

Body:
I'm creating a new workspace for a project and use Debian 9 inside the VB in a MacBook Pro, El Capitan. For the Java 8, I have the instructions like,

--------------------------------------------------------------------
Create /etc/apt/sources.list.d/java8.list with this content:

deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main
deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main
--------------------------------------------------------------------

So, I went to the terminal and type,

sudo gedit /etc/apt/sources.list.d/java8.list

Then, I paste the mentioned content into the file, saved and closed. Afterwards, when I execute the command,

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886

I get this error stack,

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
Executing: /tmp/apt-key-gpghome.Nrr9YiY2yQ/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
gpg: failed to start the dirmngr '/usr/bin/dirmngr': No such file or directory
gpg: connecting dirmngr at '/run/user/1000/gnupg/d.efsrb3uyo6fh5yhoikm7bucx/S.dirmngr' failed: No such file or directory
gpg: keyserver receive failed: No dirmngr

I use the command apt-get install dirmngr to install the dirmngr and tried again in the terminal. This time I have the error,

Executing: /tmp/apt-key-gpghome.A4f5OjYwxw/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
gpg: key C2518248EEA14886: public key "Launchpad VLC" imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg: no writable keyring found: Not found
gpg: error reading '[stdin]': General error
gpg: import from '[stdin]' failed: General error
gpg: Total number processed: 0

I have next to zero knowledge about Linux/ Debian, so, what to do in this context? It seems that the dirmngr issue is gone for now


问:
How to find city name from latitude and longitude in Postgresql?
I have a database which has latitudes and longitudes of various properties stored. I want to find out, which city does each of these properties belong to (all properties are in the US). </p>

答:
Talking about Postgresql, first of all you need to get a data of US cities boundaries shape file.  Possible sites are

```<code>https://www.census.gov/geo/maps-data/data/tiger.html
https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html
https://catalog.data.gov/dataset?tags=cities
</code>```

After that import data into postgres. I am assuming that your properties data is already stored in postgres. Make sure the SRID geometry type of cities boundaries is 4326. if not, you can convert it easily with ST_transform function.

Finally, to check which city some specific lat/long  falls in, you need to convert the lat/long into point geometry and check against the cities data. e.g it would be some thing like this

```<code>SELECT c.city_name FROM cities_boundaries AS c, properties AS p
WHERE ST_CONTAINS(c.geom, ST_SetSRID(ST_MakePoint(p.longitude, p.latitude), 4326))
</code>```

Body:
Talking about Postgresql, first of all you need to get a data of US cities boundaries shape file.  Possible sites are

https://www.census.gov/geo/maps-data/data/tiger.html
https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html
https://catalog.data.gov/dataset?tags=cities

After that import data into postgres. I am assuming that your properties data is already stored in postgres. Make sure the SRID geometry type of cities boundaries is 4326. if not, you can convert it easily with ST_transform function.

Finally, to check which city some specific lat/long  falls in, you need to convert the lat/long into point geometry and check against the cities data. e.g it would be some thing like this

SELECT c.city_name FROM cities_boundaries AS c, properties AS p
WHERE ST_CONTAINS(c.geom, ST_SetSRID(ST_MakePoint(p.longitude, p.latitude), 4326))


问:
Planning calendar default one month view on mobile
Currently, I am developing an app in which users should be able to pick a date from the calendar. It works pretty much ok on desktop and also on mobile phone.
My problem is that the 'One Month' view is not reachable from mobile phones. What I need is to be able to have a similar view to the one shown below from my mobile phone.

I have already tried to PlanningCalendarView with intervalType="Month" but it just made it worse cause it shows the same appointments associated.

答:
The “1 Month” option is not supported as intervalType for PlanningCalendarView.

But you can combine both your custom views ("Day" , "Week") and the already built in view for “1 Month”
by using the “builtInViews” property from PlanningCalendar.
Something like:

```<code>...
<PlanningCalendar
    id="PC1"
    startDate="{path: '/startDate'}"
    rows="{path: '/people'}"

    builtInViews="One Month"
...
<views>
    <PlanningCalendarView

...
</code>```

Please see also this Plunkr.

ContentLicense: CC BY-SA 4.0

Body:
The “1 Month” option is not supported as intervalType for PlanningCalendarView.

But you can combine both your custom views ("Day" , "Week") and the already built in view for “1 Month”
by using the “builtInViews” property from PlanningCalendar.
Something like:

...
<PlanningCalendar
    id="PC1"
    startDate="{path: '/startDate'}"
    rows="{path: '/people'}"

    builtInViews="One Month"
...
<views>
    <PlanningCalendarView

...

Please see also this Plunkr.


问:
Vertx Websockets starts encoding-decoding in loop after connecting second client
I have simple Vertx-based websocket chatting app. It consists of two parts MsgServerVerticle and MsgClientVerticle (source code below). So, if I am instantiating one server and only one client it looks like working normally. After second client connects, server starts trying to announce it to other clients. And things gonna weird. Log says that netty backed are encoding-decoding websocket frames continuously in loop. There is no difference what type of frames I am using, binary or text, issues are the same.
log screenshot here

What's wrong?

MsgClientVerticle Source code:

```<code>private Logger L;

private String eBusTag;
private String backwardTag;
private String targetHost;
private int port;
private String id;
private String path;

private EventBus eBus;

private HttpClient client;

public MsgClientVerticle(String eBusTag, String targetHost, int port, String path, String id, String backwardTag) {
    this.eBusTag = eBusTag;
    this.targetHost = targetHost;
    this.path = path;
    this.port = port;
    this.id = id;
    this.backwardTag = backwardTag;

    L = LoggerFactory.getLogger(eBusTag);
}

@Override
public void start(Future<Void> startFuture) throws Exception {
    L.info("Initializing client connection to " + targetHost + ":" + port + path);
    eBus = vertx.eventBus();

    try {

        client = vertx.createHttpClient();

        client.websocket(port, targetHost, path, webSock -> {
            L.info("Connected to " + targetHost + ":" + port + "/" + path);
            eBus.publish(backwardTag, Utils.msg("Connected"));
            webSock.binaryMessageHandler(buf -> {
                eBus.publish(backwardTag, Utils.bufToJson(buf));
            });
            eBus.consumer(eBusTag).handler(msg -> {
                JsonObject message = (JsonObject) msg.body();
                webSock.writeBinaryMessage(Utils.jsonToBuf(message));
            });
        });
    } catch (NullPointerException e) {
        L.error("Null Pointer: " + e.getLocalizedMessage());
        e.printStackTrace();
    }

    startFuture.complete();
}

@Override
public void stop(Future<Void> stopFuture) throws Exception {
    L.info("Connection to " + targetHost + ":" + port + "/" + path + " closed");
    client.close();
    stopFuture.complete();
}
</code>```

And MsgServerVerticle source:

```<code>private Logger L;

private String path;
private int port;
private String eBusTag;
private String backwardTag;

private HttpServer server;

private EventBus eBus;

private Set<ServerWebSocket> conns;

public MsgServerVerticle(int port, String eBusTag, String backwardTag) {
    this.port = port;
    this.eBusTag = eBusTag;
    this.backwardTag = backwardTag;

    conns = new ConcurrentSet<>();
    path = eBusTag;

    L = LoggerFactory.getLogger(eBusTag);

}

@Override
public void start(Future<Void> startFuture) throws Exception {
    eBus = vertx.eventBus();
    L.info("Initializing server instance at port " + port);

    server = vertx.createHttpServer();

    server.websocketHandler(webSock -> {

        if (!webSock.path().equals(path)) {

            webSock.reject();

        } else {

            conns.add(webSock);

            conns.forEach(sock -> {
                if (sock != webSock) {
                    sock.writeBinaryMessage(Utils.jsonToBuf(Utils.msg("SERVER: new client " + webSock.remoteAddress().toString())));
                }
            });

            eBus.publish(backwardTag, Utils.msg("SERVER: new client " + webSock.remoteAddress().toString()));

            webSock.binaryMessageHandler(buf -> {
                JsonObject msg = Utils.bufToJson(buf);
                conns.forEach(sock -> {
                    if (sock != webSock) {
                        sock.writeBinaryMessage(buf);
                    }
                });
                eBus.publish(backwardTag, msg);
            });

        }

    });

    server.listen(port);

    startFuture.complete();
}

@Override
public void stop(Future<Void> stopFuture) throws Exception {
    conns.forEach(sock -> {
        sock.writeFinalTextFrame("Server is shutting down...");
    });
    server.close();
    stopFuture.complete();
}
</code>```

答:
I wasn't able to reproduce your original problem. But I had to make a few changes in the first place to test it.

One change is in initialization of your server:

this.path = "/" + eBusTag;

Otherwise this check will always fail:

if (!webSock.path().equals(this.path)) {

Since websock.path() will always start with /, hence /anything=/=anything

Second, please take a look how I initialized the clients, and check if you do the same:

```<code>    final Vertx vertx = Vertx.vertx();

    vertx.deployVerticle(new MsgServerVerticle(8080,
            "ebus",
            "back"), new DeploymentOptions().setWorker(true), (r) -> {
        vertx.deployVerticle(new MsgClientVerticle("ebus",
                "127.0.0.1",
                8080,
                "/ebus",
                "a",
                "back"), new DeploymentOptions().setWorker(true), (r2) -> {
            vertx.deployVerticle(new MsgClientVerticle("ebus",
                    "127.0.0.1",
                    8080,
                    "/ebus",
                    "b",
                    "back"), new DeploymentOptions().setWorker(true), (r3) -> {
                System.out.println("Done");
            });
        });
    });
</code>```

And third, as far as I could understand, your Utils class is something you implemented. My implementation looks as follows:

```<code>public class Utils {
    public static Buffer jsonToBuf(final JsonObject message) {
        return message.toBuffer();
    }

    public static JsonObject bufToJson(final Buffer buf) {
        return buf.toJsonObject();
    }

    public static JsonObject msg(final String msg) {
        return new JsonObject("{\"value\":\"" + msg + "\"}");
    }
}
</code>```

Hope that helps pinpoint your problem.

Body:
I have simple Vertx-based websocket chatting app. It consists of two parts MsgServerVerticle and MsgClientVerticle (source code below). So, if I am instantiating one server and only one client it looks like working normally. After second client connects, server starts trying to announce it to other clients. And things gonna weird. Log says that netty backed are encoding-decoding websocket frames continuously in loop. There is no difference what type of frames I am using, binary or text, issues are the same.
log screenshot here

What's wrong?

MsgClientVerticle Source code:

private Logger L;

private String eBusTag;
private String backwardTag;
private String targetHost;
private int port;
private String id;
private String path;

private EventBus eBus;

private HttpClient client;

public MsgClientVerticle(String eBusTag, String targetHost, int port, String path, String id, String backwardTag) {
    this.eBusTag = eBusTag;
    this.targetHost = targetHost;
    this.path = path;
    this.port = port;
    this.id = id;
    this.backwardTag = backwardTag;

    L = LoggerFactory.getLogger(eBusTag);
}

@Override
public void start(Future<Void> startFuture) throws Exception {
    L.info("Initializing client connection to " + targetHost + ":" + port + path);
    eBus = vertx.eventBus();

    try {

        client = vertx.createHttpClient();

        client.websocket(port, targetHost, path, webSock -> {
            L.info("Connected to " + targetHost + ":" + port + "/" + path);
            eBus.publish(backwardTag, Utils.msg("Connected"));
            webSock.binaryMessageHandler(buf -> {
                eBus.publish(backwardTag, Utils.bufToJson(buf));
            });
            eBus.consumer(eBusTag).handler(msg -> {
                JsonObject message = (JsonObject) msg.body();
                webSock.writeBinaryMessage(Utils.jsonToBuf(message));
            });
        });
    } catch (NullPointerException e) {
        L.error("Null Pointer: " + e.getLocalizedMessage());
        e.printStackTrace();
    }

    startFuture.complete();
}

@Override
public void stop(Future<Void> stopFuture) throws Exception {
    L.info("Connection to " + targetHost + ":" + port + "/" + path + " closed");
    client.close();
    stopFuture.complete();
}

And MsgServerVerticle source:

private Logger L;

private String path;
private int port;
private String eBusTag;
private String backwardTag;

private HttpServer server;

private EventBus eBus;

private Set<ServerWebSocket> conns;

public MsgServerVerticle(int port, String eBusTag, String backwardTag) {
    this.port = port;
    this.eBusTag = eBusTag;
    this.backwardTag = backwardTag;

    conns = new ConcurrentSet<>();
    path = eBusTag;

    L = LoggerFactory.getLogger(eBusTag);

}

@Override
public void start(Future<Void> startFuture) throws Exception {
    eBus = vertx.eventBus();
    L.info("Initializing server instance at port " + port);

    server = vertx.createHttpServer();

    server.websocketHandler(webSock -> {

        if (!webSock.path().equals(path)) {

            webSock.reject();

        } else {

            conns.add(webSock);

            conns.forEach(sock -> {
                if (sock != webSock) {
                    sock.writeBinaryMessage(Utils.jsonToBuf(Utils.msg("SERVER: new client " + webSock.remoteAddress().toString())));
                }
            });

            eBus.publish(backwardTag, Utils.msg("SERVER: new client " + webSock.remoteAddress().toString()));

            webSock.binaryMessageHandler(buf -> {
                JsonObject msg = Utils.bufToJson(buf);
                conns.forEach(sock -> {
                    if (sock != webSock) {
                        sock.writeBinaryMessage(buf);
                    }
                });
                eBus.publish(backwardTag, msg);
            });

        }

    });

    server.listen(port);

    startFuture.complete();
}

@Override
public void stop(Future<Void> stopFuture) throws Exception {
    conns.forEach(sock -> {
        sock.writeFinalTextFrame("Server is shutting down...");
    });
    server.close();
    stopFuture.complete();
}

Body:
I wasn't able to reproduce your original problem. But I had to make a few changes in the first place to test it.

One change is in initialization of your server:

this.path = "/" + eBusTag;

Otherwise this check will always fail:

if (!webSock.path().equals(this.path)) {

Since websock.path() will always start with /, hence /anything=/=anything

Second, please take a look how I initialized the clients, and check if you do the same:

    final Vertx vertx = Vertx.vertx();

    vertx.deployVerticle(new MsgServerVerticle(8080,
            "ebus",
            "back"), new DeploymentOptions().setWorker(true), (r) -> {
        vertx.deployVerticle(new MsgClientVerticle("ebus",
                "127.0.0.1",
                8080,
                "/ebus",
                "a",
                "back"), new DeploymentOptions().setWorker(true), (r2) -> {
            vertx.deployVerticle(new MsgClientVerticle("ebus",
                    "127.0.0.1",
                    8080,
                    "/ebus",
                    "b",
                    "back"), new DeploymentOptions().setWorker(true), (r3) -> {
                System.out.println("Done");
            });
        });
    });

And third, as far as I could understand, your Utils class is something you implemented. My implementation looks as follows:

public class Utils {
    public static Buffer jsonToBuf(final JsonObject message) {
        return message.toBuffer();
    }

    public static JsonObject bufToJson(final Buffer buf) {
        return buf.toJsonObject();
    }

    public static JsonObject msg(final String msg) {
        return new JsonObject("{\"value\":\"" + msg + "\"}");
    }
}

Hope that helps pinpoint your problem.


问:
Django Rest Framework Nested Routes - PK alternatives
I am using drf-nested-routers to nest my resources and everything is working well. I would like, however, to use something other than the pk to refer to a parent object.

What I currently have is:

api/movies/4/scenes - generates a list of scenes from movie with pk=4.

What I would like is:

api/movies/ghost-busters/scenes - where the identifier is movie.title instead of movie.pk

Any suggestions?

Thanks

答:
you can use slug for the url you want to make "api/movies/ghost-busters/scenes"

at first you have to make model with slugField eg.

```<code>class Blog(models.Model):
    qoute = models.CharField(max_length=30)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.qoute)
        super(Blog, self).save(*args, **kwargs)
</code>```

during the saving model it will create a slug by "qoute" and save to the column "slug"

make your urls.py entry

```<code>url(r'^api/movies/(?P<slug>[\w-]+)/scenes/$', 'myapp.views.blog_detail', name='blog_detail'),
</code>```

then for the drf you have set lookup_field in the serializer and view also.
N.B: you can user ModelSerializer or Serializer or HyperlinkSerialzer as you wish..

```<code>class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ('quote', 'slug',)
        lookup_field = 'slug'
</code>```

and the views..

```<code>class blog_detail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    lookup_field = 'slug'
</code>```

Body:
you can use slug for the url you want to make "api/movies/ghost-busters/scenes"

at first you have to make model with slugField eg.

class Blog(models.Model):
    qoute = models.CharField(max_length=30)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.qoute)
        super(Blog, self).save(*args, **kwargs)

during the saving model it will create a slug by "qoute" and save to the column "slug"

make your urls.py entry

url(r'^api/movies/(?P<slug>[\w-]+)/scenes/$', 'myapp.views.blog_detail', name='blog_detail'),

then for the drf you have set lookup_field in the serializer and view also.
N.B: you can user ModelSerializer or Serializer or HyperlinkSerialzer as you wish..

class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ('quote', 'slug',)
        lookup_field = 'slug'

and the views..

class blog_detail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    lookup_field = 'slug'


问:
What's Is the Best File Format for Configuration Files
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.

What format would be the best for these config files?

Here is my quantification of best:

Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.

Remains easily read by humans even when there are a large amount of entries

Is a widely used standard, no custom formats

Succinctness is appreciated

I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.

答:
How about an INI file format?  It's a de facto configuration file standard, and PHP has a built-in parser for that format:

parse_ini_file

OwnerDisplayName: macinjosh

LastEditorDisplayName: InSciTek Jeff

OwnerDisplayName: Jeff


问:
Windows Console and Qt Unicode Text
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}
</code>```

答:
You're making mistakes in both phases - input and output.

Input

You can't write

QString szqLine = QString::fromUtf8("abc áéüóöú őű");

and hope to have a valid Unicode string as the result because this is not guaranteed by the C++ Standard (see SO question C++ source in unicode for details).

You can check you don't have a valid Unicode string using code like this

```<code>foreach(QChar ch, szqLine) {
  qout << ch.unicode();
}
</code>```

If szqLine were a valid Unicode string you would get a list of Unicode code points of characters in the string. In case of your string you get no output.

The proper way to do it is like this

```<code>QChar const chars[] = { 'a', 'b', 'c', ' ', 255, 233, 252, 243, 246, 250, ' ', 337, 369};
QString s(&chars[0], sizeof(chars)/sizeof(QChar));
</code>```

See QString::QString ( const QChar * unicode, int size ), QChar::QChar ( int code ) Qt functions and Full UTF-8 Character Map for Unicode code points of your characters.

Output

Windows console uses one specific code page for input and another one for output (see Console Code Pages) when you use standard input/output mechanisms. This constraints the set of characters you can enter and display to these present in the current code page. However you can use WriteConsole Win API function to output any Unicode string encoded in UTF-16. There's no way you can avoid using Win API function here because there's no Qt API that could be used here. Below is complete example showing how to display characters from your question on the Windows console.

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextCodec>

#include <Windows.h>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QChar const chars[] = { 'a', 'b', 'c', ' ', 255, 233, 252, 243, 246, 250, ' ', 337, 369};
    QString s(&chars[0], sizeof(chars)/sizeof(QChar));

    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), s.utf16().constData(), s.size(), NULL, NULL);

    return app.exec();
}
</code>```

Title: Windows Console and Qt Unicode Text

Body:
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}

Body:
You're making mistakes in both phases - input and output.

Input

You can't write

QString szqLine = QString::fromUtf8("abc áéüóöú őű");

and hope to have a valid Unicode string as the result because this is not guaranteed by the C++ Standard (see SO question C++ source in unicode for details).

You can check you don't have a valid Unicode string using code like this

foreach(QChar ch, szqLine) {
  qout << ch.unicode();
}

If szqLine were a valid Unicode string you would get a list of Unicode code points of characters in the string. In case of your string you get no output.

The proper way to do it is like this

QChar const chars[] = { 'a', 'b', 'c', ' ', 255, 233, 252, 243, 246, 250, ' ', 337, 369};
QString s(&chars[0], sizeof(chars)/sizeof(QChar));

See QString::QString ( const QChar * unicode, int size ), QChar::QChar ( int code ) Qt functions and Full UTF-8 Character Map for Unicode code points of your characters.

Output

Windows console uses one specific code page for input and another one for output (see Console Code Pages) when you use standard input/output mechanisms. This constraints the set of characters you can enter and display to these present in the current code page. However you can use WriteConsole Win API function to output any Unicode string encoded in UTF-16. There's no way you can avoid using Win API function here because there's no Qt API that could be used here. Below is complete example showing how to display characters from your question on the Windows console.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextCodec>

#include <Windows.h>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QChar const chars[] = { 'a', 'b', 'c', ' ', 255, 233, 252, 243, 246, 250, ' ', 337, 369};
    QString s(&chars[0], sizeof(chars)/sizeof(QChar));

    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), s.utf16().constData(), s.size(), NULL, NULL);

    return app.exec();
}


问:
How to get element-wise matrix multiplication (Hadamard product) in numpy?
I have two matrices

```<code>a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])
</code>```

and I want to get the element-wise product, [[1*5,2*6], [3*7,4*8]], equaling

[[5,12], [21,32]]

I have tried

```<code>print(np.dot(a,b))
</code>```

and

```<code>print(a*b)
</code>```

but both give the result

[[19 22], [43 50]]

which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?

答:
```<code>import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out:
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out:
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
</code>```

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic

Body:
I have two matrices

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

and I want to get the element-wise product, [[1*5,2*6], [3*7,4*8]], equaling

[[5,12], [21,32]]

I have tried

print(np.dot(a,b))

and

print(a*b)

but both give the result

[[19 22], [43 50]]

which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?

Body:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out:
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out:
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic


问:
Can a service worker update the cache without an open tab?
I want to give the user a speed feel when he accesses my website. If I cache the initial page in service worker, then I can achieve it. But I am having the following doubts.

Is there any way to update that cache even user does not have any tabs with my website?

Is there any memory limitation?

答:
1) Not in a simple way - your Service Worker is suspended until something wakes it up, for example the user opening your app. Or the push message. So you might run your cache update flow in a push message handler and send the push to all subscribed users whenever the update should happen. But you have to be aware that there are limitations of how many pushes can the app receive and/or how long the handler can run.

"Normally" this is done when the new Service Worker version is installing and requires reload (or manual handling) to take effect.

2) Yes, the general storage limit applies. It is OS-specific and you can query for the estimate with Quota Estimation API (Chrome only by now).


问:
How to use a pure TypeScript library as a dependency with Webpack?
I have 3 repos - client, backend and interfaces.

All are written in TypeScript. Client and backend repos compile into JavaScript during the build phase then deployed to server.

Last repo interfaces is not supposed to be compiled to anything, but just used as an npm dependency for both client and backend repos declaring how client and backend apps communicate with each other.

Before I introduced interfaces repo and added it as a dependency to both other repos, I used hardcoded messages types strings and all compiled just fine.

Now, with a purely TypeScript dependency, which is interfaces, I can inject types from it into client or backend repos code and see them connected properly.

But the problem is I cannot compile projects now because seems like something is not configured properly for this case in Webpack.

Here is the related piece of webpack.config.js:

```<code>module: {
    rules: [
        {
            test: /\.js$/,
            use: 'babel-loader',
            // exclude: /node_modules/
        },
        {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }
    ]
},
</code>```

With this one I see an error while trying to build with webpack:

ERROR in ./node_modules/myapp_interfaces/interfaces/ClientRequestPayload.ts

Module parse failed: The keyword 'interface' is reserved (1:0)

You may need an appropriate loader to handle this file type.

If I comment out exclude: /node_modules/, I see this:

ERROR in ./node_modules/myapp_interfaces/index.ts

Module build failed: Error: Typescript emitted no output for /myapp/myapp_backend/node_modules/myapp_interfaces/index.ts.

You should not need to recompile .ts files in node_modules.

Please contact the package author to advise them to use --declaration --outDir.

This interfaces code would work normally if it were in another folder of the project I suppose.

How do I get rid of this error and just import these into my code then compile?

答: If you exclude /node_modules/ from ts-loader isn't it expected that a .ts file in this folder is not imported properly ?</p>

Body:
I have 3 repos - client, backend and interfaces.

All are written in TypeScript. Client and backend repos compile into JavaScript during the build phase then deployed to server.

Last repo interfaces is not supposed to be compiled to anything, but just used as an npm dependency for both client and backend repos declaring how client and backend apps communicate with each other.

Before I introduced interfaces repo and added it as a dependency to both other repos, I used hardcoded messages types strings and all compiled just fine.

Now, with a purely TypeScript dependency, which is interfaces, I can inject types from it into client or backend repos code and see them connected properly.

But the problem is I cannot compile projects now because seems like something is not configured properly for this case in Webpack.

Here is the related piece of webpack.config.js:

module: {
    rules: [
        {
            test: /\.js$/,
            use: 'babel-loader',
            // exclude: /node_modules/
        },
        {
            test: /\.ts$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }
    ]
},

With this one I see an error while trying to build with webpack:

ERROR in ./node_modules/myapp_interfaces/interfaces/ClientRequestPayload.ts

Module parse failed: The keyword 'interface' is reserved (1:0)

You may need an appropriate loader to handle this file type.

If I comment out exclude: /node_modules/, I see this:

ERROR in ./node_modules/myapp_interfaces/index.ts

Module build failed: Error: Typescript emitted no output for /myapp/myapp_backend/node_modules/myapp_interfaces/index.ts.

You should not need to recompile .ts files in node_modules.

Please contact the package author to advise them to use --declaration --outDir.

This interfaces code would work normally if it were in another folder of the project I suppose.

How do I get rid of this error and just import these into my code then compile?


问:
pycharm does not show all attributes and methods of a object
When I use Python to write opencv, I have got the image object using the imread method, but when I try to use the object, I cannot see any attribute or method of the method.

Like this

When I use iPython or use the dir() method to check, I can see it

答:
This happens when PyCharm can't guess the type of the object returned by method - imread() in this case. Some methods return different types of object based on the input. You'd have to take a look into opencv source code to see why it isn't clear what the returned type is. Static analysis of the code detects obvious cases.

IPython has already executed the method, so it's clear what type was returned.

One solution, if you know the type returned, is to use type comments like this:

```<code>import cv2
import numpy
# I've checked with IPython that the returned object is a `numpy.ndarray` instance

img = cv2.imread('/home/me/Pictures/image.jpg')  # type: numpy.ndarray
</code>```

And then if you type img. you will see

The feauture is described on PEP 0484.

This PEP says it's introduced in Python 3.5. However it might be that PyCharm could handle this simple case in older Python versions than 3.5 but I haven't check.

This PEP describes features of typing module which is not available in older Python versions, so most of the features from this document won't work but I'm not sure if PyCharm is really using typing module to parse type comments or does it natively.

Body:
This happens when PyCharm can't guess the type of the object returned by method - imread() in this case. Some methods return different types of object based on the input. You'd have to take a look into opencv source code to see why it isn't clear what the returned type is. Static analysis of the code detects obvious cases.

IPython has already executed the method, so it's clear what type was returned.

One solution, if you know the type returned, is to use type comments like this:

import cv2
import numpy
# I've checked with IPython that the returned object is a `numpy.ndarray` instance

img = cv2.imread('/home/me/Pictures/image.jpg')  # type: numpy.ndarray

And then if you type img. you will see

The feauture is described on PEP 0484.

This PEP says it's introduced in Python 3.5. However it might be that PyCharm could handle this simple case in older Python versions than 3.5 but I haven't check.

This PEP describes features of typing module which is not available in older Python versions, so most of the features from this document won't work but I'm not sure if PyCharm is really using typing module to parse type comments or does it natively.


答:
In your result set is the password column named as used function. All you need is to set an alias of that column such as: aes_decrypt(pass,'k') as 'pass':

```<code>SELECT UserNameID, userName, aes_decrypt(pass,'k') as pass FROM username
</code>```

Your PHP code expect the column 'pass' in result set..

Title: How to echo out decrypt data in PHP

Body:
First, i have use aes_encrypt to encrypt the password

Then i have use aes_decrypt to decrypt the password

The issue is when i try to echo out the data in a table using
<?php echo $row['pass'];?>,  there'll be an error

"Undefined index: pass in"

SQL insert

insert into username (userName,pass) values('$userName',
  aes_encrypt('$pass','k'))

SQL select

SELECT UserNameID,userName,aes_decrypt(pass,'k') from username

What went wrong?

Body:
In your result set is the password column named as used function. All you need is to set an alias of that column such as: aes_decrypt(pass,'k') as 'pass':

SELECT UserNameID, userName, aes_decrypt(pass,'k') as pass FROM username

Your PHP code expect the column 'pass' in result set..


问:
Pick the specific file in the folder
I want pick the specific format of file among the list of files in a directory. Please find the below example.

I have a below list of files (6 files).

Set-1

1) MAG_L_NT_AA_SUM_2017_01_20.dat

2) MAG_L_NT_AA_2017_01_20.dat

Set-2

1) MAG_L_NT_BB_SUM_2017_01_20.dat

2) MAG_L_NT_BB_2017_01_20.dat

Set-3

1) MAG_L_NT_CC_SUM_2017_01_20.dat

2) MAG_L_NT_CC_2017_01_20.dat

From the above three sets I need only 3 files.

1) MAG_L_NT_AA_2017_01_20.dat

2) MAG_L_NT_BB_2017_01_20.dat

3) MAG_L_NT_CC_2017_01_20.dat

Note: There can be multiple lines of commands because i have create the script for above req. Thanks

答:
Probably easiest and least complex solution to your problem is combining find (a tool for searching for files in a directory hierarchy) and grep (tool for printing lines that match a pattern). You also can read those tools manuals by typing man find and man grep.

Before going straight to solution we need to understand, how we will approach your problem. To find pattern in a name of file we search we will use find command with option -name:

-name pattern

Base of file name (the path with the leading directories removed) matches shell pattern pattern. The metacharacters ('*', '?', and '[]')
  match a '.' at the start of the base name (this is a change in
  findutils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a
  directory and the files under it, use -prune; see an example in the
  description of -path. Braces are not recognised as being special,
  despite the fact that some shells including Bash imbue braces with a
  special meaning in shell patterns. The filename matching is performed
  with the use of the fnmatch(3) library function. Don't forget to
  enclose the pattern in quotes in order to protect it from expansion by
  the shell.

For instance, if we want to search for a file containing string 'abc' in directory called 'words_directory', we will enter following:

```<code>$ find words_directory -name "*abc*"
</code>```

And if we want to search all directories in directory:

```<code>$ find words_directory/* -name "*abc*"
</code>```

So first, we will need to find all files, which begin with string "MAG_L_NT_" and end with ".dat", therefore to find all matching names in /your/specified/path/ which contains many subdirectories, which could contain files that match this pattern:

```<code>$ find /your/specified/path/* -name "MAG_L_NT_*.dat"
</code>```

However this prints all found filenames, but we still get names containing "SUM" string, there comes in grep. To exclude names containing unwanted string we will use option -v:

-v, --invert-match

Invert the sense of matching, to select non-matching lines. (-v is
  specified by POSIX .)

To use grep to filter out first commands output we will use pipe () |:

The standard shell syntax for pipelines is to list multiple commands,
  separated by vertical bars ("pipes" in common Unix verbiage). For
  example, to list files in the current directory (ls), retain only the
  lines of ls output containing the string "key" (grep), and view the
  result in a scrolling page (less), a user types the following into the
  command line of a terminal:

```<code>ls -l | grep key | less
</code>```

"ls -l" produces a process, the output (stdout) of which is piped to
  the input (stdin) of the process for "grep key"; and likewise for the
  process for "less". Each process takes input from the previous process
  and produces output for the next process via standard streams. Each
  "|" tells the shell to connect the standard output of the command on
  the left to the standard input of the command on the right by an
  inter-process communication mechanism called an (anonymous) pipe,
  implemented in the operating system. Pipes are unidirectional; data
  flows through the pipeline from left to right.

```<code> process1 | process2 | process3
</code>```

After you got acquainted to mentioned commands and options which will be used to achieve your goal, you are ready for solution:

```<code>$ find /your/specified/path/* -name "MAG_L_NT_*.dat" | grep -v "SUM"
</code>```

This command will produce output of all names which begin "MAG_L_NT_" and end with ".dat". grep -v will use first command output as input and remove all lines containing "SUM" string.

Title: Pick the specific file in the folder

Body:
Probably easiest and least complex solution to your problem is combining find (a tool for searching for files in a directory hierarchy) and grep (tool for printing lines that match a pattern). You also can read those tools manuals by typing man find and man grep.

Before going straight to solution we need to understand, how we will approach your problem. To find pattern in a name of file we search we will use find command with option -name:

-name pattern

Base of file name (the path with the leading directories removed) matches shell pattern pattern. The metacharacters ('*', '?', and '[]')
  match a '.' at the start of the base name (this is a change in
  findutils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore a
  directory and the files under it, use -prune; see an example in the
  description of -path. Braces are not recognised as being special,
  despite the fact that some shells including Bash imbue braces with a
  special meaning in shell patterns. The filename matching is performed
  with the use of the fnmatch(3) library function. Don't forget to
  enclose the pattern in quotes in order to protect it from expansion by
  the shell.

For instance, if we want to search for a file containing string 'abc' in directory called 'words_directory', we will enter following:

$ find words_directory -name "*abc*"

And if we want to search all directories in directory:

$ find words_directory/* -name "*abc*"

So first, we will need to find all files, which begin with string "MAG_L_NT_" and end with ".dat", therefore to find all matching names in /your/specified/path/ which contains many subdirectories, which could contain files that match this pattern:

$ find /your/specified/path/* -name "MAG_L_NT_*.dat"

However this prints all found filenames, but we still get names containing "SUM" string, there comes in grep. To exclude names containing unwanted string we will use option -v:

-v, --invert-match

Invert the sense of matching, to select non-matching lines. (-v is
  specified by POSIX .)

To use grep to filter out first commands output we will use pipe () |:

The standard shell syntax for pipelines is to list multiple commands,
  separated by vertical bars ("pipes" in common Unix verbiage). For
  example, to list files in the current directory (ls), retain only the
  lines of ls output containing the string "key" (grep), and view the
  result in a scrolling page (less), a user types the following into the
  command line of a terminal:

ls -l | grep key | less

"ls -l" produces a process, the output (stdout) of which is piped to
  the input (stdin) of the process for "grep key"; and likewise for the
  process for "less". Each process takes input from the previous process
  and produces output for the next process via standard streams. Each
  "|" tells the shell to connect the standard output of the command on
  the left to the standard input of the command on the right by an
  inter-process communication mechanism called an (anonymous) pipe,
  implemented in the operating system. Pipes are unidirectional; data
  flows through the pipeline from left to right.

 process1 | process2 | process3

After you got acquainted to mentioned commands and options which will be used to achieve your goal, you are ready for solution:

$ find /your/specified/path/* -name "MAG_L_NT_*.dat" | grep -v "SUM"

This command will produce output of all names which begin "MAG_L_NT_" and end with ".dat". grep -v will use first command output as input and remove all lines containing "SUM" string.


问:
Google+ API to get all the photos
I have done the google+ authentication and now i can access user id, access token etc.
I want to access the user personal and shared photos from google plus or picasa [anything works for me].

What API should i call? [Web application]

答:
Note that the Picasa API seems to have cross-origin restrictions for if you want to upload images. So to upload images, you'll need to use a server/proxy, or a helper Chrome extension. (since those don't have the same cross-origin restrictions that webpage code has -- at least when the correct permissions are set in the manifest)

See here for an example solution (in a Chrome extension): https://webapps.stackexchange.com/a/112527/147716

Title: Google+ API to get all the photos


问:
Is there any start and end for order property in flex?
I want to know that is there any begin or end number for arranging elements in a flex container ?
For example :

```<code>.firstOrder {
    order: <First-Item>
}
</code>```

Why ? Because I want to create a CSS framework, So I want to know can I add 2 classes to order First item and Last item.

答:
No, there are not any specific start or end number.

Any number is usable, both positive and negative, and the one's with lower comes first, and a flex item's default is 0.

If two, or more, items have the same value, it is their order in the markup that decides.

In your case, having a first and last, and based on the default of 0, giving one item -1 and another 1, will make the item with -1 first and the item with 1 last.

Based on a comment by Ali, it should be noted that older Flexbox versions might have a different default value, e.g. it appears for -webkit-box-ordinal-group to be 1.

Body:
I want to know that is there any begin or end number for arranging elements in a flex container ?
For example :

.firstOrder {
    order: <First-Item>
}

Why ? Because I want to create a CSS framework, So I want to know can I add 2 classes to order First item and Last item.


问:
saving the files in a variable and deleting the files
I am trying to delete old files, I first need to store the files in a variable and delete them one by one, my code works for normal files but if filename has white spaces in it, it cant delete that file and throws an error

code-

```<code>OLD_FILES=`find . -name "*.txt" -type f -newermt $2000-01-01 ! -newermt $2017-12-12`
for i in $OLD_FILES
   do
     rm $i
   done
</code>```

I can't use

```<code>OLD_FILES=`find . -name "*.$FILE_TYPE" -type f -newermt $START_DATE ! -newermt $DATE -delete `
</code>```

because find and delete needs to be separate functions and to avoid code repetition

答:
Have a look at the following link
https://unix.stackexchange.com/questions/208140/deleting-files-with-spaces-in-their-names

There are many solutions you might be able to apply to your problem:

like deleting the files via their inum

using a regex with space to fetch the file: find . -regex '.* .*' -delete

using xargs and find . -type -f -print 0

make a function to escape all spaces of your filenames \, before running the rm command

Body:
I am trying to delete old files, I first need to store the files in a variable and delete them one by one, my code works for normal files but if filename has white spaces in it, it cant delete that file and throws an error

code-

OLD_FILES=`find . -name "*.txt" -type f -newermt $2000-01-01 ! -newermt $2017-12-12`
for i in $OLD_FILES
   do
     rm $i
   done

I can't use

OLD_FILES=`find . -name "*.$FILE_TYPE" -type f -newermt $START_DATE ! -newermt $DATE -delete `

because find and delete needs to be separate functions and to avoid code repetition