问:
Saving 2 plots into one PDF with 2 pages?
Let's say I have from output 2 matplotlib plots in my jupyter notebook (for example purposes these charts are the exact same).

```<code>import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()
</code>```

How can I save these 2 charts into a single PDF with each chart having its own page, instead of having them combined onto a single page?

答:
@sascha. Voila the code you referred to. Pages referrals sometimes seem to break after a few years without reason ;-) Teh code example...</p>

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is a demo of creating a pdf file with several pages,
as well as adding metadata and annotations to pdf files.
"""

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.attach_note("plot of sin(x)")  # you can add a pdf note to
                                       # attach metadata to a page
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()
</code>```

Body:
Let's say I have from output 2 matplotlib plots in my jupyter notebook (for example purposes these charts are the exact same).

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()

How can I save these 2 charts into a single PDF with each chart having its own page, instead of having them combined onto a single page?

Body:
@sascha. Voila the code you referred to. Pages referrals sometimes seem to break after a few years without reason ;-) Teh code example...

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is a demo of creating a pdf file with several pages,
as well as adding metadata and annotations to pdf files.
"""

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.attach_note("plot of sin(x)")  # you can add a pdf note to
                                       # attach metadata to a page
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()


来源: stackexchange

问:
calling to bubbleSort method from main to print sorted array
How do you call to the bubbleSort method from the main method in order to print a sorted list array. I have generated 10 random numbers into an array but I have not figured out how to call to the bubbleSort and print results. What am I missing here?

public class Bubblesort{

public static void main(String[] args) {

```<code>    int [] numbers = new int[10];
    //Generate 10 random numbers between 1-100
      for(int i = 0; i < numbers.length; i++) {
        numbers[i] = (int)(Math.random() * 100 + 1);
        }//end of loop
    System.out.println("The unsorted list is: " + Arrays.toString(numbers));
         //Solution added
         bubbleSort(numbers); //Call to sort the array
    System.out.println("The sorted list is: " + Arrays.toString(numbers));
</code>```

}

```<code>    public static void bubbleSort(int[] list)
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--)
          {
             for (int j = 0; j < i; j++)
             {
               if (list[j] > list[j + 1])
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;

               }
             }
          }
       }
</code>```

}

答:
You just are not calling your function.

`public static void main(String[] args)
{
    int [] numbers = new int[10];

```<code>//Generate 10 random numbers between 1-100

  for(int i = 0; i < numbers.length; i++) {
    numbers[i] = (int)(Math.random() * 100 + 1);
    }//end of loop
bubblesort(numbers);
System.out.println("The unsorted list is: " + Arrays.toString(numbers));}
</code>```

As you see I added the bubblesort(numbers); which calls the function you have made. Continue asking questions as I see you are quite new with Java and welcome to the world of coding!

ContentLicense: CC BY-SA 3.0

Body:
How do you call to the bubbleSort method from the main method in order to print a sorted list array. I have generated 10 random numbers into an array but I have not figured out how to call to the bubbleSort and print results. What am I missing here?

public class Bubblesort{

public static void main(String[] args) {

    int [] numbers = new int[10];
    //Generate 10 random numbers between 1-100
      for(int i = 0; i < numbers.length; i++) {
        numbers[i] = (int)(Math.random() * 100 + 1);
        }//end of loop
    System.out.println("The unsorted list is: " + Arrays.toString(numbers));
         //Solution added
         bubbleSort(numbers); //Call to sort the array
    System.out.println("The sorted list is: " + Arrays.toString(numbers));

}

    public static void bubbleSort(int[] list)
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--)
          {
             for (int j = 0; j  list[j + 1])
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;

               }
             }
          }
       }

}

Body:
You just are not calling your function.

`public static void main(String[] args)
{
    int [] numbers = new int[10];

//Generate 10 random numbers between 1-100

  for(int i = 0; i < numbers.length; i++) {
    numbers[i] = (int)(Math.random() * 100 + 1);
    }//end of loop
bubblesort(numbers);
System.out.println("The unsorted list is: " + Arrays.toString(numbers));}

As you see I added the bubblesort(numbers); which calls the function you have made. Continue asking questions as I see you are quite new with Java and welcome to the world of coding!


问:
Java 32 bit memory threshold on 64 bit Windows 10
I've got some software that requires around 1500m of memory to run correctly. I force this amount at the start using xms and xmx to make sure it has the memory it needs. I used to run it on Windows XP or Windows 7 and it ran fine. After switching to Windows 10 I suddenly find I don't have enough memory to run it anymore. After researching how memory in Java works I came across the following information on this page:

http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit

Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G.

It sounds like I've been running on the edge of what 32bit Java is capable of. Testing the limits of my machine it seems my current max is about 1.1g. At the moment switching to 64bit may not be on the table, so I'm trying to figure out how to get back the roughly .5g I've lost from my max memory threshold. I've tried researching all of the things listed in the FAQ that could affect it.

available swap: This appears to be the page file or virtual memory. Apparently increasing this can sometimes help. Sometimes when I increase this I see a temporary improvement after a restart, but the fix never seems to last if I restart again.

kernel address space usage: This seems like it’s the memory ceiling for the operating system. Nothing we can do the change this right?

memory fragmentation: Supposedly Windows 10 is actually better at handling this than previous versions of Windows. So this shouldn’t be a factor.

VM overhead: Seems like it’s referring to RAM usage from other virtual machines. Other than Java I don’t think I have anything else running that counts as a virtual machine.

Is there any solid way to identify and correct what could be causing the difference in performance between versions of Windows? It's super frustrating because I have more physical memory now than ever, but the only RAM that matters is the RAM JVM is allowed to use, which is now somehow less.

Update

I hear you. I know I can fix it easily switching to 64 bit; my question is how I can fix it without doing that. Isn't it helpful to understand how JVM determines it's max heap for scholarly reasons as well as practical? I doubt there are many apps that hit the upper limit of 64 bit Java, but wouldn't Java behave the same way if there were?

答:
I wasn't able to figure out why the memory was different between systems, but I did learn of a LARGEADDRESSAWARE flag I could set on the Java.exe that would allow it to have up to 1G more memory.

Out of several tools people were typically using to set the flag I found this custom coded python script that attempts to set it on any .exe file you hand it. Using that I was able to feed it the Java.exe and now everything works.

It would appear that setting this flag is not typically recommended, but no side effects so far. I'll use this until I can properly switch everything to 64 bit.

https://github.com/pyinstaller/pyinstaller/issues/1288

```<code># See http://en.wikibooks.org/wiki/X86_Disassembly/Windows_Executable_Files#PE_Header
# and https://msdn.microsoft.com/en-us/library/ms680349%28v=vs.85%29.aspx

import struct

IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020
PE_HEADER_OFFSET = 60
CHARACTERISTICS_OFFSET = 18

def set_large_address_aware(filename):
    f = open(filename, 'rb+')
    # Check for MZ Header
    if f.read(2) != b'MZ':
        print('Not MZ')
        return False
    # Get PE header location
    f.seek(PE_HEADER_OFFSET)
    pe_header_loc, = struct.unpack('i', f.read(4))
    # Get PE header, check it
    f.seek(pe_header_loc)
    if f.read(4) != b'PE\0\0':
        print('error in PE header')
        return False
    # Get Characteristics, check if IMAGE_FILE_LARGE_ADDRESS_AWARE bit is set
    charac_offset = pe_header_loc + 4 + CHARACTERISTICS_OFFSET
    f.seek(charac_offset)
    bits, = struct.unpack('h', f.read(2))
    if (bits & IMAGE_FILE_LARGE_ADDRESS_AWARE) == IMAGE_FILE_LARGE_ADDRESS_AWARE:
        return True
    else:
        print('large_address_aware is NOT set - will try to set')
        f.seek(charac_offset)
        bytes = struct.pack('h', (bits | IMAGE_FILE_LARGE_ADDRESS_AWARE))
        f.write(bytes)
    f.close()
    return False

if set_large_address_aware('file.exe'):
    print('large_address_aware is set')
else:
    print('large_address_aware was NOT set')
</code>```

Body:
I wasn't able to figure out why the memory was different between systems, but I did learn of a LARGEADDRESSAWARE flag I could set on the Java.exe that would allow it to have up to 1G more memory.

Out of several tools people were typically using to set the flag I found this custom coded python script that attempts to set it on any .exe file you hand it. Using that I was able to feed it the Java.exe and now everything works.

It would appear that setting this flag is not typically recommended, but no side effects so far. I'll use this until I can properly switch everything to 64 bit.

https://github.com/pyinstaller/pyinstaller/issues/1288

# See http://en.wikibooks.org/wiki/X86_Disassembly/Windows_Executable_Files#PE_Header
# and https://msdn.microsoft.com/en-us/library/ms680349%28v=vs.85%29.aspx

import struct

IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020
PE_HEADER_OFFSET = 60
CHARACTERISTICS_OFFSET = 18

def set_large_address_aware(filename):
    f = open(filename, 'rb+')
    # Check for MZ Header
    if f.read(2) != b'MZ':
        print('Not MZ')
        return False
    # Get PE header location
    f.seek(PE_HEADER_OFFSET)
    pe_header_loc, = struct.unpack('i', f.read(4))
    # Get PE header, check it
    f.seek(pe_header_loc)
    if f.read(4) != b'PE\0\0':
        print('error in PE header')
        return False
    # Get Characteristics, check if IMAGE_FILE_LARGE_ADDRESS_AWARE bit is set
    charac_offset = pe_header_loc + 4 + CHARACTERISTICS_OFFSET
    f.seek(charac_offset)
    bits, = struct.unpack('h', f.read(2))
    if (bits & IMAGE_FILE_LARGE_ADDRESS_AWARE) == IMAGE_FILE_LARGE_ADDRESS_AWARE:
        return True
    else:
        print('large_address_aware is NOT set - will try to set')
        f.seek(charac_offset)
        bytes = struct.pack('h', (bits | IMAGE_FILE_LARGE_ADDRESS_AWARE))
        f.write(bytes)
    f.close()
    return False

if set_large_address_aware('file.exe'):
    print('large_address_aware is set')
else:
    print('large_address_aware was NOT set')


问:
How do I initialize app with external JSON?
I need to initialize my app with external json data. The problem I'm getting is that I can't force the app to wait loading children components for after the data arrives.

For example, let's use this as an example (not external loading here, I'm using setTimeout to make a point of waiting for data to arrive).

