问:
Haskell converting string to binary number
I need to convert a string of chars to a list of binary numbers in Haskell. I've written two functions to do this, but I'm not sure how to combine them into one. So far I have

```<code>dec[]=[]
dec(x:xs) = ord(x): dec xs
</code>```

to convert every char in the list into a decimal number. The next function

```<code>bin 0 = [0]
bin n| n `mod` 2 == 1 = bin (n `div` 2) ++ [1]
     | n `mod` 2 == 0 = bin (n `div` 2) ++ [0]
</code>```

converts a decimal number to its binary equivalent. I'm not sure how to apply the second function to every element in the list, in order to convert every char to its equivalent in binary. I tried to use the where clause:

where n = dec(x:xs) = ord(x): dec xs

but this is not valid as there are two equals signs on the same line. How can I achieve the correct functionality?

答:
What we want is a function of type String -> String (decimal -> binary). What you have now is

```<code>dec :: String -> [Int]
bin :: Int -> [Int] -- use *lowercase*
</code>```

So it seems impossible to compose a function of type String -> String only with these two. Besides, ord is not what you want.

```<code>*Main> dec "123"
[49,50,51]
*Main> bin 123
[0,1,1,1,1,0,1,1]
</code>```

From what you have now, the possible solution would be:

```<code>*Main Data.Char> toBinary = map intToDigit . bin . read
*Main Data.Char> toBinary "123"
"01111011"
</code>```

I guess your intention may be dec :: String -> Int, then bin . dec :: String -> [Int]. You can follow the type signature and retry.

Body:
I need to convert a string of chars to a list of binary numbers in Haskell. I've written two functions to do this, but I'm not sure how to combine them into one. So far I have

dec[]=[]
dec(x:xs) = ord(x): dec xs

to convert every char in the list into a decimal number. The next function

bin 0 = [0]
bin n| n `mod` 2 == 1 = bin (n `div` 2) ++ [1]
     | n `mod` 2 == 0 = bin (n `div` 2) ++ [0]

converts a decimal number to its binary equivalent. I'm not sure how to apply the second function to every element in the list, in order to convert every char to its equivalent in binary. I tried to use the where clause:

where n = dec(x:xs) = ord(x): dec xs

but this is not valid as there are two equals signs on the same line. How can I achieve the correct functionality?

Body:
What we want is a function of type String -> String (decimal -> binary). What you have now is

dec :: String -> [Int]
bin :: Int -> [Int] -- use *lowercase*

So it seems impossible to compose a function of type String -> String only with these two. Besides, ord is not what you want.

*Main> dec "123"
[49,50,51]
*Main> bin 123
[0,1,1,1,1,0,1,1]

From what you have now, the possible solution would be:

*Main Data.Char> toBinary = map intToDigit . bin . read
*Main Data.Char> toBinary "123"
"01111011"

I guess your intention may be dec :: String -> Int, then bin . dec :: String -> [Int]. You can follow the type signature and retry.


来源: stackexchange

问:
How to use bootstrap toggle to call a funciton?
I have created a toggle switch using bootstrap. The code for it is as follows:

```<code><label >
  Automatic Refresh:
</label>
<input class="pull-right" data-size="mini" type="checkbox" data-
toggle="toggle">
</code>```

In my application, I want to call automatic refresh function when the button is "On" and turn off the automatic refresh when the toggle button is "Off".
For experimentation purpose, I will be using setInterval() and clearInterval() for toggle On and toggle Off respectively.
The code which should run when toggle is on is as follows:

```<code>var int = setInterval(function(){ alert("Hello"); }, 1000);
</code>```

The code which should run when the toggle is set to Off is as follows:

```<code>clearInterval(int);
</code>```

How do I make a function call on toggle clicks ?
My toggle button looks like this

答:
you can use an onchange event.

For this example, I've given your checkbox an id and used that to bind the onchange event (there are other options):

```<code><input id="data-toggle" class="pull-right" data-size="mini" type="checkbox" data-
toggle="toggle">
</code>```

Javascript:

```<code>document.getElementById('data-toggle').onchange = function(e){

        if(e.target.checked) {
            //Toggle is on
        } else {
            //Toggle is off
        }
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a toggle switch using bootstrap. The code for it is as follows:

  Automatic Refresh:

<input class="pull-right" data-size="mini" type="checkbox" data-
toggle="toggle">

In my application, I want to call automatic refresh function when the button is "On" and turn off the automatic refresh when the toggle button is "Off".
For experimentation purpose, I will be using setInterval() and clearInterval() for toggle On and toggle Off respectively.
The code which should run when toggle is on is as follows:

var int = setInterval(function(){ alert("Hello"); }, 1000);

The code which should run when the toggle is set to Off is as follows:

clearInterval(int);

How do I make a function call on toggle clicks ?
My toggle button looks like this

Body:
you can use an onchange event.

For this example, I've given your checkbox an id and used that to bind the onchange event (there are other options):

<input id="data-toggle" class="pull-right" data-size="mini" type="checkbox" data-
toggle="toggle">

Javascript:

document.getElementById('data-toggle').onchange = function(e){

        if(e.target.checked) {
            //Toggle is on
        } else {
            //Toggle is off
        }
};


问:
iPhone: Is it possible to send Push-Notifications from a website?
I'd like to be notified of certain events on my webserver with a push notification from my website to my iPhone. Is this somehow possible, or do I have to install/create a special App for this?</p>

答: You can definitely send notifications triggered from a website: you just have to hook up the backend to do so. See this previous post for more information.</p>

ContentLicense: CC BY-SA 2.5


答:
Here's a tidyverse solution based on first tidying your data into long format.

```<code># load packages
require(stringr)
require(tidyverse)

# your example data
df <- read_table('var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715')

# generating obtained values
df %>%
    gather(col, value, -var) %>%
    mutate(col_letter = str_extract(col, 'A|C')) %>%
    group_by(var, col_letter) %>%
    mutate(col_position = row_number()) %>%
    group_by(var) %>%
    select(-col) %>%
    spread(col_letter, value) %>%
    mutate(dif = C - A) %>%
    select(var, col_position, dif) %>%
    spread(col_position, dif, sep='_') %>%
    bind_cols(df, .)
</code>```

This doesn't get the column names you want in the output, but it does contain all the values you asked for.  You could manually rename at this point if you'd like.

Title: Calculate new (78) variables based on column input from 78*2 other variables dplyr

Body:
I would like to make a simple subtraction based on a "two column" pair, the a1...n and c1...n series to create a third column b1...n over 78 "pairs" in dplyr. But, I do not know how to call the columns correctly and rund it over each column pair.

df
var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715

I have tried:

b_names <- c( "B400",   "B403",   "B407")
df_b  <- mutate_at(df,vars(C400.0:C407.1), .funs(b_names= ., vars(C400.0:C407.1)-vars(A399.6:A403.4)))

with no success

The results should look like

df_b
var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4 B400   B403   B407
V1  1.176    1.149   1.111   0.767   0.736    0.699  0.408  0.412  0.412
V2  1.192    1.160   1.127   0.770   0.738    0.707  0.421  0.421  0.420
V3  1.223    1.1918  1.154   0.775   0.744    0.715  0.447  0.447  0.439

Body:
Here's a tidyverse solution based on first tidying your data into long format.

# load packages
require(stringr)
require(tidyverse)

# your example data
df <- read_table('var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715')

# generating obtained values
df %>%
    gather(col, value, -var) %>%
    mutate(col_letter = str_extract(col, 'A|C')) %>%
    group_by(var, col_letter) %>%
    mutate(col_position = row_number()) %>%
    group_by(var) %>%
    select(-col) %>%
    spread(col_letter, value) %>%
    mutate(dif = C - A) %>%
    select(var, col_position, dif) %>%
    spread(col_position, dif, sep='_') %>%
    bind_cols(df, .)

This doesn't get the column names you want in the output, but it does contain all the values you asked for.  You could manually rename at this point if you'd like.


问:
Best way to call methods of child objects in a list?
I am trying to make a system of GUI elements that all inherit a base class. I want to be able to call all of the child elements by calling a Draw method in the parent class. Here is essentially what I have so far:

Base element:

```<code>interface GuiElementBase
{
protected:
    std::vector<GuiElementBase> children;
public:
    void Draw()
    {
        for (int i = 0; i < children.size(); i++)
            children[i].Draw();
    }
    void AddChild(GuiElementBase child)
    {
        children.push_back(child);
    }
};
</code>```

Text element:

```<code>class GuiElementText : public GuiElementBase
{
public:
    void Draw()
    {
        GuiElementBase::Draw();
        // + some text-specific drawing code
    }
};
</code>```

Implementation:

```<code>GuiElementText* TextTest;