```<code>new Vue({
  el: '#app',
  router,
  render: h => h(App),
  beforeCreate() {
    setTimeout(() => {
      this.myConfig = 'loaded'; // I realize I'm not using $data here, but nevermind
    }, 1000)
  },
});
</code>```

And in my child component

```<code>created() {
  console.log(this.$root.myConfig);
},
</code>```

The problem is that created from the child is called before the beforeCreate finishes.

Data won't change from initial state. Thus, I don't need the reactivity of VueX.

As I'm using vue-router, an option maybe is to create a loading component as the default route, which should load the data, and then on arrival switch to the correct initial state.

Also, by looking at Async Components, maybe it's what I should use, but I get the feeling that it's a little more complicated than what I need.

Is there a best practice way to achieve this?

答:
Maybe this directs you:

console.log('wait for 1 second')

new Vue({
  template: '#app',
  created () {
    setTimeout(() => {
      this.myConfig = 'loaded'
      this.$mount('#app')
    }, 1000)
  },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template id="app">
  <p>{{ myConfig }}</p>
</template>

<script src="https://unpkg.com/vue@2.5.4/dist/vue.min.js"></script></code>```

For more advanced 'preinitialization' look at this example.

ContentLicense: CC BY-SA 4.0

Body:
I need to initialize my app with external json data. The problem I'm getting is that I can't force the app to wait loading children components for after the data arrives.

For example, let's use this as an example (not external loading here, I'm using setTimeout to make a point of waiting for data to arrive).

new Vue({
  el: '#app',
  router,
  render: h => h(App),
  beforeCreate() {
    setTimeout(() => {
      this.myConfig = 'loaded'; // I realize I'm not using $data here, but nevermind
    }, 1000)
  },
});

And in my child component

created() {
  console.log(this.$root.myConfig);
},

The problem is that created from the child is called before the beforeCreate finishes.

Data won't change from initial state. Thus, I don't need the reactivity of VueX.

As I'm using vue-router, an option maybe is to create a loading component as the default route, which should load the data, and then on arrival switch to the correct initial state.

Also, by looking at Async Components, maybe it's what I should use, but I get the feeling that it's a little more complicated than what I need.

Is there a best practice way to achieve this?

Body:
Maybe this directs you:

console.log('wait for 1 second')

new Vue({
  template: '#app',
  created () {
    setTimeout(() => {
      this.myConfig = 'loaded'
      this.$mount('#app')
    }, 1000)
  },
});

<template id="app">
  <p>{{ myConfig }}</p>
</template>

<script src="https://unpkg.com/vue@2.5.4/dist/vue.min.js"></script>

For more advanced 'preinitialization' look at this example.


问:
(Python, Pandas) - How do I get everything to the left of a certain character?
I have a column, market_area that I want to abbreviate by keeping only the part of the string to the left of the hyphen.

For example, my data is like this:

```<code>import pandas as pd
tmp = pd.DataFrame({'market_area': ['San Francisco-Oakland-San Jose',
                                    None,
                                    'Dallas-Fort Worth',
                                    'Los Angeles-Riverside-Orange County'],
                    'val': [1,2,3,4]})
</code>```

My desired output would be:

```<code>['San Francisco', None, 'Dallas', 'Los Angeles']
</code>```

I am able to split based on the hyphen:

```<code>tmp['market_area'].str.split('-')
</code>```

But how do I extract only the part to the left of the hyphen?

答:
You can extract the first element in the splitted list using .str[0]:

```<code>tmp.market_area.str.split('-').str[0]
Out[3]:
0    San Francisco
1             None
2           Dallas
3      Los Angeles
Name: market_area, dtype: object
</code>```

Or use str.extract method with regex ^([^-]*).*, which captures the pattern until the first -:

```<code>tmp.market_area.str.extract('^([^-]*).*', expand=False)
Out[5]:
0    San Francisco
1              NaN
2           Dallas
3      Los Angeles
Name: market_area, dtype: object
</code>```

Body:
I have a column, market_area that I want to abbreviate by keeping only the part of the string to the left of the hyphen.

For example, my data is like this:

import pandas as pd
tmp = pd.DataFrame({'market_area': ['San Francisco-Oakland-San Jose',
                                    None,
                                    'Dallas-Fort Worth',
                                    'Los Angeles-Riverside-Orange County'],
                    'val': [1,2,3,4]})

My desired output would be:

['San Francisco', None, 'Dallas', 'Los Angeles']

I am able to split based on the hyphen:

tmp['market_area'].str.split('-')

But how do I extract only the part to the left of the hyphen?

Body:
You can extract the first element in the splitted list using .str[0]:

tmp.market_area.str.split('-').str[0]
Out[3]:
0    San Francisco
1             None
2           Dallas
3      Los Angeles
Name: market_area, dtype: object

Or use str.extract method with regex ^([^-]*).*, which captures the pattern until the first -:

tmp.market_area.str.extract('^([^-]*).*', expand=False)
Out[5]:
0    San Francisco
1              NaN
2           Dallas
3      Los Angeles
Name: market_area, dtype: object


问:
Can't receive UDP Packets in Java
I'm trying to receive some UDP packets on a Java MulticastSocket.

I can see the packets arriving in wireshark and the code works for other people, but not for me.

I honestly don't know what I'm doing wrong.

I have disabled my firewall and antivirus.

I'm running Windows 10 and IntelliJ 2017.2.5.

I'm creating a MulticastSocket with a portnumber (2000 or 2001) as a parameter.

My JRE is 1.8.0_152 and I'm using the JDK supplied by JetBrains.

This is how I'm creating the MulticastSocket:

```<code>this.socket = new MulticastSocket(this.portNum);
//this.socket = new MulticastSocket();
this.socket.setReceiveBufferSize(1 << 17);
this.socket.joinGroup(InetAddress.getByName(this.ip));
</code>```

And, in a while loop, I try to receive data like this:

```<code>while(!this.socket.isClosed())
    {
        byte[] buffer = new byte[500];
        DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
        try
        {
            this.socket.receive(incomingPacket);
            ...
</code>```

答:
Things to check are:

Make sure you bind your UDP socket to the interface you want to receive on. This is different for Windows and for Linux. For Windows: Bind to the IP address of the interface you want to receive on. On Linux bind to 0.0.0.0 to receive on all interfaces. (Receiving just on a specific interface is non-trivial on Linux.)

Make sure your this.ip is your multicast address, e.g. 224.1.2.3.

Title: Can't receive UDP Packets in Java

Body:
I'm trying to receive some UDP packets on a Java MulticastSocket.

I can see the packets arriving in wireshark and the code works for other people, but not for me.

I honestly don't know what I'm doing wrong.

I have disabled my firewall and antivirus.

I'm running Windows 10 and IntelliJ 2017.2.5.

I'm creating a MulticastSocket with a portnumber (2000 or 2001) as a parameter.

My JRE is 1.8.0_152 and I'm using the JDK supplied by JetBrains.

This is how I'm creating the MulticastSocket:

this.socket = new MulticastSocket(this.portNum);
//this.socket = new MulticastSocket();
this.socket.setReceiveBufferSize(1 << 17);
this.socket.joinGroup(InetAddress.getByName(this.ip));

And, in a while loop, I try to receive data like this:

while(!this.socket.isClosed())
    {
        byte[] buffer = new byte[500];
        DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
        try
        {
            this.socket.receive(incomingPacket);
            ...


问:
Getting "Firefox can’t establish a connection to the server at localhost" despite having SSL enabled
Am creating a ASP.NET Web Application with Identity using the Individual User Account method of authentication in ASP.NET Core:

When I run the app, I get the error message in my browser:

Unable to connect:
     Firefox can’t establish a connection to the server at localhost:44330.
     ...

In my search for a solution, I found that having SSL disabled could cause this but that was enabled by default.

I have also added:

```<code>services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});
</code>```

to the public void ConfigureServices(IServiceCollection services) method and added:

```<code>var options = new RewriteOptions()
            .AddRedirectToHttps();

        app.UseRewriter(options);
</code>```

to the public void Configure(IApplicationBuilder app, IHostingEnvironment env) method

Other things I tried based on information I got searching for a solution

I have also installed URL Rewrite

Tried different browsers

Checked that my browsers are permitted to go past firewall

All with no luck.

答:
After many hours of trials and errors, I was able to get my web app running on Chrome by following these steps:

For Chrome

Copy and past chrome://net-internals/#hsts into your browser (Chrome) and hit run

In the page that opens, locate Delete domain security policies Enter localhost into the Domain field and click delete.

The app now runs on Chrome. I'll update this post as soon as I find a solution that works across all browsers.

I also found that the launch browser url had to match the url specified in the Enable SSL checkbox had to match:

To get here, Right click on Project -> Properties -> Debug

Body:
Am creating a ASP.NET Web Application with Identity using the Individual User Account method of authentication in ASP.NET Core:

When I run the app, I get the error message in my browser:

Unable to connect:
     Firefox can’t establish a connection to the server at localhost:44330.
     ...

In my search for a solution, I found that having SSL disabled could cause this but that was enabled by default.

I have also added:

services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});

to the public void ConfigureServices(IServiceCollection services) method and added:

var options = new RewriteOptions()
            .AddRedirectToHttps();

        app.UseRewriter(options);

to the public void Configure(IApplicationBuilder app, IHostingEnvironment env) method

Other things I tried based on information I got searching for a solution

I have also installed URL Rewrite

Tried different browsers

Checked that my browsers are permitted to go past firewall

All with no luck.


问:
Force mongodb to output strict JSON
I want to consume the raw output of some MongoDB commands in other programs that speak JSON. When I run commands in the mongo shell, they represent Extended JSON, fields in "shell mode", with special fields like NumberLong , Date, and Timestamp. I see references in the documentation to "strict mode", but I see no way to turn it on for the shell, or a way to run commands like db.serverStatus() in things that do output strict JSON, like mongodump. How can I force Mongo to output standards-compliant JSON?

There are several other questions on this topic, but I don't find any of their answers particularly satisfactory.

答:
To build on the answer from @jbyler, you can strip out the numberLongs using sed after you get your data - that is if you're using linux.</p>

```<code>mongoexport --jsonArray -d dbName -c collection -q '{fieldName: {$regex: ".*turkey.*"}}' | sed -r 's/\{ "[$]numberLong" : "([0-9]+)" }/"\1"/g' | json_pp
</code>```

Title: Force mongodb to output strict JSON

Body:
To build on the answer from @jbyler, you can strip out the numberLongs using sed after you get your data - that is if you're using linux.

mongoexport --jsonArray -d dbName -c collection -q '{fieldName: {$regex: ".*turkey.*"}}' | sed -r 's/\{ "[$]numberLong" : "([0-9]+)" }/"\1"/g' | json_pp


问:
Versioning library like SQLite database library?
I like how SQLite library can be included into an application and the application has a full-fledged database to use.

Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?

答:
In my opinion Firebird is one of the best choices for embedded DB scenarios.

Also Microsoft SQL Server Compact (closed source, but free) might be suitable, however it less capable than Firebird.

EDIT:
I misread you question. If you don't need RDBMS, you can try to embed SVN to your application.

OwnerDisplayName: Swaroop C H

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Cebjyre

OwnerDisplayName: aku

LastEditorDisplayName: aku


问:
Asp.net open-source project as a learning source in c#
I am looking for an open-source asp.net (preferably .net 2.0) project in c#. It doesn't matter if it is some kind of a shop or cms or anything else. What matters is the size of the project that must be at least of medium size (not a simple app that was done in 2 weeks by one developer) and it would be a great advantage if the project contained unit tests and some kind of case study.

I want to use this project as a learning source. I know there are many books and web resources about asp.net but i would like to see how bigger projects are implemented. I am especially interested in implementation of user rights to certain parts of application, separation between html and application logic and i would like to see if developers use .net web controls or write their own custom controls.

Thanks in advance.

答:
ScrewTurn Wiki is a nice open source project.

ScrewTurn Wiki is a fast, powerful and
  simple ASP.NET wiki engine, installs
  in minutes and it's available in
  different packages.

We use it for documentation in our team. There's a lot of different things to learn from the code: theming, compression, how to write an RSS feed, configuration, multi-language support ...

OwnerDisplayName: empi

OwnerDisplayName: splattne

LastEditorDisplayName: splattne


问:
Porting C++ to C# - templates
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

```<code>template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
</code>```

Clearly for this example I could do:

```<code>public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}
</code>```

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

答:
This is as close as I could think of:

```<code>public class Factorial<T>
    where T : IConvertible
    {
        public T GetFactorial(T t)
        {
            int int32 = Convert.ToInt32(t);
            if (int32 == 0)
                return (T) Convert.ChangeType( 1, typeof(T));
            return GetFactorial( (T) Convert.ChangeType(int32-1, typeof(T)) );
        }
    }
</code>```

The problem is you cannot define generics and limit it to ValueTypes. This will work for byte, Int16 and Int32. Also for small values of Int64.

Title: Porting C++ to C# - templates

Body:
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Clearly for this example I could do:

public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

Body:
This is as close as I could think of:

public class Factorial<T>
    where T : IConvertible
    {
        public T GetFactorial(T t)
        {
            int int32 = Convert.ToInt32(t);
            if (int32 == 0)
                return (T) Convert.ChangeType( 1, typeof(T));
            return GetFactorial( (T) Convert.ChangeType(int32-1, typeof(T)) );
        }
    }

The problem is you cannot define generics and limit it to ValueTypes. This will work for byte, Int16 and Int32. Also for small values of Int64.


问:
Save as csv file in javascript
I am still a beginner in javascript and still training , I make a code that computes sunrise, sunset, ,noon & midnight times.

I could everything make w/o problems (even it is not professional) and with help of many topics in StackOverflow.

I can use document.write() or console.log() to use my result.

I would know, how to save my result as csv file instead of displaying my result with document.write()

My displayed result is already in csv format:

01/01/yyyy,06:00:00,12:00:00,18:00:00,00:00:00 ......
  31/12/yyyy,06:00:00,12:00:00,18:00:00,00:00:00

Conclusion: how to save my result as csv file, and please with explaining.

Html:

```<code><!DOCTYPE html> <html>
    <head>
        <title>Sunrise and Sunset</title>
    </head>
    <body>
    <form>
    Latitude: <input id='lat' value='52.0'>
    <br>
    Longitude: <input id='lon' value='10.0'>
    <br>
    Elevation: <input id='elv' value='0.0'>
    <br><br>
    Year: <input id='yr' value='2000'>
    <br>
    Time zone: <input id='tz' value='1.0'>
    <br>
    <button id='btn' onclick='rechner();'>
    Get your data
    </button>
    </body> </html>
</code>```

Javascript:

```<code>//-------Degrees to radians------//
function toRad(angle){

    return angle*Math.PI/180;
};

//------Radians to degrees-------//
function toDeg(angle){

    return angle*180/Math.PI;
};

//---------Main function-------//

function rechner(){
    var lat,lon,elv,year,tzone;

lat = parseFloat(document.getElementById('lat').value);
lon = parseFloat(document.getElementById('lon').value);
elv = parseFloat(document.getElementById('elv').value);

year = parseInt(document.getElementById('yr').value);
tzone = parseFloat(document.getElementById('tz').value);

    var dip_angle = 0.0347*Math.sqrt(elv);
//dip angle for sunrise and sunset accounting for elevation of the location, it is here in degrees expressed

    var date = new Date(year,0,1,12);
    var time = date.getTime();
    var julian_date = (time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5;
    var d = julian_date - 2451545.0;

var yr = date.getFullYear();
// get year from the date 01/01/YYYY

    for(var i=0; i<=((yr%4)==0 ? 365 : 364); i++){

    var D = d+i;

//------Solar approximate coordinates----//

    var g = ((357.529 + 0.98560028*D)+360)%360;
//Mean anomaly of the Sun

    var q = ((280.459 + 0.98564736*D)+360)%360;
//Mean longitude of the Sun

    var L = ((q + 1.915*Math.sin(toRad(g)) + 0.020*Math.sin(toRad(2*g)))+360)%360;
//Geocentric apparent ecliptic longitude of the Sun (adjusted for aberration)

    var e = 23.439 - 0.00000036*D;
//Mean obliquity of the ecliptic

    var ra = ((toDeg(Math.atan2(Math.cos(toRad(e))*Math.sin(toRad(L)),Math.cos(toRad(L)))))+360)%360;
// Right ascension in deg

    var dec = toDeg(Math.asin(Math.sin(toRad(e))*Math.sin(toRad(L))));
// Declination in deg

    var eqt = (((q - ra)/15)+24)%24
//equation of time, in hrs

    var R = 1.00014 - 0.01671*Math.cos(toRad(g)) - 0.00014*Math.cos(toRad(2*g));
// Distance Sun-Earth in AU

    var SD = 0.2666/R;
// Semi-diameter of sun in degrees

//---function calculates timestamp from noon to the wanted angle under horizon--//

function timeTodip (angle){
    return 1/15*toDeg(Math.acos((-Math.sin(toRad(angle))-Math.sin(toRad (lat))*Math.sin(toRad(dec)))/(Math.cos(toRad(lat))*Math.cos(toRad(dec)))));
};

//function renders hh.hhh in range [0,24]
    function rendHr(y){
if(y>=0 && y<=24){return y;}
else if(y>24){return y%24;}
else{return y%24 + 24}
    };

//---function converts hh.hhhh to hh:mm:ss
    function hhToHMS(nbr){
var decimalTimeString = nbr;
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
return n.toTimeString().slice(0, 8)
};

//---function gets date as DD/MM/YYYY---//

function convertDate(inputFormat) {
  function pad(s) { return (s < 10) ? '0' + s : s; }
  var z = new Date(inputFormat);
  return [pad(z.getDate()), pad(z.getMonth()+1), z.getFullYear()].join('/');
};

var noon = rendHr(12 + tzone - lon/15 - eqt); //noon time in format hh.hhhh

//--------Sunrise and sunset calc--------//

var sunrise = noon - timeTodip(0.833+dip_angle); //sunrise
var sunset = noon + timeTodip(0.833+dip_angle); //sunset

var mid = (24-rendHr(sunset-sunrise))/2 + sunset; //solar midnight

var nbrDay= new Date((10957+(julian_date - 2451545.0)+i)*86400000);

document.write(convertDate(nbrDay)+','+hhToHMS(sunrise)+','+hhToHMS(noon)+','+hhToHMS(sunset)+','+hhToHMS(mid)+'<br>');

    };
};
</code>```

thanks for any help

Edit:
Jsfiddle

js linter says it's good

答:
Include this handy "saveAs" function somewhere in your document.

```<code>function saveAs(text, filename){
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=urf-8,'+encodeURIComponent(text));
  pom.setAttribute('download', filename);
  pom.click();
};
</code>```

And then use it:

```<code>saveAs(myCSVString, "data.csv");
</code>```

Title: Save as csv file in javascript

Body:
I am still a beginner in javascript and still training , I make a code that computes sunrise, sunset, ,noon & midnight times.

I could everything make w/o problems (even it is not professional) and with help of many topics in StackOverflow.

I can use document.write() or console.log() to use my result.

I would know, how to save my result as csv file instead of displaying my result with document.write()

My displayed result is already in csv format:

01/01/yyyy,06:00:00,12:00:00,18:00:00,00:00:00 ......
  31/12/yyyy,06:00:00,12:00:00,18:00:00,00:00:00

Conclusion: how to save my result as csv file, and please with explaining.

Html:

<!DOCTYPE html>

        <title>Sunrise and Sunset</title>

    <form>
    Latitude: <input id='lat' value='52.0'>

    Longitude: <input id='lon' value='10.0'>

    Elevation: <input id='elv' value='0.0'>

    Year: <input id='yr' value='2000'>

    Time zone: <input id='tz' value='1.0'>

    <button id='btn' onclick='rechner();'>
    Get your data
    </button>

Javascript:

//-------Degrees to radians------//
function toRad(angle){

    return angle*Math.PI/180;
};

//------Radians to degrees-------//
function toDeg(angle){

    return angle*180/Math.PI;
};

//---------Main function-------//

function rechner(){
    var lat,lon,elv,year,tzone;

lat = parseFloat(document.getElementById('lat').value);
lon = parseFloat(document.getElementById('lon').value);
elv = parseFloat(document.getElementById('elv').value);

year = parseInt(document.getElementById('yr').value);
tzone = parseFloat(document.getElementById('tz').value);

    var dip_angle = 0.0347*Math.sqrt(elv);
//dip angle for sunrise and sunset accounting for elevation of the location, it is here in degrees expressed

    var date = new Date(year,0,1,12);
    var time = date.getTime();
    var julian_date = (time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5;
    var d = julian_date - 2451545.0;

var yr = date.getFullYear();
// get year from the date 01/01/YYYY

    for(var i=0; i<=((yr%4)==0 ? 365 : 364); i++){

    var D = d+i;

//------Solar approximate coordinates----//

    var g = ((357.529 + 0.98560028*D)+360)%360;
//Mean anomaly of the Sun

    var q = ((280.459 + 0.98564736*D)+360)%360;
//Mean longitude of the Sun

    var L = ((q + 1.915*Math.sin(toRad(g)) + 0.020*Math.sin(toRad(2*g)))+360)%360;
//Geocentric apparent ecliptic longitude of the Sun (adjusted for aberration)

    var e = 23.439 - 0.00000036*D;
//Mean obliquity of the ecliptic

    var ra = ((toDeg(Math.atan2(Math.cos(toRad(e))*Math.sin(toRad(L)),Math.cos(toRad(L)))))+360)%360;
// Right ascension in deg

    var dec = toDeg(Math.asin(Math.sin(toRad(e))*Math.sin(toRad(L))));
// Declination in deg

    var eqt = (((q - ra)/15)+24)%24
//equation of time, in hrs

    var R = 1.00014 - 0.01671*Math.cos(toRad(g)) - 0.00014*Math.cos(toRad(2*g));
// Distance Sun-Earth in AU

    var SD = 0.2666/R;
// Semi-diameter of sun in degrees

//---function calculates timestamp from noon to the wanted angle under horizon--//

function timeTodip (angle){
    return 1/15*toDeg(Math.acos((-Math.sin(toRad(angle))-Math.sin(toRad (lat))*Math.sin(toRad(dec)))/(Math.cos(toRad(lat))*Math.cos(toRad(dec)))));
};

//function renders hh.hhh in range [0,24]
    function rendHr(y){
if(y>=0 && y<=24){return y;}
else if(y>24){return y%24;}
else{return y%24 + 24}
    };

//---function converts hh.hhhh to hh:mm:ss
    function hhToHMS(nbr){
var decimalTimeString = nbr;
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
return n.toTimeString().slice(0, 8)
};

//---function gets date as DD/MM/YYYY---//

function convertDate(inputFormat) {
  function pad(s) { return (s < 10) ? '0' + s : s; }
  var z = new Date(inputFormat);
  return [pad(z.getDate()), pad(z.getMonth()+1), z.getFullYear()].join('/');
};

var noon = rendHr(12 + tzone - lon/15 - eqt); //noon time in format hh.hhhh

//--------Sunrise and sunset calc--------//

var sunrise = noon - timeTodip(0.833+dip_angle); //sunrise
var sunset = noon + timeTodip(0.833+dip_angle); //sunset

var mid = (24-rendHr(sunset-sunrise))/2 + sunset; //solar midnight

var nbrDay= new Date((10957+(julian_date - 2451545.0)+i)*86400000);

document.write(convertDate(nbrDay)+','+hhToHMS(sunrise)+','+hhToHMS(noon)+','+hhToHMS(sunset)+','+hhToHMS(mid)+'
');

    };
};

thanks for any help

Edit:
Jsfiddle

js linter says it's good

Body:
Include this handy "saveAs" function somewhere in your document.

function saveAs(text, filename){
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=urf-8,'+encodeURIComponent(text));
  pom.setAttribute('download', filename);
  pom.click();
};

And then use it:

saveAs(myCSVString, "data.csv");


问:
What is the preferred method for setting the value of a Seamless Immutable Array?
The docs for Seamless Immutable Object has set to update the value of a key in an object, but in the Immutable Array docs, there is no set for updating an element of an array.

What is the preferred method for setting the value of a Seamless Immutable Array?

答:
So I dug into the code — lo and behold! — there are undocumented Array methods:

My Redux reducer using the arraySet on the currentAnswer array:

export const updateIncompleteAnswer = (state, { assignment_id, questionIndex, questionAnswer }) => {
  const currentAnswer = state.incompleteAnswers[assignment_id]
  return state.merge({
    incompleteAnswers: {
      [assignment_id]: currentAnswer.set(questionIndex, questionAnswer)
    }
  })
}
```


问:
how to extract one element from nested list as vector - R twitteR package
I have a nested list of 'twitteR' user objects, whereby the 1st level of the list is a given user-id, e.g. 000000000, and the second level is a number of attributes for that entry, e.g. description or name. There are n list elements, and for each of these elements, the exact same variables/attributes exist.

What I want to do, is to extract one particular attribute/variable for every 1st order element of the list and save it to a character vector.

I can do this with a for loop, but this takes forever, and I'd really like for it to be more efficient, as I want to extract these variables for a huge amount of similar lists.

So, this is what the data i have looks like at the moment, let's assume my list is called list:

```<code>> list$`00000000`$description
[1] "bla bla bla bla"
> list$`00000001`$description
[1] "blub blub blub"
> list$`00000002`$description
[1] "pim pim pim"
</code>```

and this is what i'd like to have

```<code>> description
[1] "bla bla bla bla" "blub blub blub" "pim pim pim"
> class(description)
[1] "character"
</code>```

Is there a way of elegantly doing this in as few lines as possible, without the need for a for-loop?
Thanks in advance!

答:
Here is my answer using only base.

Data

```<code>list<-structure(list(`00000000` = structure(list(description = "bla bla bla bla"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame"), `00000001` = structure(list(description = "blub blub blub"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame"), `00000002` = structure(list(description = "pim pim pim"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame")), .Names = c("00000000", "00000001",
"00000002"))
</code>```

Solution

```<code>sapply(list,function(x){x$description})
</code>```

This returns an object of class character.

Body:
I have a nested list of 'twitteR' user objects, whereby the 1st level of the list is a given user-id, e.g. 000000000, and the second level is a number of attributes for that entry, e.g. description or name. There are n list elements, and for each of these elements, the exact same variables/attributes exist.

What I want to do, is to extract one particular attribute/variable for every 1st order element of the list and save it to a character vector.

I can do this with a for loop, but this takes forever, and I'd really like for it to be more efficient, as I want to extract these variables for a huge amount of similar lists.

So, this is what the data i have looks like at the moment, let's assume my list is called list:

> list$`00000000`$description
[1] "bla bla bla bla"
> list$`00000001`$description
[1] "blub blub blub"
> list$`00000002`$description
[1] "pim pim pim"

and this is what i'd like to have

> description
[1] "bla bla bla bla" "blub blub blub" "pim pim pim"
> class(description)
[1] "character"

Is there a way of elegantly doing this in as few lines as possible, without the need for a for-loop?
Thanks in advance!

Body:
Here is my answer using only base.

Data

list<-structure(list(`00000000` = structure(list(description = "bla bla bla bla"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame"), `00000001` = structure(list(description = "blub blub blub"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame"), `00000002` = structure(list(description = "pim pim pim"), .Names = "description", row.names = c(NA,
-1L), class = "data.frame")), .Names = c("00000000", "00000001",
"00000002"))

Solution

sapply(list,function(x){x$description})

This returns an object of class character.


问:
If username is set and password is not, display me an error message
```<code>    <div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php
      if (isset($_POST['username']) && !isset($_POST['password']))  {
    echo "Please enter your password.";
}?>
</code>```

I just want to display an error message IF username IS set and password field is not filled with any character after click on "submit", this is how I tried but now working for me.

答:
In your form you are missing an action. Inside the action attribute put the same URL that you did below. Also, you should check if the submit POST is set.

```<code>if (isset($_POST['submit']) && isset($_POST['username']) && $_POST['password'] == "")  {
    echo "Please enter your password.";
}
</code>```

Body:
Log In

<form action="" method="post" name="login">
<input type="text" name="username" placeholder="username" required />
<input type="password" name="password" placeholder="password" required />
<input name="submit" type="submit" value="Login" />
</form>

<?php
      if (isset($_POST['username']) && !isset($_POST['password']))  {
    echo "Please enter your password.";
}?>

I just want to display an error message IF username IS set and password field is not filled with any character after click on "submit", this is how I tried but now working for me.

Body:
In your form you are missing an action. Inside the action attribute put the same URL that you did below. Also, you should check if the submit POST is set.

if (isset($_POST['submit']) && isset($_POST['username']) && $_POST['password'] == "")  {
    echo "Please enter your password.";
}


问:
Difference between a statement and a query in SQL
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!

答: They're used interchangeably by most, but some often use the word "query" to mean, specifically, SELECT statements, because when you query something or someone, you want information. And SELECT queries return result sets, so that'd fit the description nicely. This also is evident in the fact that SELECT statements are formally called DQL (Data Query Language) statements.


问:
Python3 / Creating multiple class objects with different arguments from a list?
I want to create instances of my class car. How do I put the arguments from the list for each of the x amount of cars?

```<code>argument_list = ['h','2','2','0','v','2','0','0'........etc]

car1 = car('h','2','2','0')
car2 = car('v','2','0','0')
car3 = car(............etc)
</code>```

doing this for every single car would be so bad:

```<code>car1 = car(*coordinate_list[0:4])
car2 = car(*coordinate_list[4:8])
</code>```

答:
You can get this done with a for loop and globals.

```<code>class Car:
    def __init__(self, *args, **kwargs):
        print(args, kwargs)
        self.attr1 = args[0]
        self.attr2 = args[1]
        self.attr3 = args[2]
        self.attr4 = args[3]

argument_list = list(range(32)) #enough arguments for 8 cars

# the // operator guarantees integer division
num_cars = len(argument_list)//4
car_list = []
for i in range(num_cars-1):
    # [i*4:(i+1)*4] will grab 4 items at a time from argument list
    # the asterisk before it *argument_list[i*4:(i+1)*4] unpacks the list so they can be arguments for init
    car_list.append(Car(*argument_list[i*4:(i+1)*4]))

for car in car_list:
    print(car.attr1, car.attr2, car.attr3, car.attr4)

for i, car in enumerate(car_list):
    # accesses global variables and adds whatever variable we want by name
    globals()['car' + str(i)] = car

print(car1.attr1)

print(car2.attr2)
</code>```

Body:
I want to create instances of my class car. How do I put the arguments from the list for each of the x amount of cars?

argument_list = ['h','2','2','0','v','2','0','0'........etc]

car1 = car('h','2','2','0')
car2 = car('v','2','0','0')
car3 = car(............etc)

doing this for every single car would be so bad:

car1 = car(*coordinate_list[0:4])
car2 = car(*coordinate_list[4:8])

Body:
You can get this done with a for loop and globals.

class Car:
    def __init__(self, *args, **kwargs):
        print(args, kwargs)
        self.attr1 = args[0]
        self.attr2 = args[1]
        self.attr3 = args[2]
        self.attr4 = args[3]

argument_list = list(range(32)) #enough arguments for 8 cars

# the // operator guarantees integer division
num_cars = len(argument_list)//4
car_list = []
for i in range(num_cars-1):
    # [i*4:(i+1)*4] will grab 4 items at a time from argument list
    # the asterisk before it *argument_list[i*4:(i+1)*4] unpacks the list so they can be arguments for init
    car_list.append(Car(*argument_list[i*4:(i+1)*4]))

for car in car_list:
    print(car.attr1, car.attr2, car.attr3, car.attr4)

for i, car in enumerate(car_list):
    # accesses global variables and adds whatever variable we want by name
    globals()['car' + str(i)] = car

print(car1.attr1)

print(car2.attr2)


答:
```<code>if (isset($_POST['username']) && ($_POST['password'] == ""))  {
    echo "Please enter your password.";
}
</code>```

Title: If username is set and password is not, display me an error message


问:
Oracle SQL Full Outer Joins
My tables are as follows:

```<code>SELECT * FROM r_a;

CLASS   SECTION
-----   -------
1       A
1       B
2       A
2       B

SELECT * FROM r_b;

CLASS   SECTION
-----   -------
1       B
1       C
2       B
2       C
</code>```

I want to perform a full outer join on these tables over the column SECTION where CLASS=1 in both tables. My desired output is :

```<code>SECTION SECTION_1
------- ---------
B       B
A       (Null)
(Null)  C
</code>```

However, the following query yields only the matching row, similar to result of an inner join.

```<code>**QUERY 1**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
</code>```

I am able to achieve desired result by taking the where conditions inside a nested query:

```<code>**QUERY 2**

SELECT a.section, b.section
FROM
(SELECT SECTION FROM r_a WHERE class=1) a
FULL OUTER JOIN
(SELECT SECTION FROM r_b WHERE class=1) b
ON a.section=b.section

SECTION SECTION_1
------- ---------
B       B
(Null)  C
A       (Null)
</code>```

The result is more surprising when the where conditions in **Query 1** is moved to the on clause:

```<code>** Query 3**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
(Null)  C
(Null)  B
(Null)  C
B       (Null)
A       (Null)
A       (Null)

MORE CLARITY:
*************

SELECT *
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

CLASS   SECTION CLASS_1 SECTION_1
------  ------- ------- ---------
1       B       1       B
(Null)  (Null)  1       C
(Null)  (Null)  2       B
(Null)  (Null)  2       C
2       B       (Null)  (Null)
2       A       (Null)  (Null)
1       A       (Null)  (Null)
</code>```

Explanation on why Query 1 doesn't produce the desired result and why Query 3 joins on class=2 even when the on clause says AND  A.class=1 AND B.class=1 is greatly appreciated.

答:
You first query is 100% perfect, just change your WHERE statement to OR instead of AND.

```<code>SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 OR B.class=1
</code>```

That is essentially what you are doing when you do your second attempt with the subqueries.

Keeping in mind that your WHERE clause is executed AFTER the FROM clause. When you use AND here you are saying "Only take results AFTER the join where both conditions are true." Obviously this dumps results when one table has a condition = 1 and the other does not. With the "OR" you are saying "Take results AFTER the join where either condition is true".

Title: Oracle SQL Full Outer Joins

Body:
My tables are as follows:

SELECT * FROM r_a;

CLASS   SECTION
-----   -------
1       A
1       B
2       A
2       B

SELECT * FROM r_b;

CLASS   SECTION
-----   -------
1       B
1       C
2       B
2       C

I want to perform a full outer join on these tables over the column SECTION where CLASS=1 in both tables. My desired output is :

SECTION SECTION_1
------- ---------
B       B
A       (Null)
(Null)  C

However, the following query yields only the matching row, similar to result of an inner join.

**QUERY 1**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B

I am able to achieve desired result by taking the where conditions inside a nested query:

**QUERY 2**

SELECT a.section, b.section
FROM
(SELECT SECTION FROM r_a WHERE class=1) a
FULL OUTER JOIN
(SELECT SECTION FROM r_b WHERE class=1) b
ON a.section=b.section

SECTION SECTION_1
------- ---------
B       B
(Null)  C
A       (Null)

The result is more surprising when the where conditions in **Query 1** is moved to the on clause:

** Query 3**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
(Null)  C
(Null)  B
(Null)  C
B       (Null)
A       (Null)
A       (Null)

MORE CLARITY:
*************

SELECT *
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

CLASS   SECTION CLASS_1 SECTION_1
------  ------- ------- ---------
1       B       1       B
(Null)  (Null)  1       C
(Null)  (Null)  2       B
(Null)  (Null)  2       C
2       B       (Null)  (Null)
2       A       (Null)  (Null)
1       A       (Null)  (Null)

Explanation on why Query 1 doesn't produce the desired result and why Query 3 joins on class=2 even when the on clause says AND  A.class=1 AND B.class=1 is greatly appreciated.

Body:
You first query is 100% perfect, just change your WHERE statement to OR instead of AND.

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 OR B.class=1

That is essentially what you are doing when you do your second attempt with the subqueries.

Keeping in mind that your WHERE clause is executed AFTER the FROM clause. When you use AND here you are saying "Only take results AFTER the join where both conditions are true." Obviously this dumps results when one table has a condition = 1 and the other does not. With the "OR" you are saying "Take results AFTER the join where either condition is true".


答:
A statement is any text that the database engine recognizes as a valid command. As of SQL-92:

An SQL-statement is a string of characters that conforms to the format and syntax rules specified in this international standard.

A query is a statement that returns a recordset (possibly empty).

How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!

A series of SQL statements sent to the server at once is called a batch.

Not all SQL engines required the statements in a batch to be semicolon delimited. SQL Server, for instance, generally does not and breaks the statements based on context. CTE statements starting with WITH are a notable exception.

Title: Difference between a statement and a query in SQL

Body:
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!


问:
How to get custom SQL Server type into Entity Framework generated code
There is a TABLE Type defined in SQL server:

```<code>CREATE TYPE RealtySearchResult AS TABLE
(
realtyId int not null,
OwnerId int not null,
...)
</code>```

And stored procedure:

```<code>CREATE PROCEDURE [dbo].[SearchRealty]
(@fulltext nvarchar(200) null,
 @skipRows int,
 @pageCount int,
....
)
AS
BEGIN

DECLARE @SQL nvarchar(max)
DECLARE @result RealtySearchResult

CREATE TABLE #TEMP
(
realtyId int not null,
OwnerId int not null,
...
)

set @SQL = N'
INSERT INTO #TEMP
SELECT
realty.Id AS realtyId,
realty.OwnerId,
....join with fulltext catalog.... WHERE....@pageCount .....@skipRows'

-- sp_executesql cannot write to local table variable @result,
-- that is why it reads to temp table and then to @result

exec sp_executesql @SQL, N'@skipRows int, @pageCount int', @skipRows, @pageCount

INSERT INTO @result SELECT * FROM #TEMP
SELECT * FROM @result

END
</code>```

And then in Visual Studio I update the model from database and a new method (wrapper for store procedure SearchRealty) is generated, but it does not contains generated code for returning complex type.

I would expect that EntityFramework should be able to recognize that the store procedure returns defined table type RealtySearchResult and should generate wrapper for it. I am too lazy to write the complex return type by myself in C# again (I just wrote it in SQL). It is really needed?

Can I just generate wrapper for RealtySearchResult type in EntityFramework  somehow?

I use Visual Studio 2017 and EntityFramework 6.

It sounds as duplicate as Stored procedure in Entity Framework database first approach but once I click the button Get Column Information I got message "The selected stored procedure or function returns no columns".

答:
Analysis

Based on link Entity Framework not getting column info on a different schema provided by kirsten I realize that EntityFramework execute stored procedure with mode

SET FMTONLY ON

It means it strips all condition and dynamic SQL. This result in empty temporary table and procedure failing during receiving metadata from EntityFramework.

Solution

To help the designer to get metadata without dynamic SQL. Count with that conditions are removed. Following code does a job:

```<code>DECLARE @result RealtySearchResult

IF 0=1
BEGIN
    SELECT * FROM @result
    RETURN
END
</code>```

During execution of store procedure by EntityFramework (in order to get metadata), condition 0=1 is removed and empty table of Table type is returned which is enough to get metadata. This code is never trigerred in production because of impossible condition.

Body:
There is a TABLE Type defined in SQL server:

CREATE TYPE RealtySearchResult AS TABLE
(
realtyId int not null,
OwnerId int not null,
...)

And stored procedure:

CREATE PROCEDURE [dbo].[SearchRealty]
(@fulltext nvarchar(200) null,
 @skipRows int,
 @pageCount int,
....
)
AS
BEGIN

DECLARE @SQL nvarchar(max)
DECLARE @result RealtySearchResult

CREATE TABLE #TEMP
(
realtyId int not null,
OwnerId int not null,
...
)

set @SQL = N'
INSERT INTO #TEMP
SELECT
realty.Id AS realtyId,
realty.OwnerId,
....join with fulltext catalog.... WHERE....@pageCount .....@skipRows'

-- sp_executesql cannot write to local table variable @result,
-- that is why it reads to temp table and then to @result

exec sp_executesql @SQL, N'@skipRows int, @pageCount int', @skipRows, @pageCount

INSERT INTO @result SELECT * FROM #TEMP
SELECT * FROM @result

END

And then in Visual Studio I update the model from database and a new method (wrapper for store procedure SearchRealty) is generated, but it does not contains generated code for returning complex type.

I would expect that EntityFramework should be able to recognize that the store procedure returns defined table type RealtySearchResult and should generate wrapper for it. I am too lazy to write the complex return type by myself in C# again (I just wrote it in SQL). It is really needed?

Can I just generate wrapper for RealtySearchResult type in EntityFramework  somehow?

I use Visual Studio 2017 and EntityFramework 6.

It sounds as duplicate as Stored procedure in Entity Framework database first approach but once I click the button Get Column Information I got message "The selected stored procedure or function returns no columns".

Body:
Analysis

Based on link Entity Framework not getting column info on a different schema provided by kirsten I realize that EntityFramework execute stored procedure with mode

SET FMTONLY ON

It means it strips all condition and dynamic SQL. This result in empty temporary table and procedure failing during receiving metadata from EntityFramework.

Solution

To help the designer to get metadata without dynamic SQL. Count with that conditions are removed. Following code does a job:

DECLARE @result RealtySearchResult

IF 0=1
BEGIN
    SELECT * FROM @result
    RETURN
END

During execution of store procedure by EntityFramework (in order to get metadata), condition 0=1 is removed and empty table of Table type is returned which is enough to get metadata. This code is never trigerred in production because of impossible condition.


问:
When trying to download inline images in Chrome, what is the file size?
I am generating a GIF in the browser, and so the only link to it I can use is an inline data URL. (Like data:image/gif;base64,...)

I want to allow the user to download the GIF they created. To make it as easy as clicking on a link, I am using an a[download] like so:

```<code><a download="GIF" href="data:image/gif;base64,...">Download</a>
</code>```

With small files, this opens my MacOS "save as" dialog. With this GIF, it does not. Nothing happens when I click on the link, except that the Chrome icon changes to look like this:

When I right-click on the GIF and select "save image as", I can save it just fine. This allows me to see that the GIF is a whopping 3MB.

I have checked with a large file linked to in the usual fashion, and the a[download] link works just fine. This seems to only be a problem with inline, data-URL files.

Is there a file size limit?

Bonus questions:

Why is there a file size limit?

Is there a workaround?

答:
TL;DR: The data-url size limit is 2 MiB. See this demo.

--

This means that the file size is a little smaller than that, as a base64-encoded image is about 37% larger than the original.

Note also that it's a 2 Mebibyte limit, hence the "2 MiB" with the little "i". As explained here, this means the limit is 2 * 2^20 =  2,097,152 bytes, or 2.097 of the familiar base-ten megabytes, MB.

As shown in the demo, this translates to a 1.568 MB file downloading just fine, but Chrome failing to download a 1.581 MB file.

Why does Chrome do this? Not sure. Seems like it might be a bug.

Workarounds: Not sure. You could try to use URL.createObjectUrl as @roland-starke suggests, or perhaps open the data URL in a new tab

Body:
I am generating a GIF in the browser, and so the only link to it I can use is an inline data URL. (Like data:image/gif;base64,...)

I want to allow the user to download the GIF they created. To make it as easy as clicking on a link, I am using an a[download] like so:

Download

With small files, this opens my MacOS "save as" dialog. With this GIF, it does not. Nothing happens when I click on the link, except that the Chrome icon changes to look like this:

When I right-click on the GIF and select "save image as", I can save it just fine. This allows me to see that the GIF is a whopping 3MB.

I have checked with a large file linked to in the usual fashion, and the a[download] link works just fine. This seems to only be a problem with inline, data-URL files.

Is there a file size limit?

Bonus questions:

Why is there a file size limit?

Is there a workaround?


问:
Complex Dataframe Merge Python Pandas
I am trying to merge 2 dataframes and can't quite get what I'm looking for.

Dataframe 1 looks like this.

```<code>Index       Date      Data1   Data2

  A    2007-07-21      76      32
  A    2007-08-13      nan     23
  B    2007-06-15      53      nan
  B    2007-07-15      87      39
</code>```

Dataframe 2 looks like this:

```<code>Index       Date      Data3   Data4

  A    2007-07-24      14      nan
  A    2007-08-13      67      51
  B    2007-06-21      32      36
  B    2007-07-15      nan     91
</code>```

The same indicies are in both dataframes.  The index labels contain duplicates.  There is some overlap in the dates but each dataframe also contains unique dates.

What I'd like in my result is the following:  rows with the same Index and Date appear ONCE in the result with combined values (Data1, Data2, Data3, Data4).   If an Index/Date combination appears once in either the left dataframe or right dataframe, that combination appears along with the relevant data from respective  data frame and nans in columns from the dataframe where values don't exist.

From the above dataframes the result would look like this:

```<code>Index       Date      Data1   Data2  Data3  Data4

  A    2007-07-21      76      32     nan    nan
  A    2007-07-24      nan     nan    14     nan
  A    2007-08-13      nan     23     67      51
  B    2007-06-15      53      nan    nan    nan
  B    2007-06-21      nan     nan    32      36
  B    2007-07-15      87      39     nan     91
</code>```

This exercise has aspects of a left join but also an outer join.  Not sure how to get this using pd.merge or pd.concat.

Thank in advance for insight.

Title: Complex Dataframe Merge Python Pandas

Body:
I am trying to merge 2 dataframes and can't quite get what I'm looking for.

Dataframe 1 looks like this.

Index       Date      Data1   Data2

  A    2007-07-21      76      32
  A    2007-08-13      nan     23
  B    2007-06-15      53      nan
  B    2007-07-15      87      39

Dataframe 2 looks like this:

Index       Date      Data3   Data4

  A    2007-07-24      14      nan
  A    2007-08-13      67      51
  B    2007-06-21      32      36
  B    2007-07-15      nan     91

The same indicies are in both dataframes.  The index labels contain duplicates.  There is some overlap in the dates but each dataframe also contains unique dates.

What I'd like in my result is the following:  rows with the same Index and Date appear ONCE in the result with combined values (Data1, Data2, Data3, Data4).   If an Index/Date combination appears once in either the left dataframe or right dataframe, that combination appears along with the relevant data from respective  data frame and nans in columns from the dataframe where values don't exist.

From the above dataframes the result would look like this:

Index       Date      Data1   Data2  Data3  Data4

  A    2007-07-21      76      32     nan    nan
  A    2007-07-24      nan     nan    14     nan
  A    2007-08-13      nan     23     67      51
  B    2007-06-15      53      nan    nan    nan
  B    2007-06-21      nan     nan    32      36
  B    2007-07-15      87      39     nan     91

This exercise has aspects of a left join but also an outer join.  Not sure how to get this using pd.merge or pd.concat.

Thank in advance for insight.

Body:
set_index + concat

pd.concat([df1.set_index(['Index','Date']),df2.set_index(['Index','Date'])],1).reset_index()
Out[1145]:
  Index        Date  Data1  Data2  Data3  Data4
0     A  2007-07-21   76.0   32.0    NaN    NaN
1     A  2007-07-24    NaN    NaN   14.0    NaN
2     A  2007-08-13    NaN   23.0   67.0   51.0
3     B  2007-06-15   53.0    NaN    NaN    NaN
4     B  2007-06-21    NaN    NaN   32.0   36.0
5     B  2007-07-15   87.0   39.0    NaN   91.0

Or we can use merge

df1.merge(df2,on=['Index','Date'],how='outer')
Out[1147]:
  Index        Date  Data1  Data2  Data3  Data4
0     A  2007-07-21   76.0   32.0    NaN    NaN
1     A  2007-08-13    NaN   23.0   67.0   51.0
2     B  2007-06-15   53.0    NaN    NaN    NaN
3     B  2007-07-15   87.0   39.0    NaN   91.0
4     A  2007-07-24    NaN    NaN   14.0    NaN
5     B  2007-06-21    NaN    NaN   32.0   36.0


问:
Java: Declaring array with do... while
My school homework is to declare array with 100 variables.

The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.

So far I got:

```<code>public static void runTask1() {

    Scanner read = new Scanner(System.in);
    int[] tab = new int [100];
    for (int i = 0; i < tab.length; i++);
    System.out.println("Enter number for array ");
    tab [] = read.nextInt();
</code>```

Please help. I'm a total newbie in programming.

答:
You should do your homework yourself ;)

```<code>Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
    System.out.println("Number for array idx "+idx);
    try{
        tab[idx] = read.nextInt();
    }catch(Exception e){
        System.out.println("Wrong input");
    }
    if(tab[idx]<0) break;
    idx++;
}while(idx<100)
</code>```

Not compiled, just wrote it here.

Title: Java: Declaring array with do... while

Body:
My school homework is to declare array with 100 variables.

The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.

So far I got:

public static void runTask1() {

    Scanner read = new Scanner(System.in);
    int[] tab = new int [100];
    for (int i = 0; i < tab.length; i++);
    System.out.println("Enter number for array ");
    tab [] = read.nextInt();

Please help. I'm a total newbie in programming.

Body:
You should do your homework yourself ;)

Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
    System.out.println("Number for array idx "+idx);
    try{
        tab[idx] = read.nextInt();
    }catch(Exception e){
        System.out.println("Wrong input");
    }
    if(tab[idx]<0) break;
    idx++;
}while(idx<100)

Not compiled, just wrote it here.


问:
Get type_info from typename
Is there a way to get std::type_info from the type's name?  For example,

```<code>std::type_info f(std::string name) {
std::type_info info;
...
return info;
}

int main() {
const std::string name = typeid(double).name();
std::type_info info = f(name);
assert(info==typeid(double));
}
</code>```

What would the function f be?

答:
No. As documentation for std::type_info::name says:

No guarantees are given; in particular, the returned string can be
  identical for several types and change between invocations of the same
  program.

I don't know your exact use case, but chances are you can utilise C++11 std::type_index instead.

Title: Get type_info from typename

Body:
Is there a way to get std::type_info from the type's name?  For example,

std::type_info f(std::string name) {
std::type_info info;
...
return info;
}

int main() {
const std::string name = typeid(double).name();
std::type_info info = f(name);
assert(info==typeid(double));
}

What would the function f be?


问:
How to customize CSS with django-bootstrap3
Im working on a project in Django that I installed Django-bootstrap3 on. It seems to have installed successfully and is generally working...but I'm not sure how to customize the css with this setup. Can anyone help?</p>

答: You can add your own css using a css file in the static directory, the catch is that you need to place your css link tag under the bootstrap css link tag. Any css you add to your file will override most of the bootstrap styling. </p>


问:
Connect API to kdb database
simple question - I've successfully connected to the Coinbase API using Python 3.6 and receiving BTC buy/sell prices in my console.

I'd like to connect this to a kdb database and start creating a HDB of tick data but I'm a bit confused on how to structure this set-up, i.e., push the get requests to the database for storage. My python code looks like...

```<code>api_key = 'XXXXX'
api_secret = 'XXXXX'
from coinbase.wallet.client import Client
import time, requests

client = Client(api_key, api_secret)

starttime = time.time()
while True:
    buy_price = client.get_buy_price(currency_pair = 'BTC-USD')
    sell_price = client.get_sell_price(currency_pair = 'BTC-USD')
    time.sleep(10.0)
    print(buy_price)
    print(sell_price)
    print("=-=-=-=-=-=")
</code>```

The console prints the feed, which looks like...

```<code>{
  "amount": "8034.79",
  "base": "BTC",
  "currency": "USD"
}
{
  "amount": "7875.67",
  "base": "BTC",
  "currency": "USD"
}
=-=-=-=-=-=
{
  "amount": "8034.80",
  "base": "BTC",
  "currency": "USD"
}
{
  "amount": "7875.97",
  "base": "BTC",
  "currency": "USD"
}
=-=-=-=-=-=
</code>```

Any guidance in storing this data locally would be helpful. Please let me know if you need any additional info.

Thank you in advance!

Title: Connect API to kdb database

Body:
simple question - I've successfully connected to the Coinbase API using Python 3.6 and receiving BTC buy/sell prices in my console.

I'd like to connect this to a kdb database and start creating a HDB of tick data but I'm a bit confused on how to structure this set-up, i.e., push the get requests to the database for storage. My python code looks like...

api_key = 'XXXXX'
api_secret = 'XXXXX'
from coinbase.wallet.client import Client
import time, requests

client = Client(api_key, api_secret)

starttime = time.time()
while True:
    buy_price = client.get_buy_price(currency_pair = 'BTC-USD')
    sell_price = client.get_sell_price(currency_pair = 'BTC-USD')
    time.sleep(10.0)
    print(buy_price)
    print(sell_price)
    print("=-=-=-=-=-=")

The console prints the feed, which looks like...

{
  "amount": "8034.79",
  "base": "BTC",
  "currency": "USD"
}
{
  "amount": "7875.67",
  "base": "BTC",
  "currency": "USD"
}
=-=-=-=-=-=
{
  "amount": "8034.80",
  "base": "BTC",
  "currency": "USD"
}
{
  "amount": "7875.97",
  "base": "BTC",
  "currency": "USD"
}
=-=-=-=-=-=

Any guidance in storing this data locally would be helpful. Please let me know if you need any additional info.

Thank you in advance!

Body:
You can use PyQ:

>>> from pyq import q
>>> p = {
...   "amount": "8034.79",
...   "base": "BTC",
...   "currency": "USD"
... }
>>> q.set(':x', [p])
k('`:x')
>>> q.upsert(':x', p)
k('`:x')
>>> q.get(':x').show()
amount  base currency
---------------------
8034.79 BTC  USD
8034.79 BTC  USD


问:
calling to bubbleSort method from main to print sorted array
How do you call to the bubbleSort method from the main method in order to print a sorted list array. I have generated 10 random numbers into an array but I have not figured out how to call to the bubbleSort and print results. What am I missing here?

public class Bubblesort{

public static void main(String[] args) {

```<code>    int [] numbers = new int[10];
    //Generate 10 random numbers between 1-100
      for(int i = 0; i < numbers.length; i++) {
        numbers[i] = (int)(Math.random() * 100 + 1);
        }//end of loop
    System.out.println("The unsorted list is: " + Arrays.toString(numbers));
         //Solution added
         bubbleSort(numbers); //Call to sort the array
    System.out.println("The sorted list is: " + Arrays.toString(numbers));
</code>```

}

```<code>    public static void bubbleSort(int[] list)
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--)
          {
             for (int j = 0; j < i; j++)
             {
               if (list[j] > list[j + 1])
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;

               }
             }
          }
       }
</code>```

}

答:
```<code>import java.util.Arrays;
import java.util.Random;

public class BubbleSort{
    static Random rand = new Random();

    public static void main(String[] args) {
        int [] numbers = new int[10];
        //Generate 10 random numbers between 1-100
          for(int i = 0; i < numbers.length; i++) {
            numbers[i] = (int)(rand.nextFloat() * 100 + 1);
            }//end of loop
        System.out.println("The unsorted list is: " + Arrays.toString(numbers));
        bubbleSort(numbers);
        System.out.println("The sorted list is: " + Arrays.toString(numbers));

    }

    public static void bubbleSort(int[] list) {
        int temp;
        for (int i = list.length - 1; i > 0; i--){
            for (int j = 0; j < i; j++){
                if (list[j] > list[j + 1]){
                    temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                }
            }
        }
    }
}
</code>```

Body:
How do you call to the bubbleSort method from the main method in order to print a sorted list array. I have generated 10 random numbers into an array but I have not figured out how to call to the bubbleSort and print results. What am I missing here?

public class Bubblesort{

public static void main(String[] args) {

    int [] numbers = new int[10];
    //Generate 10 random numbers between 1-100
      for(int i = 0; i < numbers.length; i++) {
        numbers[i] = (int)(Math.random() * 100 + 1);
        }//end of loop
    System.out.println("The unsorted list is: " + Arrays.toString(numbers));
         //Solution added
         bubbleSort(numbers); //Call to sort the array
    System.out.println("The sorted list is: " + Arrays.toString(numbers));

}

    public static void bubbleSort(int[] list)
      {
        int temp;

          for (int i = list.length - 1; i > 0; i--)
          {
             for (int j = 0; j  list[j + 1])
               {
               temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;

               }
             }
          }
       }

}


问:
Python linear programming - how to constrain a variable to be an integer
I would like to maximize the probability of winning a raffle by buying a certain number of tickets. For this, I wrote the following code

```<code>import numpy as np
import math as mt
from scipy.optimize import minimize
from pulp import *

def objective(tickets, winners = 500, losers = 2500, cost_of_ticket = 40, winning_amt = 1000):

    Pwin = 1 - mt.factorial(losers)//mt.factorial(losers - tickets)*mt.factorial(winners+losers-tickets)/mt.factorial(winners+losers)
    Ewin = Pwin*(winning_amt - cost_of_ticket*tickets)

    return Ewin

# declare your variables
tickets = LpVariable("tickets", range(0, 10))   # 0<= tickets <= 10

prob = LpProblem("problem", LpMaximize)

#define the objective
prob += objective(tickets)

# solve the problem
status = prob.solve(GLPK(msg=0))
LpStatus[status]

# print the results
value(tickets)
</code>```

The issue seems to be that the number of tickets that get passed into the objective function is not an integer (and the factorial function then fails). Can anyone suggest how I should ensure that the ticket is restricted to positive integer values?

The answer, for checking, should be 8. I can do this by manually calling the objective function and checking.

答:
Your objective is really

```<code> ExpWin(t) = choose(N,t)*(A-C*t)
</code>```