void GUI::Init()
{
    TextTest = new GuiElementText();
    TextTest->AddChild(GuiElementText());
}

void GUI::Draw()
{
    TextTest->Draw();
}
</code>```

Constructors, drawing code, and other methods were left out for simplicity's sake.

When it tries to update the TextTest child, it obviously just calls GuiElementBase::Draw() because the "children" vector is GuiElementBase. I have been having trouble finding a way to have it call the child object and not the base class. All help is greatly appreciated!

答:
In the following example, the base Draw() is executed first then Draw() for each child in vector. Is this what you are after?

```<code>#include <iostream>

class GuiElementBase
{
private:
    std::vector<GuiElementBase *> children;
public:
    virtual void Draw()
    {
        std::cout << "GuiElementBase draw" << std::endl;

        for (int i = 0; i < children.size(); i++)
            children[i]->Draw();
    }
    void AddChild(GuiElementBase *child)
    {
        children.push_back(child);
    }
};

class GuiElementText : public GuiElementBase
{
public:
    void Draw() override
    {
        std::cout << "GuiElementText draw" << std::endl;
    }
};

int main()
{
    GuiElementBase base;
    GuiElementText* child = new GuiElementText();

    base.AddChild(child);
    base.AddChild(child);

    base.Draw();

    return 0;
}
</code>```

Prints:

```<code>GuiElementBase draw
GuiElementText draw
GuiElementText draw
</code>```

Body:
I am trying to make a system of GUI elements that all inherit a base class. I want to be able to call all of the child elements by calling a Draw method in the parent class. Here is essentially what I have so far:

Base element:

interface GuiElementBase
{
protected:
    std::vector<GuiElementBase> children;
public:
    void Draw()
    {
        for (int i = 0; i < children.size(); i++)
            children[i].Draw();
    }
    void AddChild(GuiElementBase child)
    {
        children.push_back(child);
    }
};

Text element:

class GuiElementText : public GuiElementBase
{
public:
    void Draw()
    {
        GuiElementBase::Draw();
        // + some text-specific drawing code
    }
};

Implementation:

GuiElementText* TextTest;

void GUI::Init()
{
    TextTest = new GuiElementText();
    TextTest->AddChild(GuiElementText());
}

void GUI::Draw()
{
    TextTest->Draw();
}

Constructors, drawing code, and other methods were left out for simplicity's sake.

When it tries to update the TextTest child, it obviously just calls GuiElementBase::Draw() because the "children" vector is GuiElementBase. I have been having trouble finding a way to have it call the child object and not the base class. All help is greatly appreciated!

Body:
In the following example, the base Draw() is executed first then Draw() for each child in vector. Is this what you are after?

#include <iostream>

class GuiElementBase
{
private:
    std::vector<GuiElementBase *> children;
public:
    virtual void Draw()
    {
        std::cout << "GuiElementBase draw" << std::endl;

        for (int i = 0; i < children.size(); i++)
            children[i]->Draw();
    }
    void AddChild(GuiElementBase *child)
    {
        children.push_back(child);
    }
};

class GuiElementText : public GuiElementBase
{
public:
    void Draw() override
    {
        std::cout << "GuiElementText draw" << std::endl;
    }
};

int main()
{
    GuiElementBase base;
    GuiElementText* child = new GuiElementText();

    base.AddChild(child);
    base.AddChild(child);

    base.Draw();

    return 0;
}

Prints:

GuiElementBase draw
GuiElementText draw
GuiElementText draw


问:
Liberty Server - ClassLoader.getSystemResource returns null
Developed a rest service which uses third party jars. Reviewing their code I found that they are using ClassLoader.getSystemResource("log4j.properties") to retrieve the data. This code returns null and henceforth I get null pointer exception always. The same code if I deploy in websphere 8.5.5.7 and set server classpath it is working fine.
Since I am using Liberty in my local machine this is not retrieving the path.

I also tried setting classloader in server.xml but no use.

```<code><library id="config">
  <folder dir="/properties/dev/" includes="*.properties" scanInterval="5s"/>
</library>

<enterpriseApplication id="AbcEAR"location="AbcEAR.ear" name="AbcEAR">
  <classloader privateLibraryRef="config"/>
</enterpriseApplication>
</code>```

答:
Using ClassLoader.getSystemResource() will use the system classloader, which will only be able to see things from the JDK and whatever is on the classpath.  Since Liberty does not use a traditional classpath and instead uses OSGi, the system loader will be of little use in Liberty from an application perspective.

Instead, use ClassLoader.getResource() from the thread context classloader, which will take into account the Liberty classloaders.

Body:
Developed a rest service which uses third party jars. Reviewing their code I found that they are using ClassLoader.getSystemResource("log4j.properties") to retrieve the data. This code returns null and henceforth I get null pointer exception always. The same code if I deploy in websphere 8.5.5.7 and set server classpath it is working fine.
Since I am using Liberty in my local machine this is not retrieving the path.

I also tried setting classloader in server.xml but no use.

<library id="config">
  <folder dir="/properties/dev/" includes="*.properties" scanInterval="5s"/>
</library>

<enterpriseApplication id="AbcEAR"location="AbcEAR.ear" name="AbcEAR">
  <classloader privateLibraryRef="config"/>
</enterpriseApplication>


问:
VS2017 command line build issue
I have installed both VS2008 and VS2017 on same machine. During test I found that if I set VS2018 build environment firstly by command: %VS90COMNTOOLS%vsvars32.bat, then reset to VS2017 environment by command: %VS150COMNTOOLS%VsDevCmd.bat. The reset will report following error:

[ERROR:team_explorer.bat] Directory not found: "C"\Program
  Files(x86)\Microsoft Visual Studio
  9.0\Common7\IDECommonExtensions\Microsoft\TeamFoundation\Team Explorer" [Error:VSDevCmd.bat] * VsDevCmd.bat encounterred errors.
  Environment may be incomplete and/or incorrect. *

If I just set VS2017 build environment by %VS150COMNTOOLS%VsDevCmd.bat. No error occurs.
Does anyone meet this issue?

答:
I found a workaround...Use SetLocal and EndLocal to set local build environment.

```<code>SetLocal
Call %VS90COMNTOOLS%vsvars32.bat
EndLocal
call %VS150COMNTOOLS%VsDevCmd.bat
</code>```

Save above command to a bat file and call it. The error disappeared.

Title: VS2017 command line build issue

Body:
I found a workaround...Use SetLocal and EndLocal to set local build environment.

SetLocal
Call %VS90COMNTOOLS%vsvars32.bat
EndLocal
call %VS150COMNTOOLS%VsDevCmd.bat

Save above command to a bat file and call it. The error disappeared.


问:
UWP CreateFileAsync thread exits when compiled in release mode with Compile with .NET Native tool chain checked
I have a UWP app and I am trying to save a config file using the below code.  This works fine with Compile with .NET Native tool chain unchecked and in debug mode.  However once Compile with .NET Native tool chain is checked the thread exits when trying to create the file.  How do I get around this?</p>

```<code>public async void SaveConfig()
{
    // serialize JSON to a string
    string json = JsonConvert.SerializeObject(uris);

    // write string to a file
    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("config.json", CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteTextAsync(file, json);
}
</code>```

答:
The problem is most likely to be in the async void method which isn't awaited to be executed till the end. If this is the case, the solution would be to change the method header

```<code>public async Task SaveConfigAsync()
</code>```

and invoke the method like this

```<code>await SaveConfigAsync();
</code>```

Body:
I have a UWP app and I am trying to save a config file using the below code.  This works fine with Compile with .NET Native tool chain unchecked and in debug mode.  However once Compile with .NET Native tool chain is checked the thread exits when trying to create the file.  How do I get around this?

public async void SaveConfig()
{
    // serialize JSON to a string
    string json = JsonConvert.SerializeObject(uris);

    // write string to a file
    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("config.json", CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteTextAsync(file, json);
}

Body:
The problem is most likely to be in the async void method which isn't awaited to be executed till the end. If this is the case, the solution would be to change the method header

public async Task SaveConfigAsync()

and invoke the method like this

await SaveConfigAsync();


问:
How to get sorted paged map by couple conditions using java 8 streams
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

```<code>@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}
</code>```

答:
Other answers are correct, however I think TreeSet (instead of TreeMap) could be of great help to you:

```<code>TreeSet<Account> accounts = new TreeSet<>(
    Comparator.comparingDouble(Account::getMargin).reversed()
        .thenComparing(Account::getName));