where t is an integer variable and N,A,C are constants. This is a nonlinear function so a linear MIP solver will not be able to handle this.

For this problem it is silly, but in general we can linearize this. Introduce binary variables x(i) with:

```<code>x(i) = 1 if tickets=i
       0 otherwise
</code>```

This can be enforced by

```<code>sum(i,x(i)) = 1
sum(i,i*x(i)) = tickets
</code>```

This only makes sense if the range of variable tickets is small (in your case 10). Now we can precalculate a constant array w(i) which is the expected win if the number of tickets is i. Now the objective can look like:

```<code>max sum(i, w(i)*x(i))
</code>```

which is now linear.

Anyway it is always a good idea to step away from code and write down the problem in math. This can help you think about the problem in a different way.

Body:
I would like to maximize the probability of winning a raffle by buying a certain number of tickets. For this, I wrote the following code

import numpy as np
import math as mt
from scipy.optimize import minimize
from pulp import *

def objective(tickets, winners = 500, losers = 2500, cost_of_ticket = 40, winning_amt = 1000):

    Pwin = 1 - mt.factorial(losers)//mt.factorial(losers - tickets)*mt.factorial(winners+losers-tickets)/mt.factorial(winners+losers)
    Ewin = Pwin*(winning_amt - cost_of_ticket*tickets)

    return Ewin