// Then add all the accounts

Map<Double, List<Account>> result = accounts
    .headSet(new Account("zzzz", MARGIN_LIMIT)) // zzzz is the greatest string
    .stream()                                   // I could think of at this time
    .skip(PAGE_SIZE * (page - 1))               // (it's quite late here)
    .limit(PAGE_SIZE)
    .collect(Collectors.groupingBy(Account::getMargin));
</code>```

This solution uses the TreeSet.headSet method, which fits like a glove for what you are trying to do. Then, we turn to stream to skip and limit elements and finally collect to the desired data structure.

Body:
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}

Body:
Other answers are correct, however I think TreeSet (instead of TreeMap) could be of great help to you:

TreeSet<Account> accounts = new TreeSet<>(
    Comparator.comparingDouble(Account::getMargin).reversed()
        .thenComparing(Account::getName));

// Then add all the accounts

Map<Double, List<Account>> result = accounts
    .headSet(new Account("zzzz", MARGIN_LIMIT)) // zzzz is the greatest string
    .stream()                                   // I could think of at this time
    .skip(PAGE_SIZE * (page - 1))               // (it's quite late here)
    .limit(PAGE_SIZE)
    .collect(Collectors.groupingBy(Account::getMargin));

This solution uses the TreeSet.headSet method, which fits like a glove for what you are trying to do. Then, we turn to stream to skip and limit elements and finally collect to the desired data structure.


问:
Change the device ID on an Android emulator?
Is there a way to change the IMEI that will be returned by the emulator's TelephonyManager?  Also, is there a way to change the ID returned by Settings.Secure.ANDROID_ID?

I use these IDs to distinguish my users from one another when storing their data on the server side.  It would be nice if my QA team could change these IDs so that they are not all using the same set of user data.

答: I haven't tried it, but this page outlines a method that involves manually modifying the emaultor.exe file. It seems pretty straightforward, though you'd have to create a separate emulator for each QA team member.</p>


问:
ASP.NET Core CreatedAtRoute No route matches the supplied values
Using ASP.NET Core 2.0.0 Web API, I'm trying to build a controller to do a database insert. The information can be inserted into the database just fine, but returning a CreatedAtRoute throws an 'InvalidOperationException: No route matches the supplied values.' Everything I've found online so far says this was a bug with early pre-release versions of ASP.NET Core and has since been fixed, but I'm not really sure what to do about this. The following is my controller code:

```<code>[Produces("application/json")]
[Route("api/page")]
public class PageController : Controller
{
    private IPageDataAccess _pageData; // data access layer

    public PageController(IPageDataAccess pageData)
    {
        _pageData = pageData;
    }

    [HttpGet("{id}", Name = "GetPage")]
    public async Task<IActionResult> Get(int id)
    {
        var result = await _pageData.GetPage(id); // data access call

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] Page page)
    {
        if (page == null)
        {
            return BadRequest();
        }

        await _pageData.CreatePage(page); // data access call

        // Return HTTP 201 response and add a Location header to response
        // TODO - fix this, currently throws exception 'InvalidOperationException: No route matches the supplied values.'
        return CreatedAtRoute("GetPage", new { PageId = page.PageId }, page);
    }
</code>```

Could anyone possibly shed some light on this for me?

答:
The parameters need to match the route values of the intended action.

In this case you need id not PageId

```<code>return CreatedAtRoute(
    actionName: "GetPage",
    routeValues: new { id = page.PageId },
    value: page);
</code>```

Body:
Using ASP.NET Core 2.0.0 Web API, I'm trying to build a controller to do a database insert. The information can be inserted into the database just fine, but returning a CreatedAtRoute throws an 'InvalidOperationException: No route matches the supplied values.' Everything I've found online so far says this was a bug with early pre-release versions of ASP.NET Core and has since been fixed, but I'm not really sure what to do about this. The following is my controller code:

[Produces("application/json")]
[Route("api/page")]
public class PageController : Controller
{
    private IPageDataAccess _pageData; // data access layer

    public PageController(IPageDataAccess pageData)
    {
        _pageData = pageData;
    }

    [HttpGet("{id}", Name = "GetPage")]
    public async Task<IActionResult> Get(int id)
    {
        var result = await _pageData.GetPage(id); // data access call

        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] Page page)
    {
        if (page == null)
        {
            return BadRequest();
        }

        await _pageData.CreatePage(page); // data access call

        // Return HTTP 201 response and add a Location header to response
        // TODO - fix this, currently throws exception 'InvalidOperationException: No route matches the supplied values.'
        return CreatedAtRoute("GetPage", new { PageId = page.PageId }, page);
    }

Could anyone possibly shed some light on this for me?

Body:
The parameters need to match the route values of the intended action.

In this case you need id not PageId

return CreatedAtRoute(
    actionName: "GetPage",
    routeValues: new { id = page.PageId },
    value: page);

ContentLicense: CC BY-SA 4.0


问:
Excel VBA ADO recordset issue with Null values
I'm pretty new at VBA and having an issue with ADO.

Currently the code im using returns fields (Name, Suburb, State) from a SQL database into a ListBox.
The code works fine as long as there are there all fields have a value, if there is a Null value it returns the error

Could not set the List property. Type mismatch

I need to find a way so if the Suburb and/or State fields return a Null value that it still populates the Listbox.

Any info would be greatly appreciated, thanks in advance!

Database entries

Screenshot of error

```<code>Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQLquery As String
Dim cnnstr As String
Dim SQLName As String
Dim i As Integer

SQLName = "Salon"
SQLquery = "SELECT [Name], [Suburb], [State] FROM Salon WHERE Name like '" & SQLName & "%'"

Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
                "Data Source=localhost; " & _
                "Initial Catalog=MyDatabase;" & _
                "User ID=sa;" & _
                "Password=Password;" & _
                "Trusted_Connection=Yes;"

cnn.Open cnnstr
cnn.Execute SQLquery
rs.Open SQLquery, cnn, adOpenStatic

    rs.MoveFirst
    i = 0
    With Me.lb_search
        .Clear
        Do
            .AddItem
            .List(i, 0) = rs!Name
            .List(i, 1) = rs!Suburb
            .List(i, 2) = rs!State
            i = i + 1
            rs.MoveNext
        Loop Until rs.EOF
    End With

btn_search_test_Exit:
On Error Resume Next
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing
</code>```

答:
Iif can return an alternate for Null Values.

For example:

```<code>.List(i, 0) = IIf(IsNull(a), "(not found)", rs!Name)
</code>```

will return "(not found)" if the value is null.

More info here and here.

Body:
I'm pretty new at VBA and having an issue with ADO.

Currently the code im using returns fields (Name, Suburb, State) from a SQL database into a ListBox.
The code works fine as long as there are there all fields have a value, if there is a Null value it returns the error

Could not set the List property. Type mismatch

I need to find a way so if the Suburb and/or State fields return a Null value that it still populates the Listbox.

Any info would be greatly appreciated, thanks in advance!

Database entries

Screenshot of error

Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQLquery As String
Dim cnnstr As String
Dim SQLName As String
Dim i As Integer

SQLName = "Salon"
SQLquery = "SELECT [Name], [Suburb], [State] FROM Salon WHERE Name like '" & SQLName & "%'"

Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
                "Data Source=localhost; " & _
                "Initial Catalog=MyDatabase;" & _
                "User ID=sa;" & _
                "Password=Password;" & _
                "Trusted_Connection=Yes;"

cnn.Open cnnstr
cnn.Execute SQLquery
rs.Open SQLquery, cnn, adOpenStatic

    rs.MoveFirst
    i = 0
    With Me.lb_search
        .Clear
        Do
            .AddItem
            .List(i, 0) = rs!Name
            .List(i, 1) = rs!Suburb
            .List(i, 2) = rs!State
            i = i + 1
            rs.MoveNext
        Loop Until rs.EOF
    End With

btn_search_test_Exit:
On Error Resume Next
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing

Body:
Iif can return an alternate for Null Values.

For example:

.List(i, 0) = IIf(IsNull(a), "(not found)", rs!Name)

will return "(not found)" if the value is null.

More info here and here.


问:
What is the difference between SoapVar and SoapParam?
In PHP, we have SoapVar and SoapParam classes. I've been confused long enough, since there is no decent documentation of them on php.net.

Today I was surprised to find out that those lines will produce the exact same result in the XML input:

```<code>$soapVar   = new SoapVar((object) ['Foo' => 'bar'], null, null, null, 'TagName');
$soapParam = new SoapParam((object) ['Foo' => 'bar'], 'TagName');
</code>```

In most SoapClient tutorials, I have seen snippets with SoapParam inside SoapVar whenever someone wanted to set custom xsi:type:

```<code>$response = $soapClient->DoSomething(
    new SoapParam(
        new SoapVar(
            (object) ['Foo' => 'bar'],
            null,
            'TypeName'
        ),
        'TagName'
    )
);
</code>```

That is really unintuitive, since SoapVar and SoapParam class names don't say much. The same result can be achieved by more elegant:

```<code>$response = $soapClient->DoSomething(
    new SoapVar(
        (object) ['Foo' => 'bar'],
        null,
        'TypeName',
        null,
        'TagName'
    )
);
</code>```

What is the purpose of SoapParam then? Is it just more simple version of SoapVar? It seems like these two are confused and misunderstood a lot. Is there any extra behavior attached to SoapParam?

答:
You are right the manual is a little vague explaining the exact difference in theory and I was surprised that till now none had pointed some detailed info or explanation into their differences.

By the manual

SoapParam:

Represents parameter to a SOAP call.

SoapVal:

A class representing a variable or object for use with SOAP services.

I went a little down and the main difference I could find was the data parameter in their representative constructors:

for SoapParam::SoapParam ( mixed $data , string $name )
where $data =

The data to pass or return. This parameter can be passed directly as
  PHP value, but in this case it will be named as paramN and the SOAP
  service may not understand it.

while on the other hand we have SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] ) where $data =

The data to pass or return.

By taking these two into consideration, the example in the PHP Manual, i believe points for good the main difference in the argument passing and what you can do with one that can not be done with the other.

In the case of SoapParam

```<code><?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>
</code>```

where $a, $b and $c are PHP variables send directly without passing them through a structure / class. The SaopParam constructor is getting the parameter $data (PHP Variable) and the String representative of the parameter name.

On the other side SoapVar

```<code><?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>
</code>```

As you can see, the arguments/variables are passed through the per-defined class and after an object of that class is passed as argument. That Class is a representative of the SOAP Structure (that SOAP can recognize / thous the risk with SoapParam).

Now the almost confusing part...although there are a few differences in the constructor why the same behavior on your example?

```<code>$soapVar   = new SoapVar((object) ['Foo' => 'bar'], null, null, null, 'TagName');
$soapParam = new SoapParam((object) ['Foo' => 'bar'], 'TagName');
</code>```

I am not surprised, as mentioned above the data either a SOAP Structure or a PHP Variable of a CORRECT Soap Structure is the same :) thanks to Object Oriented we pass the Object produced by a PHP Class. In the SoapVar the construction of the object has more options, thus allowing the user to adapt a more "safe" request towards the SOAP call. While on SoapParam the object can be constructed by passing any object and next its name.

Your (object) ['Foo' => 'bar'] is very simple and has no need for XML Schema Encoding thus the SOAP call receiving it I believe can very easily understand it. It has no need for the

encoding

The encoding ID, one of the XSD_... constants.

that is the second parameter in the SoapVar constructor.

Finally since they both accept an object (any object) in place of the $data variable to my understanding the SoapVar just gives the possibility to build a more safer request to be understood by the SOAP call through the extra arguments in the constructor. The SoapParam is just a badass and allows you to send anything you like at the risk of the SOAP refusing it.... it's like almost wants to act as JSON @ RESTful :P not caring about the type nor structure of the  data it sends :)

References:

SoapParam Class

SoapParam Constructor

SoapVar Class

SoapVar Constructor

Body:
In PHP, we have SoapVar and SoapParam classes. I've been confused long enough, since there is no decent documentation of them on php.net.

Today I was surprised to find out that those lines will produce the exact same result in the XML input:

$soapVar   = new SoapVar((object) ['Foo' => 'bar'], null, null, null, 'TagName');
$soapParam = new SoapParam((object) ['Foo' => 'bar'], 'TagName');

In most SoapClient tutorials, I have seen snippets with SoapParam inside SoapVar whenever someone wanted to set custom xsi:type:

$response = $soapClient->DoSomething(
    new SoapParam(
        new SoapVar(
            (object) ['Foo' => 'bar'],
            null,
            'TypeName'
        ),
        'TagName'
    )
);

That is really unintuitive, since SoapVar and SoapParam class names don't say much. The same result can be achieved by more elegant:

$response = $soapClient->DoSomething(
    new SoapVar(
        (object) ['Foo' => 'bar'],
        null,
        'TypeName',
        null,
        'TagName'
    )
);

What is the purpose of SoapParam then? Is it just more simple version of SoapVar? It seems like these two are confused and misunderstood a lot. Is there any extra behavior attached to SoapParam?

Body:
You are right the manual is a little vague explaining the exact difference in theory and I was surprised that till now none had pointed some detailed info or explanation into their differences.

By the manual

SoapParam:

Represents parameter to a SOAP call.

SoapVal:

A class representing a variable or object for use with SOAP services.

I went a little down and the main difference I could find was the data parameter in their representative constructors:

for SoapParam::SoapParam ( mixed $data , string $name )
where $data =

The data to pass or return. This parameter can be passed directly as
  PHP value, but in this case it will be named as paramN and the SOAP
  service may not understand it.

while on the other hand we have SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] ) where $data =

The data to pass or return.

By taking these two into consideration, the example in the PHP Manual, i believe points for good the main difference in the argument passing and what you can do with one that can not be done with the other.

In the case of SoapParam

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

where $a, $b and $c are PHP variables send directly without passing them through a structure / class. The SaopParam constructor is getting the parameter $data (PHP Variable) and the String representative of the parameter name.

On the other side SoapVar

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

As you can see, the arguments/variables are passed through the per-defined class and after an object of that class is passed as argument. That Class is a representative of the SOAP Structure (that SOAP can recognize / thous the risk with SoapParam).

Now the almost confusing part...although there are a few differences in the constructor why the same behavior on your example?

$soapVar   = new SoapVar((object) ['Foo' => 'bar'], null, null, null, 'TagName');
$soapParam = new SoapParam((object) ['Foo' => 'bar'], 'TagName');

I am not surprised, as mentioned above the data either a SOAP Structure or a PHP Variable of a CORRECT Soap Structure is the same :) thanks to Object Oriented we pass the Object produced by a PHP Class. In the SoapVar the construction of the object has more options, thus allowing the user to adapt a more "safe" request towards the SOAP call. While on SoapParam the object can be constructed by passing any object and next its name.

Your (object) ['Foo' => 'bar'] is very simple and has no need for XML Schema Encoding thus the SOAP call receiving it I believe can very easily understand it. It has no need for the

encoding

The encoding ID, one of the XSD_... constants.

that is the second parameter in the SoapVar constructor.

Finally since they both accept an object (any object) in place of the $data variable to my understanding the SoapVar just gives the possibility to build a more safer request to be understood by the SOAP call through the extra arguments in the constructor. The SoapParam is just a badass and allows you to send anything you like at the risk of the SOAP refusing it.... it's like almost wants to act as JSON @ RESTful :P not caring about the type nor structure of the  data it sends :)

References:

SoapParam Class

SoapParam Constructor

SoapVar Class

SoapVar Constructor


问:
cast problem from class to interface
```<code>Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}
</code>```

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

```<code>string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location
</code>```

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

```<code>string a3 = queryManagerType.Assembly.Location;
</code>```

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll

答:
You may need to do this:

Register for this event somewhere in your application startup code (Program.cs is a good place):

```<code>    //Since we'll be dynamically loading assemblies at runtime, we need to add an appropriate resolution path
    //Otherwise weird things like failing to instantiate TypeConverters will happen
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
</code>```

And then handle it like this:

```<code>    private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        var domain = (AppDomain) sender;

        foreach (var assembly in domain.GetAssemblies())
        {
            if (assembly.FullName == args.Name)
                return assembly;
        }

        return null;
    }