# declare your variables
tickets = LpVariable("tickets", range(0, 10))   # 0<= tickets <= 10

prob = LpProblem("problem", LpMaximize)

#define the objective
prob += objective(tickets)

# solve the problem
status = prob.solve(GLPK(msg=0))
LpStatus[status]

# print the results
value(tickets)

The issue seems to be that the number of tickets that get passed into the objective function is not an integer (and the factorial function then fails). Can anyone suggest how I should ensure that the ticket is restricted to positive integer values?

The answer, for checking, should be 8. I can do this by manually calling the objective function and checking.

Body:
Your objective is really

 ExpWin(t) = choose(N,t)*(A-C*t)

where t is an integer variable and N,A,C are constants. This is a nonlinear function so a linear MIP solver will not be able to handle this.

For this problem it is silly, but in general we can linearize this. Introduce binary variables x(i) with:

x(i) = 1 if tickets=i
       0 otherwise

This can be enforced by

sum(i,x(i)) = 1
sum(i,i*x(i)) = tickets

This only makes sense if the range of variable tickets is small (in your case 10). Now we can precalculate a constant array w(i) which is the expected win if the number of tickets is i. Now the objective can look like:

max sum(i, w(i)*x(i))

which is now linear.

Anyway it is always a good idea to step away from code and write down the problem in math. This can help you think about the problem in a different way.