</code>```

My understanding is that this will make sure that a dynamically loaded assembly will resolve its dependencies using already loaded assemblies rather than loading a new copy of an already loaded assembly.  This prevents the type of issues you've observed where the same Type is not valid because it's been loaded in the context of a different copy of the assembly.

Title: cast problem from class to interface

Body:
Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

string a3 = queryManagerType.Assembly.Location;

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll

Body:
You may need to do this:

Register for this event somewhere in your application startup code (Program.cs is a good place):

    //Since we'll be dynamically loading assemblies at runtime, we need to add an appropriate resolution path
    //Otherwise weird things like failing to instantiate TypeConverters will happen
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

And then handle it like this:

    private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        var domain = (AppDomain) sender;

        foreach (var assembly in domain.GetAssemblies())
        {
            if (assembly.FullName == args.Name)
                return assembly;
        }

        return null;
    }

My understanding is that this will make sure that a dynamically loaded assembly will resolve its dependencies using already loaded assemblies rather than loading a new copy of an already loaded assembly.  This prevents the type of issues you've observed where the same Type is not valid because it's been loaded in the context of a different copy of the assembly.


问:
"Allow access to Azure services" turn off by default from ARM template
Does anybody know how to setup ARM Template to keep "Allow access to Azure services" switch be turned OFF by default?

Here is what I currently have

```<code> "resources": [
{
  "name": "[parameters('serverName')]",
  "type": "Microsoft.Sql/servers",
  "location": "[parameters('location')]",
  "apiVersion": "2014-04-01-preview",
  "properties": {
    "administratorLogin": "[parameters('administratorLogin')]",
    "administratorLoginPassword": "[parameters('administratorLoginPassword')]",
    "version": "[parameters('serverVersion')]"
  },
  "tags": {
    "deploymentVersion": "[parameters('deploymentVersion')]",
    "deploymentType": "[parameters('deploymentType')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01-preview",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
      ],
      "location": "[parameters('location')]",
      "name": "AllowAllWindowsAzureIps",
      "properties": {
        "endIpAddress": "0.0.0.0",
        "startIpAddress": "0.0.0.0"
      },
      "type": "firewallrules"
    }
  ]
}  ]
</code>```

答:
Just modify endIpAddress and startIpAddress to 255.255.255.255. Like below:

```<code> {
                    "apiVersion": "2014-04-01-preview",
                    "dependsOn": [
                        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
                    ],
                    "location": "[parameters('location')]",
                    "name": "AllowAllWindowsAzureIps",
                    "properties": {
                        "endIpAddress": "255.255.255.255",
                        "startIpAddress": "255.255.255.255"
                    },
                    "type": "firewallrules"
                }
</code>```

Body:
Does anybody know how to setup ARM Template to keep "Allow access to Azure services" switch be turned OFF by default?

Here is what I currently have

 "resources": [
{
  "name": "[parameters('serverName')]",
  "type": "Microsoft.Sql/servers",
  "location": "[parameters('location')]",
  "apiVersion": "2014-04-01-preview",
  "properties": {
    "administratorLogin": "[parameters('administratorLogin')]",
    "administratorLoginPassword": "[parameters('administratorLoginPassword')]",
    "version": "[parameters('serverVersion')]"
  },
  "tags": {
    "deploymentVersion": "[parameters('deploymentVersion')]",
    "deploymentType": "[parameters('deploymentType')]"
  },
  "resources": [
    {
      "apiVersion": "2014-04-01-preview",
      "dependsOn": [
        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
      ],
      "location": "[parameters('location')]",
      "name": "AllowAllWindowsAzureIps",
      "properties": {
        "endIpAddress": "0.0.0.0",
        "startIpAddress": "0.0.0.0"
      },
      "type": "firewallrules"
    }
  ]
}  ]

Body:
Just modify endIpAddress and startIpAddress to 255.255.255.255. Like below:

 {
                    "apiVersion": "2014-04-01-preview",
                    "dependsOn": [
                        "[concat('Microsoft.Sql/servers/', parameters('serverName'))]"
                    ],
                    "location": "[parameters('location')]",
                    "name": "AllowAllWindowsAzureIps",
                    "properties": {
                        "endIpAddress": "255.255.255.255",
                        "startIpAddress": "255.255.255.255"
                    },
                    "type": "firewallrules"
                }


问:
laravel how yo include on menu button click in the samepage
I have menu on the right and want to display when click on specific item button specific page so how can I make include if only I clicked on this item button</p>

```<code><a href="{{route('customer.package')}}">
    <i class="icon-shopping-cart"></i>
    <span>Update Your Package</span>
</a>
@include('index.customer.customerpackage')
</code>```

答:
```<code><a class="btn btn-primary" href="{{route('customer.package')}}"">
   <i class=""></i>
   <span>Update Your Package</span>
</a>
</code>```

Body:
I have menu on the right and want to display when click on specific item button specific page so how can I make include if only I clicked on this item button

    Update Your Package

@include('index.customer.customerpackage')


问:
Push notification in Web pages
Can a web notification be implemented in web sites? I'm using a environment of jsp's with jquery, vue and angular.js for the front side. There's a way to implement web notifications with this environment?</p>

答:
You can use the Notification API to achieve this.

If you want to use Service Workers to push notifications from a backend, you can check the Push API

These API are still drafts and may only work with modern browsers. Make sure you are using these API's over https.

Title: Push notification in Web pages


问:
Build project with aot in Angular
I got problem with build when I use [somvar] and input the object like {a:value}.

I type ng build --prod --aot.

error Msg

```<code>Invalid ICU message. Missing '}'. ("mTemplate", [ngOutletContext]='{ item: item, dropdown: dropdown, index: i, disable: !selectable[i] }[ERROR ->]')
</code>```

my.pug

```<code>ng-template([ngTemplateOutlet]="itemTemplate", [ngOutletContext]='{ item: item, dropdown: dropdown, index: i, disable: !selectable[i] }')
</code>```

Instead of useing {...:...},I fixed the [ngOutletContext] to [ngOutletContext.item].It would display like

code

```<code>ng-template([ngTemplateOutlet]="itemTemplate", [ngOutletContext.item]='item',[ngOutletContext. dropdown]="dropdown",[ngOutletContext.index]="i",[ngOutletContext.disable]="!selectable[i]")
</code>```

it works well but it's too complex to set ngOutletContext.Is any simple thing to deal it?

added

tsconfig.aot.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "./node_modules/@types/"
    ]
  },
  "files": [
    "src/app/ay.module.ts"
  ],
  "angularCompilerOptions": {
    "genDir": "aot",
    "skipMetadataEmit": true
  }
}
</code>```

答:
Okay,I found my fault in pug.

If the project only got the pure resolver that template-language can't pass AOT compile.

What we need to do is translate to html then got AOT compile, regardless..

Big risk after webpack, parse pug to html every single compiled.Hope the pug-resolver plugin it's supported to AOT nor compile would be slowly if we need to aot.

Title: Build project with aot in Angular

Body:
I got problem with build when I use [somvar] and input the object like {a:value}.

I type ng build --prod --aot.

error Msg

Invalid ICU message. Missing '}'. ("mTemplate", [ngOutletContext]='{ item: item, dropdown: dropdown, index: i, disable: !selectable[i] }[ERROR ->]')

my.pug

ng-template([ngTemplateOutlet]="itemTemplate", [ngOutletContext]='{ item: item, dropdown: dropdown, index: i, disable: !selectable[i] }')

Instead of useing {...:...},I fixed the [ngOutletContext] to [ngOutletContext.item].It would display like

code

ng-template([ngTemplateOutlet]="itemTemplate", [ngOutletContext.item]='item',[ngOutletContext. dropdown]="dropdown",[ngOutletContext.index]="i",[ngOutletContext.disable]="!selectable[i]")

it works well but it's too complex to set ngOutletContext.Is any simple thing to deal it?

added

tsconfig.aot.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": [
      "./node_modules/@types/"
    ]
  },
  "files": [
    "src/app/ay.module.ts"
  ],
  "angularCompilerOptions": {
    "genDir": "aot",
    "skipMetadataEmit": true
  }
}


问:
Detect null reference in an array
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

```<code>public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] == null) return true;
    }
    return false;
}
</code>```

Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:

```<code>#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);
</code>```

答:
Check whether Arrays.asList(myArray).contains(null).

To check part of an array, check whether

```<code>Arrays.asList(myArray).subList(from, to).contains(null)
</code>```

This will not create unnecessary copies of the array; both asList and subList create ArrayList and RandomAccessSubList objects that wrap the original array without copying it.

Title: Detect null reference in an array

Body:
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] == null) return true;
    }
    return false;
}

Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:

#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);

Body:
Check whether Arrays.asList(myArray).contains(null).

To check part of an array, check whether

Arrays.asList(myArray).subList(from, to).contains(null)

This will not create unnecessary copies of the array; both asList and subList create ArrayList and RandomAccessSubList objects that wrap the original array without copying it.


问:
Download APKs from GooglePlay using PHP/Node
I want to download APKs from Google Play using PHP or Node.js from my computer. How can I achieve this? Is it even possible? Thank you.</p>

答: You can try node-google-play module for Nodejs solution</p>


问:
How to call a function of a react class from a service worker object?
I am trying to do unintrusive updates in a react web with my own service worker. I want to display a notification when there are new updates to teh website. I am using a component to handle service worker logic. The problem is I don't know how to call a function of my class in an event listener of the service worker, where this references the service worker itself. Any tips? Here is the class that deals with the service worker:</p>

```<code>import * as React from 'react';
import { RouteComponentProps } from 'react-router';

export class ServiceWorker extends React.Component<RouteComponentProps<{}>> {
    constructor() {
        super();
    }

    registerServiceWorker() {
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/ServiceWorker.js').then(reg => {
                    console.log('SW registered: ', reg);
                    if (!navigator.serviceWorker.controller) {
                        return;
                    }
                    if (reg.waiting) {
                        console.log("update ready1");
                        //Can call updateAlert() here, because still using the same object
                        this.updateAlert();
                        return;
                    }

                    if (reg.installing) {
                        reg.installing.addEventListener('statechange', () => {
                            if (reg.installing.state == 'installed') {
                                console.log("update ready2");
                                //Can't call here
                                //this.updateAlert();
                            }
                        });
                        return;
                    }

                    reg.addEventListener('updatefound', function () {
                        reg.installing.addEventListener('statechange', () => {
                            if (reg.installing) {
                                if (reg.installing.state == 'installed') {
                                    console.log("update ready3");
                                    //or here
                                    //this.updateAlert();
                                }
                            }
                            if (reg.waiting) {
                                if (reg.waiting.state == 'installed') {
                                    console.log("update ready4");
                                    //or here
                                    //this.updateAlert();
                                }
                            }
                        });
                    })
                }).catch(registrationError => {
                    console.log('SW registration failed: ', registrationError);
                });
            });
        }
    }

    updateAlert() {
        console.log("success");
    }

    public render() {
        this.registerServiceWorker();
        return null;
    }
}
</code>```

答:
You can probably try arrow function to use class's scope: registerServiceWorker = () => { ... }

By the way, calling this.registerServiceWorker(); in render is probably not a good idea if you only want to add event listener once, try calling it in componentDidMount.

Body:
I am trying to do unintrusive updates in a react web with my own service worker. I want to display a notification when there are new updates to teh website. I am using a component to handle service worker logic. The problem is I don't know how to call a function of my class in an event listener of the service worker, where this references the service worker itself. Any tips? Here is the class that deals with the service worker:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';

export class ServiceWorker extends React.Component<RouteComponentProps<{}>> {
    constructor() {
        super();
    }

    registerServiceWorker() {
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('/ServiceWorker.js').then(reg => {
                    console.log('SW registered: ', reg);
                    if (!navigator.serviceWorker.controller) {
                        return;
                    }
                    if (reg.waiting) {
                        console.log("update ready1");
                        //Can call updateAlert() here, because still using the same object
                        this.updateAlert();
                        return;
                    }

                    if (reg.installing) {
                        reg.installing.addEventListener('statechange', () => {
                            if (reg.installing.state == 'installed') {
                                console.log("update ready2");
                                //Can't call here
                                //this.updateAlert();
                            }
                        });
                        return;
                    }

                    reg.addEventListener('updatefound', function () {
                        reg.installing.addEventListener('statechange', () => {
                            if (reg.installing) {
                                if (reg.installing.state == 'installed') {
                                    console.log("update ready3");
                                    //or here
                                    //this.updateAlert();
                                }
                            }
                            if (reg.waiting) {
                                if (reg.waiting.state == 'installed') {
                                    console.log("update ready4");
                                    //or here
                                    //this.updateAlert();
                                }
                            }
                        });
                    })
                }).catch(registrationError => {
                    console.log('SW registration failed: ', registrationError);
                });
            });
        }
    }

    updateAlert() {
        console.log("success");
    }

    public render() {
        this.registerServiceWorker();
        return null;
    }
}


问:
Input and Print
I am trying to get a input to be typed after the "Choice: " but i also want to continue "*" around the whole text... Im  not sure how to do it even after trying multiple times with variations and research i couldn't dind an answer...

```<code>print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *                Choice: ") & print(" *  ")
</code>```

so that it is printed with "Choice:(here will be the input) * "

答:
Technically, you could just do this:

```<code>print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *       Choice:             *  ")
</code>```

All the text in the quotation marks do is that it just acts as text to be prompted, which is why this works.

Title: Input and Print

Body:
I am trying to get a input to be typed after the "Choice: " but i also want to continue "*" around the whole text... Im  not sure how to do it even after trying multiple times with variations and research i couldn't dind an answer...

print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *                Choice: ") & print(" *  ")

so that it is printed with "Choice:(here will be the input) * "

Body:
Technically, you could just do this:

print("  ********School Quizes********  ")
print("  *                           *  ")
print("  *       A) Register         *  ")
print("  *       B) Loging           *  ")
print("  *       C) Quit             *  ")
print("  *                           *  ")
input("  *       Choice:             *  ")

All the text in the quotation marks do is that it just acts as text to be prompted, which is why this works.


问:
How to write a Python module/package?
I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help.

What I have:

(Just want to be specific as possible) I have the virtualenv ready, it's also up in github, the .gitignore file for python is there as well, plus, the requests library for interacting with the REST API. That's it.

Here's the current directory tree

```<code>.
├── bin
│   └── /the usual stuff/
├── include
│   └── /the usual stuff/
├── lib
│   └── python2.7
│       └── /the usual stuff/
├── local
│   └── /the usual stuff/
└── README.md

27 directories, 280 files
</code>```

I don't even know where to put the .py files, if I ever make one.

What I wanted to do:

Make a python module install-able with "pip install ..."

If possible, I want a general step by step process on writing Python modules.

答:
Since nobody did cover this question of the OP yet:

What I wanted to do:

Make a python module install-able with "pip install ..."

Here is an absolute minimal example, showing the basic steps of preparing and uploading your package to PyPI using setuptools and twine.

This is by no means a substitute for reading at least the tutorial, there is much more to it than covered in this very basic example.

Creating the package itself is already covered by other answers here, so let us assume we have that step covered and our project structure like this:

```<code>.
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```

In order to use setuptools for packaging, we need to add a file setup.py, this goes into the root folder of our project:

```<code>.
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```

At the minimum, we specify the metadata for our package, our setup.py would look like this:

```<code>from setuptools import setup

setup(
    name='hellostackoverflow',
    version='0.0.1',
    description='a pip-installable package example',
    license='MIT',
    packages=['hellostackoverflow'],
    author='Benjamin Gerfelder',
    author_email='benjamin.gerfelder@gmail.com',
    keywords=['example'],
    url='https://github.com/bgse/hellostackoverflow'
)
</code>```