问:
How I have to encode url for Facebook sharing
I am using a JScript code like this:

```<code>shareLink = function (link) {

    FB.ui({
        method: 'share',
        display: 'popup',
        href: link,
    }, function(response){});

}
</code>```

and it is called in a line like this:

```<code><?php
$sharedata = " ... parameters ... "
?>

<a href="javascript:shareLink('http://<?php echo $site; ?>/?v=<?php echo rawurlencode($sharelink); ?>');">
</code>```

so, the destination script trasform parameter by using:

```<code>$str = rawurldecode($_GET["v"]);
</code>```

the problem is when the url has a "+" character

using rawurlencode it its converted to "%2B"

```<code>zcu0xci%2FFMH2%2B7cLDPVP%2BgD7%2FwQJ%2FFT2Bw%3D%3D
</code>```

but facebook change only "%2B" into "+" sign again:

```<code>zcu0xci%2FFMH2+7cLDPVP+gD7%2FwQJ%2FFT2Bw%3D%3D
</code>```

and my script does not recognize it

EDIT:

if I echo the "v" parameter I get

```<code>zcu0xci/FMH2 7cLDPVP gD7/wQJ/FT2Bw==
</code>```

instead of

```<code>zcu0xci/FMH2+7cLDPVP+gD7/wQJ/FT2Bw==
</code>```