Since we have set license='MIT', we include a copy in our project as LICENCE.txt, alongside a readme file in reStructuredText as README.rst:

```<code>.
├── LICENCE.txt
├── README.rst
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```

At this point, we are ready to go to start packaging using setuptools, if we do not have it already installed, we can install it with pip:

```<code>pip install setuptools
</code>```

In order to do that and create a source distribution, at our project root folder we call our setup.py from the command line, specifying we want sdist:

```<code>python setup.py sdist
</code>```

This will create our distribution package and egg-info, and result in a folder structure like this, with our package in dist:

```<code>.
├── dist/
├── hellostackoverflow.egg-info/
├── LICENCE.txt
├── README.rst
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```

At this point, we have a package we can install using pip, so from our project root (assuming you have all the naming like in this example):

```<code>pip install ./dist/hellostackoverflow-0.0.1.tar.gz
</code>```

If all goes well, we can now open a Python interpreter, I would say somewhere outside our project directory to avoid any confusion, and try to use our shiny new package:

```<code>Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hellostackoverflow import hellostackoverflow
>>> hellostackoverflow.greeting()
'Hello Stack Overflow!'
</code>```

Now that we have confirmed the package installs and works, we can upload it to PyPI.

Since we do not want to pollute the live repository with our experiments, we create an account for the testing repository, and install twine for the upload process:

```<code>pip install twine
</code>```

Now we're almost there, with our account created we simply tell twine to upload our package, it will ask for our credentials and upload our package to the specified repository:

```<code>.
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```0

We can now log into our account on the PyPI test repository and marvel at our freshly uploaded package for a while, and then grab it using pip:

```<code>.
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py
</code>```1

As we can see, the basic process is not very complicated. As I said earlier, there is a lot more to it than covered here, so go ahead and read the tutorial for more in-depth explanation.

Title: How to write a Python module/package?

Body:
I've been making Python scripts for simple tasks at work and never really bothered packaging them for others to use. Now I have been assigned to make a Python wrapper for a REST API. I have absolutely no idea on how to start and I need help.

What I have:

(Just want to be specific as possible) I have the virtualenv ready, it's also up in github, the .gitignore file for python is there as well, plus, the requests library for interacting with the REST API. That's it.

Here's the current directory tree

.
├── bin
│   └── /the usual stuff/
├── include
│   └── /the usual stuff/
├── lib
│   └── python2.7
│       └── /the usual stuff/
├── local
│   └── /the usual stuff/
└── README.md

27 directories, 280 files

I don't even know where to put the .py files, if I ever make one.

What I wanted to do:

Make a python module install-able with "pip install ..."

If possible, I want a general step by step process on writing Python modules.

Body:
Since nobody did cover this question of the OP yet:

What I wanted to do:

Make a python module install-able with "pip install ..."

Here is an absolute minimal example, showing the basic steps of preparing and uploading your package to PyPI using setuptools and twine.

This is by no means a substitute for reading at least the tutorial, there is much more to it than covered in this very basic example.

Creating the package itself is already covered by other answers here, so let us assume we have that step covered and our project structure like this:

.
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py

In order to use setuptools for packaging, we need to add a file setup.py, this goes into the root folder of our project:

.
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py

At the minimum, we specify the metadata for our package, our setup.py would look like this:

from setuptools import setup

setup(
    name='hellostackoverflow',
    version='0.0.1',
    description='a pip-installable package example',
    license='MIT',
    packages=['hellostackoverflow'],
    author='Benjamin Gerfelder',
    author_email='benjamin.gerfelder@gmail.com',
    keywords=['example'],
    url='https://github.com/bgse/hellostackoverflow'
)

Since we have set license='MIT', we include a copy in our project as LICENCE.txt, alongside a readme file in reStructuredText as README.rst:

.
├── LICENCE.txt
├── README.rst
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py

At this point, we are ready to go to start packaging using setuptools, if we do not have it already installed, we can install it with pip:

pip install setuptools

In order to do that and create a source distribution, at our project root folder we call our setup.py from the command line, specifying we want sdist:

python setup.py sdist

This will create our distribution package and egg-info, and result in a folder structure like this, with our package in dist:

.
├── dist/
├── hellostackoverflow.egg-info/
├── LICENCE.txt
├── README.rst
├── setup.py
└── hellostackoverflow/
    ├── __init__.py
    └── hellostackoverflow.py

At this point, we have a package we can install using pip, so from our project root (assuming you have all the naming like in this example):

pip install ./dist/hellostackoverflow-0.0.1.tar.gz

If all goes well, we can now open a Python interpreter, I would say somewhere outside our project directory to avoid any confusion, and try to use our shiny new package:

Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hellostackoverflow import hellostackoverflow
>>> hellostackoverflow.greeting()
'Hello Stack Overflow!'

Now that we have confirmed the package installs and works, we can upload it to PyPI.

Since we do not want to pollute the live repository with our experiments, we create an account for the testing repository, and install twine for the upload process:

pip install twine

Now we're almost there, with our account created we simply tell twine to upload our package, it will ask for our credentials and upload our package to the specified repository:

twine upload --repository-url https://test.pypi.org/legacy/ dist/*

We can now log into our account on the PyPI test repository and marvel at our freshly uploaded package for a while, and then grab it using pip:

pip install --index-url https://test.pypi.org/simple/ hellostackoverflow

As we can see, the basic process is not very complicated. As I said earlier, there is a lot more to it than covered here, so go ahead and read the tutorial for more in-depth explanation.


问:
MySQL returning incorrect data?
Recently an issue came up in the Django community regarding testing of MySQL (using MyISAM).

Here's the django ticket: http://code.djangoproject.com/ticket/14661

One of the Django core developers came up with this test and many of us have been able to replicate it. Anyone have a guess as to what we are running into here? Is it simply a bug in MySQL or am I missing something?

Here's the test code and queries:

```<code>DROP TABLE IF EXISTS `testapp_tag`;
CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
</code>```

Here's the output:

```<code>mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS  NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
|  5 | t5   |         3 |
+----+------+-----------+
3 rows in set (0.00 sec)

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
+----+------+-----------+
2 rows in set (0.01 sec)
</code>```

答:
This form works reliably:

```<code>SELECT T.`id`, T.`name`, T.`parent_id`
FROM `testapp_tag` T
WHERE NOT (T.`id` IN (
    SELECT U0.`id`
    FROM `testapp_tag` U0
    LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`)
    WHERE U1.`id` IS NULL))
ORDER BY T.`name` ASC;
</code>```

The NOT + IN + additional filter mix seems to throw MySQL out. It is definitely a bug.

The test in the NOT() looks for 2 parts. If the first part is true, the 2nd cannot possibly be true, regardless of whether the field can be null or not.  It is a redundant clause that seems to be the cause of the bug.

Taking a cue from ScrumMeister's answer, I confirm that the bug is due to some sort of caching against the last inserted ID against the AUTO_INCREMENT.

```<code>DROP TABLE IF EXISTS `testapp_tag`;

CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);

start transaction;
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t6", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t7", 3);
commit;

delete from testapp_tag where id = 6;   #######