SOLUTION:

the solution I've found is to replace space by "+" before decode

```<code>$str = str_replace(" ","+",$str);
</code>```

答:
You don't need to use rawurldecode() on elements of the $_GET super-global variable.  PHP decodes URL data for you.

In addition, you should generally use urlencode() to encode query string data.  If you investigate the difference between these two functions, you'll see that urlencode() will translate any space character to the "+" character.  This could possibly be the problem you're experiencing.

I'm having difficulty understanding the remainder of your question. You may need to work on your phrasing.

Body:
I am using a JScript code like this:

shareLink = function (link) {

    FB.ui({
        method: 'share',
        display: 'popup',
        href: link,
    }, function(response){});

}

and it is called in a line like this:

<?php
$sharedata = " ... parameters ... "
?>

<a href="javascript:shareLink('http://<?php echo $site; ?>/?v=<?php echo rawurlencode($sharelink); ?>');">

so, the destination script trasform parameter by using:

$str = rawurldecode($_GET["v"]);

the problem is when the url has a "+" character

using rawurlencode it its converted to "%2B"

zcu0xci%2FFMH2%2B7cLDPVP%2BgD7%2FwQJ%2FFT2Bw%3D%3D

but facebook change only "%2B" into "+" sign again:

zcu0xci%2FFMH2+7cLDPVP+gD7%2FwQJ%2FFT2Bw%3D%3D

and my script does not recognize it

EDIT:

if I echo the "v" parameter I get

zcu0xci/FMH2 7cLDPVP gD7/wQJ/FT2Bw==

instead of

zcu0xci/FMH2+7cLDPVP+gD7/wQJ/FT2Bw==

SOLUTION:

the solution I've found is to replace space by "+" before decode

$str = str_replace(" ","+",$str);


问:
JHipster liquibase
I'm getting started with JHipster and am attempting to initialize my data using liquibase.  I have added two entities via the JHipster yo task and have added my two csv files into the /resources/config/liquibase directory and added the relevant loadData section to my "added entity" change log files to point at the CSV's.  I had to update the MD5hash in the databasechangelog table and the app is running BUT, the CSV files don't seem to get picked up via the loadData elements I added to the "added entity" XML files. No data is inserted.  Any ideas how to go about running this down?</p>

答:
This was my solution for me:

 1. Delete row in databasechangelog

 2. Delete table

 3. Re-start app

Liquibase re-generated table with csv and loaded all data to database.

I hope I helped you :)

Title: JHipster liquibase


问:
XSL select and sum a node based on partial match to sibling value
We have poorly-formed XML coming from an Oracle report.  The report contains thousands of orders.  Each order contains less than a thousand lines.  Each line contains potentially many charges.  We read the XML with an XSL template to clean it up.  I'm having a problem reading the charge section and summarizing each charge type by Order.

Looking at the example below, we have Ack_Line__Hdr_S32 containing the charges.  AckLine_ID2 is the line number.  When the template is called, we have the Order number, but the order number does not contain the line number.  This means, we have the order number '0705181439' and have to evaluate that against the substring first ten characters of line number 0705181439009.

The first XSL solution below worked until the order volume grew.  Now it crashes after some time.  The source XML file is around 50MB.

Here's the detail:

Sample XML:

```<code><Charges_and_Fees_S9_Group>
  <Ack_Line___Hdr_S32>
    <AckLine_ID2>0705181439009</AckLine_ID2>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>ACCESSCH                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>30.00</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Accessorial Charge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FLANDED                  </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>67.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Freight - Landed Freight</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FUELSURG                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>27.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Fuel Surcharge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <AckLine_Freight_ID1>67.12</AckLine_Freight_ID1>
    <AckLine_ChargesAndFees_ID2>57.12</AckLine_ChargesAndFees_ID2>
    <AckLine_FuelSurcharge_ID4>27.12</AckLine_FuelSurcharge_ID4>
    <AckLine_AccessorialSurcharge_ID6>30.00</AckLine_AccessorialSurcharge_ID6>
  </Ack_Line___Hdr_S32>
</Charges_and_Fees_S9_Group>
<Charges_and_Fees_S9_Group>
  <Ack_Line___Hdr_S32>
    <AckLine_ID2>0705181439010</AckLine_ID2>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>ACCESSCH                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>30.00</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Accessorial Charge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FLANDED                  </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>67.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Freight - Landed Freight</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FUELSURG                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>27.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Fuel Surcharge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <AckLine_Freight_ID1>67.12</AckLine_Freight_ID1>
    <AckLine_ChargesAndFees_ID2>57.12</AckLine_ChargesAndFees_ID2>
    <AckLine_FuelSurcharge_ID4>27.12</AckLine_FuelSurcharge_ID4>
    <AckLine_AccessorialSurcharge_ID6>30.00</AckLine_AccessorialSurcharge_ID6>
  </Ack_Line___Hdr_S32>
</Charges_and_Fees_S9_Group>
</code>```

Old XSL Template:

```<code><xsl:template name="ChargesTotal">
  <xsl:param name="AckLineNumber" />
    <Total_Accessorial>
      <xsl:if test="//AckLine_AccessorialSurcharge_ID6  [substring(../AckLine_ID2, 1, 10)=$AckLineNumber]" >
        <xsl:value-of select="format-number(sum(//AckLine_AccessorialSurcharge_ID6  [substring(../AckLine_ID2, 1, 10)=$AckLineNumber]), '#.00')" />
      </xsl:if>
    </Total_Accessorial>
</xsl:template>
</code>```

New XSL Template:

```<code><xsl:template name="ChargesTotal">
  <xsl:param name="AckLineNumber" />
  <xsl:variable name="setSurchargeAcc" select="Ack_Line___Hdr_S32/AckLine_AccessorialSurcharge_ID6[substring(../AckLine_ID2, 1, 10)=$AckLineNumber]"/>
  <Total_Accessorial>
    <xsl:value-of select="format-number(sum($setSurchargeAcc/AckLine_AccessorialSurcharge_ID6), '#.00')" />
  </Total_Accessorial>
</xsl:template>
</code>```

Expected Output:

```<code><Total_Accessorial>60.00</Total_Accessorial>
</code>```

答:
You can try to define a key

```<code><xsl:key name="line-id" match="Charges_and_Fees_S9_Group/Ack_Line___Hdr_S32"
  use="substring(AckLine_ID2, 1, 10)"/>
</code>```

then you can do e.g.

```<code><xsl:variable name="setSurchargeAcc" select="key('line-id', $AckLineNumber)"/>
</code>```

and

```<code><Total_Accessorial>
  <xsl:if test="$setSurchargeAcc">
    <xsl:value-of select="format-number(sum($setSurchargeAcc/AckLine_AccessorialSurcharge_ID6), '#.00')" />
  </xsl:if>
</Total_Accessorial>
</code>```

Body:
We have poorly-formed XML coming from an Oracle report.  The report contains thousands of orders.  Each order contains less than a thousand lines.  Each line contains potentially many charges.  We read the XML with an XSL template to clean it up.  I'm having a problem reading the charge section and summarizing each charge type by Order.

Looking at the example below, we have Ack_Line__Hdr_S32 containing the charges.  AckLine_ID2 is the line number.  When the template is called, we have the Order number, but the order number does not contain the line number.  This means, we have the order number '0705181439' and have to evaluate that against the substring first ten characters of line number 0705181439009.

The first XSL solution below worked until the order volume grew.  Now it crashes after some time.  The source XML file is around 50MB.

Here's the detail:

Sample XML:

<Charges_and_Fees_S9_Group>
  <Ack_Line___Hdr_S32>
    <AckLine_ID2>0705181439009</AckLine_ID2>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>ACCESSCH                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>30.00</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Accessorial Charge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FLANDED                  </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>67.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Freight - Landed Freight</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FUELSURG                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>27.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Fuel Surcharge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <AckLine_Freight_ID1>67.12</AckLine_Freight_ID1>
    <AckLine_ChargesAndFees_ID2>57.12</AckLine_ChargesAndFees_ID2>
    <AckLine_FuelSurcharge_ID4>27.12</AckLine_FuelSurcharge_ID4>
    <AckLine_AccessorialSurcharge_ID6>30.00</AckLine_AccessorialSurcharge_ID6>
  </Ack_Line___Hdr_S32>
</Charges_and_Fees_S9_Group>
<Charges_and_Fees_S9_Group>
  <Ack_Line___Hdr_S32>
    <AckLine_ID2>0705181439010</AckLine_ID2>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>ACCESSCH                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>30.00</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Accessorial Charge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FLANDED                  </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>67.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Freight - Landed Freight</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <On_2nd_Item_Number_S19>
      <ChargeItemNumber_ID1>FUELSURG                 </ChargeItemNumber_ID1>
      <ChargesAndFees_ID3>27.12</ChargesAndFees_ID3>
      <ChargeItemDescription_ID4>Fuel Surcharge</ChargeItemDescription_ID4>
    </On_2nd_Item_Number_S19>
    <AckLine_Freight_ID1>67.12</AckLine_Freight_ID1>
    <AckLine_ChargesAndFees_ID2>57.12</AckLine_ChargesAndFees_ID2>
    <AckLine_FuelSurcharge_ID4>27.12</AckLine_FuelSurcharge_ID4>
    <AckLine_AccessorialSurcharge_ID6>30.00</AckLine_AccessorialSurcharge_ID6>
  </Ack_Line___Hdr_S32>
</Charges_and_Fees_S9_Group>

Old XSL Template:

<xsl:template name="ChargesTotal">
  <xsl:param name="AckLineNumber" />
    <Total_Accessorial>
      <xsl:if test="//AckLine_AccessorialSurcharge_ID6  [substring(../AckLine_ID2, 1, 10)=$AckLineNumber]" >
        <xsl:value-of select="format-number(sum(//AckLine_AccessorialSurcharge_ID6  [substring(../AckLine_ID2, 1, 10)=$AckLineNumber]), '#.00')" />
      </xsl:if>
    </Total_Accessorial>
</xsl:template>

New XSL Template:

<xsl:template name="ChargesTotal">
  <xsl:param name="AckLineNumber" />
  <xsl:variable name="setSurchargeAcc" select="Ack_Line___Hdr_S32/AckLine_AccessorialSurcharge_ID6[substring(../AckLine_ID2, 1, 10)=$AckLineNumber]"/>
  <Total_Accessorial>
    <xsl:value-of select="format-number(sum($setSurchargeAcc/AckLine_AccessorialSurcharge_ID6), '#.00')" />
  </Total_Accessorial>
</xsl:template>

Expected Output:

<Total_Accessorial>60.00</Total_Accessorial>

Body:
You can try to define a key

<xsl:key name="line-id" match="Charges_and_Fees_S9_Group/Ack_Line___Hdr_S32"
  use="substring(AckLine_ID2, 1, 10)"/>

then you can do e.g.

<xsl:variable name="setSurchargeAcc" select="key('line-id', $AckLineNumber)"/>

and

<Total_Accessorial>
  <xsl:if test="$setSurchargeAcc">
    <xsl:value-of select="format-number(sum($setSurchargeAcc/AckLine_AccessorialSurcharge_ID6), '#.00')" />
  </xsl:if>
</Total_Accessorial>


答:
A statement is any SQL command such as SELECT, INSERT, UPDATE, DELETE.

A query is a synonym for a SELECT statement.

Body:
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!