explain extended
SELECT T.`id`, T.`name`, T.`parent_id`
FROM `testapp_tag` T
WHERE NOT (T.`id` IN (
    SELECT U0.`id`
    FROM `testapp_tag` U0
    LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`)
    WHERE U1.`id` IS NULL) AND T.`id` IS NOT NULL)
ORDER BY T.`name` ASC;
show warnings;
</code>```

Produces this plan

```<code>select `test`.`t`.`id` AS `id`,`test`.`t`.`name` AS `name`,`test`.`t`.`parent_id` AS `parent_id`
from `test`.`testapp_tag` `T` where ((not(<in_optimizer>(`test`.`t`.`id`,
<exists>(select 1 AS `Not_used` from `test`.`testapp_tag` `U0` left join `test`.`testapp_tag` `U1`
on((`test`.`u1`.`parent_id` = `test`.`u0`.`id`)) where (isnull(`test`.`u1`.`id`)
and (<cache>(`test`.`t`.`id`) = `test`.`u0`.`id`)))))) **or (`test`.`t`.`id` = 7)**)
order by `test`.`t`.`name`
</code>```

If the insert stops at t6, and the delete is also of t6, the bug is masked because the clause added is or (test.t.id = 6) which we have already deleted in the line marked    #######

Title: MySQL returning incorrect data?

Body:
Recently an issue came up in the Django community regarding testing of MySQL (using MyISAM).

Here's the django ticket: http://code.djangoproject.com/ticket/14661

One of the Django core developers came up with this test and many of us have been able to replicate it. Anyone have a guess as to what we are running into here? Is it simply a bug in MySQL or am I missing something?

Here's the test code and queries:

DROP TABLE IF EXISTS `testapp_tag`;
CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag`.`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;

Here's the output:

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS  NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
|  5 | t5   |         3 |
+----+------+-----------+
3 rows in set (0.00 sec)

mysql> SELECT `testapp_tag`.`id`, `testapp_tag`.`name`, `testapp_tag`.`parent_id` FROM `testapp_tag` WHERE NOT ((`testapp_tag` .`id` IN (SELECT U0.`id` FROM `testapp_tag` U0 LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`) WHERE U1.`id` IS NULL) AND `testapp_tag`.`id` IS NOT NULL)) ORDER BY `testapp_tag`.`name` ASC;
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | t1   |      NULL |
|  3 | t3   |         1 |
+----+------+-----------+
2 rows in set (0.01 sec)

Body:
This form works reliably:

SELECT T.`id`, T.`name`, T.`parent_id`
FROM `testapp_tag` T
WHERE NOT (T.`id` IN (
    SELECT U0.`id`
    FROM `testapp_tag` U0
    LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`)
    WHERE U1.`id` IS NULL))
ORDER BY T.`name` ASC;

The NOT + IN + additional filter mix seems to throw MySQL out. It is definitely a bug.

The test in the NOT() looks for 2 parts. If the first part is true, the 2nd cannot possibly be true, regardless of whether the field can be null or not.  It is a redundant clause that seems to be the cause of the bug.

Taking a cue from ScrumMeister's answer, I confirm that the bug is due to some sort of caching against the last inserted ID against the AUTO_INCREMENT.

DROP TABLE IF EXISTS `testapp_tag`;

CREATE TABLE `testapp_tag` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` varchar(10) NOT NULL,
    `parent_id` integer
);

start transaction;
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t1", NULL);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t2", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t3", 1);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t4", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t5", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t6", 3);
INSERT INTO `testapp_tag` (`name`, `parent_id`) VALUES ("t7", 3);
commit;

delete from testapp_tag where id = 6;   #######

explain extended
SELECT T.`id`, T.`name`, T.`parent_id`
FROM `testapp_tag` T
WHERE NOT (T.`id` IN (
    SELECT U0.`id`
    FROM `testapp_tag` U0
    LEFT OUTER JOIN `testapp_tag` U1 ON (U0.`id` = U1.`parent_id`)
    WHERE U1.`id` IS NULL) AND T.`id` IS NOT NULL)
ORDER BY T.`name` ASC;
show warnings;

Produces this plan

select `test`.`t`.`id` AS `id`,`test`.`t`.`name` AS `name`,`test`.`t`.`parent_id` AS `parent_id`
from `test`.`testapp_tag` `T` where ((not(<in_optimizer>(`test`.`t`.`id`,
<exists>(select 1 AS `Not_used` from `test`.`testapp_tag` `U0` left join `test`.`testapp_tag` `U1`
on((`test`.`u1`.`parent_id` = `test`.`u0`.`id`)) where (isnull(`test`.`u1`.`id`)
and (<cache>(`test`.`t`.`id`) = `test`.`u0`.`id`)))))) **or (`test`.`t`.`id` = 7)**)
order by `test`.`t`.`name`

If the insert stops at t6, and the delete is also of t6, the bug is masked because the clause added is or (test.t.id = 6) which we have already deleted in the line marked    #######


问:
Background-image won't show up in any other browsers
Decided to place an image as background and it looks fine in my browser but doesn't anywhere else. Haven't found any answers yet. HELP.

```<code><style> html{
background-image:url(https://i.imgur.com/02nQ1hD.jpg);
background-color:rgb(105,95,42);} </style>
</code>```

I set a color as backup.

The webpage: https://codepen.io/Miosad/full/XzRPXR

EDIT: I tried the code with another image and that seems to be the problem. Any idea why this would be? The image url is: https://i.imgur.com/02nQ1hD.jpg

EDIT 2: Found out it was the image. Thanks for all the help and sorry for wasting your time!

答:
You need to apply the background to body rather than html:

```<code>body{
  background-image:url(https://i.imgur.com/02nQ1hD.jpg);
  background-color:rgb(105,95,42);
  color:rgb(0,0,0);
  font-family:garamond, bookman, palatino, georgia;
  -webkit-text-size-adjust: 100%;
}
</code>```

I've created an updated CodePen showcasing this here.

Body:
Decided to place an image as background and it looks fine in my browser but doesn't anywhere else. Haven't found any answers yet. HELP.

I set a color as backup.

The webpage: https://codepen.io/Miosad/full/XzRPXR

EDIT: I tried the code with another image and that seems to be the problem. Any idea why this would be? The image url is: https://i.imgur.com/02nQ1hD.jpg

EDIT 2: Found out it was the image. Thanks for all the help and sorry for wasting your time!

Body:
You need to apply the background to body rather than html:

body{
  background-image:url(https://i.imgur.com/02nQ1hD.jpg);
  background-color:rgb(105,95,42);
  color:rgb(0,0,0);
  font-family:garamond, bookman, palatino, georgia;
  -webkit-text-size-adjust: 100%;
}

I've created an updated CodePen showcasing this here.


问:
Building a Transition Matrix using words in Python/Numpy
Im trying to build a 3x3 transition matrix with this data

```<code>days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']
</code>```

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

```<code>self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix
</code>```

for every type of weather I need to calculate the probability for the next day

答:
I like a combination of pandas and itertools for this.  The code block is a bit longer than the above, but don't conflate verbosity with speed.  (The window func should be very fast; the pandas portion will be slower admittedly.)

First, make a "window" function.  Here's one from the itertools cookbook.  This gets you to a list of tuples of transitions (state1 to state2).

```<code>from itertools import islice

def window(seq, n=2):
    """Sliding window width n from seq.  From old itertools recipes."""
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

# list(window(days))
# [('rain', 'rain'),
#  ('rain', 'rain'),
#  ('rain', 'clouds'),
#  ('clouds', 'rain'),
#  ('rain', 'sun'),
# ...
</code>```

Then use a pandas groupby + value counts operation to get a transition matrix from each state1 to each state2:

```<code>import pandas as pd

pairs = pd.DataFrame(window(days), columns=['state1', 'state2'])
counts = pairs.groupby('state1')['state2'].value_counts()
probs = (counts / counts.sum()).unstack()
</code>```

Your result looks like this:

```<code>print(probs)
state2  clouds  rain   sun
state1
clouds    0.13  0.09  0.10
rain      0.06  0.11  0.09
sun       0.13  0.06  0.23
</code>```

Body:
Im trying to build a 3x3 transition matrix with this data

days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix

for every type of weather I need to calculate the probability for the next day

Body:
I like a combination of pandas and itertools for this.  The code block is a bit longer than the above, but don't conflate verbosity with speed.  (The window func should be very fast; the pandas portion will be slower admittedly.)

First, make a "window" function.  Here's one from the itertools cookbook.  This gets you to a list of tuples of transitions (state1 to state2).

from itertools import islice

def window(seq, n=2):
    """Sliding window width n from seq.  From old itertools recipes."""
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

# list(window(days))
# [('rain', 'rain'),
#  ('rain', 'rain'),
#  ('rain', 'clouds'),
#  ('clouds', 'rain'),
#  ('rain', 'sun'),
# ...

Then use a pandas groupby + value counts operation to get a transition matrix from each state1 to each state2:

import pandas as pd

pairs = pd.DataFrame(window(days), columns=['state1', 'state2'])
counts = pairs.groupby('state1')['state2'].value_counts()
probs = (counts / counts.sum()).unstack()

Your result looks like this:

print(probs)
state2  clouds  rain   sun
state1
clouds    0.13  0.09  0.10
rain      0.06  0.11  0.09
sun       0.13  0.06  0.23