问:
animateLayoutChanges does not work well with nested layout?
I have a nested layout like the following:

```<code> <LinearLayout>     <!----Parent layout--->
    <LinearLayout>    <!-----child 1--->
       ...
    </LinearLayout>   <!----child 1 ended--->
    <LinearLayout>    <!-----child 2--->
       ...
    </LinearLayout>   <!----child 2 ended--->
 </LinearLayout>    <!----Parent endded--->
</code>```

The problem I am having now is that since all my data items are within child 1 or child 2 Linearlayout, if I add or delete a item the child linearlayout will animated with the effect of animateLayoutChanges but the parent layout will not do any animation. (I have android:animateLayoutChanges set to true for all linear layouts). Especially when I delete an item within child 1 the animation effect becomes weird (basically child 2 will jump up while child 1 is still doing its animation).

Does anybody have any idea how to solve this?

Thanks

UPDATE

Shortly after I posted this question, I found this on android developer's site in the LayoutTransition API.

Using LayoutTransition at multiple levels of a nested view hierarchy may not work due to the interrelationship of the various levels of layout.

So does anyone have any work around suggestions for this issue?

答:
We had added the android:animateLayoutChanges attribute to our LinearLayout but the change didn’t trigger an animation. To fix that, use this code:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
      .enableTransitionType(LayoutTransition.CHANGING);
}
</code>```

More details.

Body:
I have a nested layout like the following:

 <LinearLayout>
    <LinearLayout>
       ...
    </LinearLayout>
    <LinearLayout>
       ...
    </LinearLayout>
 </LinearLayout>

The problem I am having now is that since all my data items are within child 1 or child 2 Linearlayout, if I add or delete a item the child linearlayout will animated with the effect of animateLayoutChanges but the parent layout will not do any animation. (I have android:animateLayoutChanges set to true for all linear layouts). Especially when I delete an item within child 1 the animation effect becomes weird (basically child 2 will jump up while child 1 is still doing its animation).

Does anybody have any idea how to solve this?

Thanks

UPDATE

Shortly after I posted this question, I found this on android developer's site in the LayoutTransition API.

Using LayoutTransition at multiple levels of a nested view hierarchy may not work due to the interrelationship of the various levels of layout.

So does anyone have any work around suggestions for this issue?

Body:
We had added the android:animateLayoutChanges attribute to our LinearLayout but the change didn’t trigger an animation. To fix that, use this code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
      .enableTransitionType(LayoutTransition.CHANGING);
}

More details.


来源: stackexchange

问:
c# string to class from which I can call functions
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

```<code>Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);
</code>```

what I want to do is call a function on this class for example:

```<code>class.foo();
</code>```

is this possible? and if it is how?

答:
```<code>var methodInfo = type.GetMethod("foo");
object result  = methodInfo.Invoke(class,null);
</code>```

The second argument to the Invoke method are the method parameters.

ContentLicense: CC BY-SA 4.0

Body:
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

what I want to do is call a function on this class for example:

class.foo();

is this possible? and if it is how?

Body:
var methodInfo = type.GetMethod("foo");
object result  = methodInfo.Invoke(class,null);

The second argument to the Invoke method are the method parameters.


问:
Codec comparison compression/quality
So I'm rebuilding my video library from my file archives (I have my DVDs/Blurays already decoded on my disk) and I want to ensure that I have the best quality files and compression. I know that lossless is not practical for saving space but I do want indistinguishable video/audio quality. I'm using VidCoder and so far have just been comparing the qualities and file sizes between video codecs. I'm thinking about using VP9, I know AV1 will be out soon and I will rebuild it again then using that. For audio I'm thinking of going with FLAC (I really like FLAC and have already used it for my digital CD archive). So which do y'all think is best for what I want? Oh and I don't care about compatibility.</p>

答:
Hevc is about 15% better than vp9. Av1 is estimated to be 10-20% better than hevc for 720p and above sources but current builds are around 50x slower to encode compared to hevc.

For audio flac or good aac encoder with high bitrate. Apple or Nero aac encoders perform the best.
Use standard aac_lc profile, NOT he-aac, its used for low bitrate scenarios.

Dont use opus for audio its optimized for low to medium bitrate.

Hope this helps,
Peder

ContentLicense: CC BY-SA 3.0

Title: Codec comparison compression/quality


问:
How to retrieve the pg_config file from Azure postgresql Database
Trying to install a postgresql database which resides on Azure for my python flask application; but the installation of psycopg2 package requires the pg_config file which comes when postgresql is installed. So how do I export the pg_config file from the postgresql database which also resides on azure? Is pg_config all psycopg2 need for a successful installation?

答:
You don't need the specific pg_config from the target database. It's only being used to compile against libpq, the client library for PostgreSQL, so you only need the matching PostgreSQL client installed on your local machine.

If you're on Windows I strongly advise you to install a pre-compiled PostgreSQL. You can just install the whole server, it comes with the client libraries.

If you're on Linux, you'll probably need the PostgreSQL -devel or -dev package that matches your PostgreSQL version.


问:
Trigger :visited state (make links purple) when browsing in Electron
In my Electron app I have a webview. If I click a link (e.g. on Google) and then move back, the link turns not purple, like in normal browsers.

Can I activate this behaviour in Electron too? Or do it programmatically, if I would store the browsing history by myself?

I guess it is somehow connected that the history support in Electron is not yet the best?

Would this maybe possible with Muon fork of Electron?

答:
As you can see from the comments at about line 16 of this file, the Electron guys/girls have created their own navigation solution. It would seem this doesn't handle a:visited properly.

Instead, we can easily create our own solution. Add the following function to all of your renderer scripts and ensure you put simuHistory(); at the start of every page:

function simuHistory() {
    var localstorageSimuHistory = localStorage.getItem('simuHistory');
    var simuHistory = localstorageSimuHistory ? JSON.parse(localstorageSimuHistory) : [];
    var found = false;
    var windowHref = window.location.href;
    for(let i=0;i<simuHistory.length;i++) {
        if(simuHistory[i] == windowHref) {
            found = true;
            break;
        }
    }
    if(found === false) {
        simuHistory[simuHistory.length] = windowHref;
        localStorage.setItem('simuHistory', JSON.stringify(simuHistory));
    }
    var elements = document.getElementsByTagName('a');
    for(let i=0;i<elements.length;i++) {
        for(let h=0;h<simuHistory.length;h++) {
            if(elements[i].href == simuHistory[h]) {
                elements[i].className += ' visited';
            }
        }
    }
}
```
<p>And add the following CSS to your stylesheet:</p>
<pre class="lang-css prettyprint-override"><code>.visited {
    color: purple;
}
</code>```

Alternatively, if you don't want to include the CSS (or want it all self-contained), you could replace this line:

elements[i].className += ' visited';
```
<p>...with this line:</p>
<pre class="lang-js prettyprint-override"><code>elements[i].style.color = 'purple';
</code>```

Scalability

The TL;DR is that unless you have more than around 25,000 fairly long unique URLs in your app, you don't need to worry about scalability.

The visited URLs are stored in localStorage. This is limited in size, and therefore limited in the number of URLs we can store. I believe in Electron this is limited to around 5MB. I tested performance by adding 25,000 additional URLs to the simuHistory array using the following code:

for(var i = 0; i < 25000; i++) {
    simuHistory[simuHistory.length] = 'https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers' + Math.floor((Math.random() * 1000000) + 1);
}
```
<p>The URL was chosen because it was fairly long. The random number on the end actually affects nothing at all; I just included it to add some extra length. Then I timed running <code>simuHistory()</code> on my crappy slow laptop (with no SSD):</p>
<pre class="lang-none prettyprint-override"><code>25,000 URLs == ~210ms
 1,000 URLs == ~13ms
</code>```

In my opinion that's plenty fast for nearly any Electron app, but it depends on your use case as to how many URLs you might end up with.

Body:
As you can see from the comments at about line 16 of this file, the Electron guys/girls have created their own navigation solution. It would seem this doesn't handle a:visited properly.

Instead, we can easily create our own solution. Add the following function to all of your renderer scripts and ensure you put simuHistory(); at the start of every page:

function simuHistory() {
    var localstorageSimuHistory = localStorage.getItem('simuHistory');
    var simuHistory = localstorageSimuHistory ? JSON.parse(localstorageSimuHistory) : [];
    var found = false;
    var windowHref = window.location.href;
    for(let i=0;i<simuHistory.length;i++) {
        if(simuHistory[i] == windowHref) {
            found = true;
            break;
        }
    }
    if(found === false) {
        simuHistory[simuHistory.length] = windowHref;
        localStorage.setItem('simuHistory', JSON.stringify(simuHistory));
    }
    var elements = document.getElementsByTagName('a');
    for(let i=0;i<elements.length;i++) {
        for(let h=0;h<simuHistory.length;h++) {
            if(elements[i].href == simuHistory[h]) {
                elements[i].className += ' visited';
            }
        }
    }
}

And add the following CSS to your stylesheet:

.visited {
    color: purple;
}

Alternatively, if you don't want to include the CSS (or want it all self-contained), you could replace this line:

elements[i].className += ' visited';

...with this line:

elements[i].style.color = 'purple';

Scalability

The TL;DR is that unless you have more than around 25,000 fairly long unique URLs in your app, you don't need to worry about scalability.

The visited URLs are stored in localStorage. This is limited in size, and therefore limited in the number of URLs we can store. I believe in Electron this is limited to around 5MB. I tested performance by adding 25,000 additional URLs to the simuHistory array using the following code:

for(var i = 0; i < 25000; i++) {
    simuHistory[simuHistory.length] = 'https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers' + Math.floor((Math.random() * 1000000) + 1);
}

The URL was chosen because it was fairly long. The random number on the end actually affects nothing at all; I just included it to add some extra length. Then I timed running simuHistory() on my crappy slow laptop (with no SSD):

25,000 URLs == ~210ms
 1,000 URLs == ~13ms

In my opinion that's plenty fast for nearly any Electron app, but it depends on your use case as to how many URLs you might end up with.


问:
silverlight - open xaml in new web browser
In my silverlight application I want to open a xaml in a new web browser. how can I do that?
with HTMLPage.Window.Navigate it is just aspx pages - maybe I can convert xaml to aspx?

10x!

答:
a XAML page cannot be shown in a browser window.  What Silverlight do actually is showing the Silverlight program within an < object > tag in the aspx (or html) page; nothing more.

In your silverlight project, if you chose to host your project in a new web site, you will see a second project with both a htm and aspx file that hosts that object that links to your xap file.

So basically, you need to create a second Silverlight project that will be hosted in a different aspx page.  Then in your main silverlight project your can open that new aspx page in a new web browser window.

ContentLicense: CC BY-SA 2.5


问:
Dictionary vs Object - which is more efficient and why?
What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?

Background:
I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.

Example:
To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:

Object (execution time ~18sec):

```<code>class Obj(object):
  def __init__(self, i):
    self.i = i
    self.l = []
all = {}
for i in range(1000000):
  all[i] = Obj(i)
</code>```

Dictionary (execution time ~12sec):

```<code>all = {}
for i in range(1000000):
  o = {}
  o['i'] = i
  o['l'] = []
  all[i] = o
</code>```

Question:
Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?

答:
Here is a copy of @hughdbrown answer for python 3.6.1, I've made the count 5x larger and added some code to test the memory footprint of the python process at the end of each run.

Before the downvoters have at it, Be advised that this method of counting the size of objects is not accurate.

```<code>from datetime import datetime
import os
import psutil

process = psutil.Process(os.getpid())

ITER_COUNT = 1000 * 1000 * 5

RESULT=None

def makeL(i):
    # Use this line to negate the effect of the strings on the test
    # return "Python is smart and will only create one string with this line"

    # Use this if you want to see the difference with 5 million unique strings
    return "This is a sample string %s" % i

def timeit(method):
    def timed(*args, **kw):
        global RESULT
        s = datetime.now()
        RESULT = method(*args, **kw)
        e = datetime.now()

        sizeMb = process.memory_info().rss / 1024 / 1024
        sizeMbStr = "{0:,}".format(round(sizeMb, 2))

        print('Time Taken = %s, \t%s, \tSize = %s' % (e - s, method.__name__, sizeMbStr))

    return timed

class Obj(object):
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

class SlotObj(object):
    __slots__ = ('i', 'l')
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

from collections import namedtuple
NT = namedtuple("NT", ["i", 'l'])

@timeit
def profile_dict_of_nt():
    return [NT(i=i, l=makeL(i)) for i in range(ITER_COUNT)]

@timeit
def profile_list_of_nt():
    return dict((i, NT(i=i, l=makeL(i))) for i in range(ITER_COUNT))

@timeit
def profile_dict_of_dict():
    return dict((i, {'i': i, 'l': makeL(i)}) for i in range(ITER_COUNT))

@timeit
def profile_list_of_dict():
    return [{'i': i, 'l': makeL(i)} for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_obj():
    return dict((i, Obj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_obj():
    return [Obj(i) for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_slot():
    return dict((i, SlotObj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_slot():
    return [SlotObj(i) for i in range(ITER_COUNT)]

profile_dict_of_nt()
profile_list_of_nt()
profile_dict_of_dict()
profile_list_of_dict()
profile_dict_of_obj()
profile_list_of_obj()
profile_dict_of_slot()
profile_list_of_slot()
</code>```

And these are my results

```<code>Time Taken = 0:00:07.018720,    provile_dict_of_nt,     Size = 951.83
Time Taken = 0:00:07.716197,    provile_list_of_nt,     Size = 1,084.75
Time Taken = 0:00:03.237139,    profile_dict_of_dict,   Size = 1,926.29
Time Taken = 0:00:02.770469,    profile_list_of_dict,   Size = 1,778.58
Time Taken = 0:00:07.961045,    profile_dict_of_obj,    Size = 1,537.64
Time Taken = 0:00:05.899573,    profile_list_of_obj,    Size = 1,458.05
Time Taken = 0:00:06.567684,    profile_dict_of_slot,   Size = 1,035.65
Time Taken = 0:00:04.925101,    profile_list_of_slot,   Size = 887.49
</code>```

My conclusion is:

Slots have the best memory footprint and are reasonable on speed.

dicts are the fastest, but use the most memory.

Body:
What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?

Background:
I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.

Example:
To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:

Object (execution time ~18sec):

class Obj(object):
  def __init__(self, i):
    self.i = i
    self.l = []
all = {}
for i in range(1000000):
  all[i] = Obj(i)

Dictionary (execution time ~12sec):

all = {}
for i in range(1000000):
  o = {}
  o['i'] = i
  o['l'] = []
  all[i] = o

Question:
Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?

Body:
Here is a copy of @hughdbrown answer for python 3.6.1, I've made the count 5x larger and added some code to test the memory footprint of the python process at the end of each run.

Before the downvoters have at it, Be advised that this method of counting the size of objects is not accurate.

from datetime import datetime
import os
import psutil

process = psutil.Process(os.getpid())

ITER_COUNT = 1000 * 1000 * 5

RESULT=None

def makeL(i):
    # Use this line to negate the effect of the strings on the test
    # return "Python is smart and will only create one string with this line"

    # Use this if you want to see the difference with 5 million unique strings
    return "This is a sample string %s" % i

def timeit(method):
    def timed(*args, **kw):
        global RESULT
        s = datetime.now()
        RESULT = method(*args, **kw)
        e = datetime.now()

        sizeMb = process.memory_info().rss / 1024 / 1024
        sizeMbStr = "{0:,}".format(round(sizeMb, 2))

        print('Time Taken = %s, \t%s, \tSize = %s' % (e - s, method.__name__, sizeMbStr))

    return timed

class Obj(object):
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

class SlotObj(object):
    __slots__ = ('i', 'l')
    def __init__(self, i):
       self.i = i
       self.l = makeL(i)

from collections import namedtuple
NT = namedtuple("NT", ["i", 'l'])

@timeit
def profile_dict_of_nt():
    return [NT(i=i, l=makeL(i)) for i in range(ITER_COUNT)]

@timeit
def profile_list_of_nt():
    return dict((i, NT(i=i, l=makeL(i))) for i in range(ITER_COUNT))

@timeit
def profile_dict_of_dict():
    return dict((i, {'i': i, 'l': makeL(i)}) for i in range(ITER_COUNT))

@timeit
def profile_list_of_dict():
    return [{'i': i, 'l': makeL(i)} for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_obj():
    return dict((i, Obj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_obj():
    return [Obj(i) for i in range(ITER_COUNT)]

@timeit
def profile_dict_of_slot():
    return dict((i, SlotObj(i)) for i in range(ITER_COUNT))

@timeit
def profile_list_of_slot():
    return [SlotObj(i) for i in range(ITER_COUNT)]

profile_dict_of_nt()
profile_list_of_nt()
profile_dict_of_dict()
profile_list_of_dict()
profile_dict_of_obj()
profile_list_of_obj()
profile_dict_of_slot()
profile_list_of_slot()

And these are my results

Time Taken = 0:00:07.018720,    provile_dict_of_nt,     Size = 951.83
Time Taken = 0:00:07.716197,    provile_list_of_nt,     Size = 1,084.75
Time Taken = 0:00:03.237139,    profile_dict_of_dict,   Size = 1,926.29
Time Taken = 0:00:02.770469,    profile_list_of_dict,   Size = 1,778.58
Time Taken = 0:00:07.961045,    profile_dict_of_obj,    Size = 1,537.64
Time Taken = 0:00:05.899573,    profile_list_of_obj,    Size = 1,458.05
Time Taken = 0:00:06.567684,    profile_dict_of_slot,   Size = 1,035.65
Time Taken = 0:00:04.925101,    profile_list_of_slot,   Size = 887.49

My conclusion is:

Slots have the best memory footprint and are reasonable on speed.

dicts are the fastest, but use the most memory.


问:
C# Restart Console Application
This question has been asked before but I cannot find an answer that works.  I need to get a C# CONSOLE program to restart periodically. Each of the other answers use the Application.Restart or Application.ExecutablePath which are not supported in console apps.  What code or reference can I use to restart a C# application?

答:
This command will work:

```<code>System.Windows.Forms.Application.Restart();
</code>```

But you need to make sure you added and referred to correctly assembly. It's System.Windows.Forms in Assembly.

Title: C# Restart Console Application

Body:
This command will work:

System.Windows.Forms.Application.Restart();

But you need to make sure you added and referred to correctly assembly. It's System.Windows.Forms in Assembly.


问:
Sending data between sites
What is a good method to send data from site A to site B without passing a new URL parameter?

For instance, on site A I submit apples are red via a form. How can I send that data to site B without modifying site B's URL structure?

example http://siteb.com/?data=apples+are+red

Not sure if trackbacks or pingbacks use a similar method.

答:
The query string, like your example above, but siteb needs to know what data its getting.

Think of it like the affiliate programs, where you pass a linke to siteb (in this case the affiliate site) from your sitea via the query string, it works because site b knows what to expect.

Title: Sending data between sites


问:
Azure Streaming Analytics custom dlls
I have a c# code which processes real time data and returns some calculations. How can I deploy this c# dll to azure stream analytics?
Any help, recommendations or documents would be very appreciated.
Many thanks</p>

答:
As far as I know, the stream analytics now doesn't support calling the function from the C# dlls. I suggest could try to use the JavaScript user-defined functions.

Azure Stream Analytics supports user-defined functions written in JavaScript. With the rich set of String, RegExp, Math, Array, and Date methods that JavaScript provides, complex data transformations with Stream Analytics jobs become easier to create.

Besides, I suggest you could send a feedback at this site to suggest azure team to include this feature.

Title: Azure Streaming Analytics custom dlls


问:
Increasing disk space for Agents/Worker nodes in Azure Container Service
I have been working with Azure Container Service and have been able to successfully create a ACS cluster which uses Kubernetes orchestratration. I have also created another ACS cluster which uses Docker-Swarm orchestration.

My question is related to the OS disks of the agent VM that are created by ACS. By Default, all the OS disks have 30GB and it seems all the container images and containers are stored on the OS disks. I hit the 30 GB limit with about 15 containers and about 10-15 images. Am I doing something wrong here?

I can create VMs with more disk space but it appears that the disk is another mount. Should I be making some change to allow the orchestration engine and docker to use the non-default drive? If so, any help on this would be appreciated.

In parallel, I did setup a Ubuntu VM and again by default the OS drive had 30 GB and the secondary had 100 GB. I changed docker-engine to use the secondary drive mount for storing the containers and images. This off course involved me SSHing into the machine and changing some docker settings. I don't presume we should be doing a similar thing on ACS as its a PaaS offering?

答:
You could increase Kubernetes agent OS disk. Kubernetes agent as Azure VM as agents. More information about this please refer to this link: Azure VM supports increase OS disk. Please refer to the following steps.

1.Stop your k8s agent VM. You could do it on Azure Portal.

2.Increase OS disk size. <agent VM>--><Disks>--><OS Disk>

3.Start your k8s agent VM.

4.ssh to agent VM and check.

```<code>shui@k8s-agent-431B3739-0:~$ df -h

Filesystem      Size  Used Avail Use% Mounted on
udev            1.7G     0  1.7G   0% /dev
tmpfs           344M  5.2M  339M   2% /run
/dev/sda1        97G  2.8G   95G   3% /
</code>```

But Docker-Swarm orchestration use Azure VMSS as agents. For now, VMSS does not support resize OS disk size, you could add new disks on them, please refer to this link.

Body:
You could increase Kubernetes agent OS disk. Kubernetes agent as Azure VM as agents. More information about this please refer to this link: Azure VM supports increase OS disk. Please refer to the following steps.

1.Stop your k8s agent VM. You could do it on Azure Portal.

2.Increase OS disk size. <agent VM>--><Disks>--><OS Disk>

3.Start your k8s agent VM.

4.ssh to agent VM and check.

shui@k8s-agent-431B3739-0:~$ df -h

Filesystem      Size  Used Avail Use% Mounted on
udev            1.7G     0  1.7G   0% /dev
tmpfs           344M  5.2M  339M   2% /run
/dev/sda1        97G  2.8G   95G   3% /

But Docker-Swarm orchestration use Azure VMSS as agents. For now, VMSS does not support resize OS disk size, you could add new disks on them, please refer to this link.


问:
Training locally with ML Engine & GCloud
I would like to train my model locally using this command:

```<code>gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output
</code>```

The issue is that it complains that --job-dir: Must be of form gs://bucket/object.

This is a local train so I'm wondering why it wants the output to be a gs storage bucket rather than a local directory.

答:
The --package-path argument to the gcloud command should point to a directory that is a valid Python package, i.e., a directory that contains an init.py file (often an empty file). Note that it should be a local directory, not one on GCS.

The --module argument will be the fully qualified name of a valid Python module within that package. You can organize your directories however you want, but for the sake of consistency, the samples all have a Python package named trainer with the module to be run named task.py.

-- Source

So you need to change this block with valid path:

```<code>gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output
</code>```

Specifically, your error is due to --job-dir ./tmp/output because it is expecting a path on your gcloud

Body:
I would like to train my model locally using this command:

gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output

The issue is that it complains that --job-dir: Must be of form gs://bucket/object.

This is a local train so I'm wondering why it wants the output to be a gs storage bucket rather than a local directory.

Body:
The --package-path argument to the gcloud command should point to a directory that is a valid Python package, i.e., a directory that contains an init.py file (often an empty file). Note that it should be a local directory, not one on GCS.

The --module argument will be the fully qualified name of a valid Python module within that package. You can organize your directories however you want, but for the sake of consistency, the samples all have a Python package named trainer with the module to be run named task.py.

-- Source

So you need to change this block with valid path:

gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output

Specifically, your error is due to --job-dir ./tmp/output because it is expecting a path on your gcloud


问:
How to have a Python script for a Django app that accesses models without using the manage.py shell?
I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running ./manage.py shell and then import myscript. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using python scriptname.py, and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using manage.py shell.

What do I need to add to my script to achieve this?

EDIT:

Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:

```<code>import sys
sys.path.append('c:\\my_projec_src_folder')
from myproject import settings
from django.core.management import setup_environ
setup_environ(settings)
</code>```

答:
If you get:

```<code>django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
</code>```

Try:

```<code>import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
application = get_wsgi_application()
</code>```

Body:
I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running ./manage.py shell and then import myscript. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using python scriptname.py, and in the first few lines of that script it would do whatever imports / other operations necessary so that it can access model objects and behave as though it was run using manage.py shell.

What do I need to add to my script to achieve this?

EDIT:

Based on @Melug's answer, with addition of dynamically setting Python path to address the 'anywhere on my HD' part of the question:

import sys
sys.path.append('c:\\my_projec_src_folder')
from myproject import settings
from django.core.management import setup_environ
setup_environ(settings)

Body:
If you get:

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Try:

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
application = get_wsgi_application()


问:
Using case statement getting error as incorrect syntax
In store procedure I am placing code as

```<code>SELECT *
FROM [Order] O
INNER JOIN Users U ON O.UserId=U.UserId
INNER JOIN State S ON S.StateId=O.Billing_StateId
INNER JOIN OrderStatus OS ON O.OrderStatusId=OS.OrderStatusId
WHERE (CASE WHEN ISNULL(@Name,'')='' THEN 0=0  ELSE O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%' END)
AND (CASE WHEN ISNULL(@Email,'')='' THEN 0=0  ELSE O.Billing_Email LIKE '%' + @Email + '%' END)
</code>```

but it is giving error as Incorrect syntax near =

I dont know what I am doing wrong in placing THEN 0=0 ?

If it is wrong what should I wrote over there and is my query ok?

If @Name parameter is not there then it will not check 1st condition and will check for next condition

答:
You can try this.</p>

```<code>WHERE (@Name IS NULL OR( O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%' ))
AND (@Email IS NULL OR ( O.Billing_Email LIKE '%' + @Email + '%'))
</code>```

Body:
In store procedure I am placing code as

SELECT *
FROM [Order] O
INNER JOIN Users U ON O.UserId=U.UserId
INNER JOIN State S ON S.StateId=O.Billing_StateId
INNER JOIN OrderStatus OS ON O.OrderStatusId=OS.OrderStatusId
WHERE (CASE WHEN ISNULL(@Name,'')='' THEN 0=0  ELSE O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%' END)
AND (CASE WHEN ISNULL(@Email,'')='' THEN 0=0  ELSE O.Billing_Email LIKE '%' + @Email + '%' END)

but it is giving error as Incorrect syntax near =

I dont know what I am doing wrong in placing THEN 0=0 ?

If it is wrong what should I wrote over there and is my query ok?

If @Name parameter is not there then it will not check 1st condition and will check for next condition

Body:
You can try this.

WHERE (@Name IS NULL OR( O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%' ))
AND (@Email IS NULL OR ( O.Billing_Email LIKE '%' + @Email + '%'))


问:
Trying to get counts through multiple associations
I have created a question an answer app for a client much like StackOverflow. I am not trying to implement some sort of point system (like SO reputation). I am trying to get certain record counts through associations (which I believe are set up correctly). Primarily I am trying to get counts for votes on users answers. Here is an example.

In /views/questions/show page I list all the answers to that question by calling a partial _answer.html.erb. With each answer I pull in the answer.user information (username, email, etc.) by simply doing answer.user.username. I am wanting to display in a badge like format some total point calculations. So if User A answered Question A, next to User A's answer I want to display a total of all User A's answer votes.

I can successfully get a count for a users answers in /views/answers/_answer.html.erb by doing the following:

```<code><%= answer.user.answers.count %>
</code>```

but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

```<code><%= answer.user.answers.votes.count %>
</code>```

Is my set up fundamentally wrong here or am I missing something.

That is a bit confusing so let me know if you need more detail.

UPDATE:

Here are the associations:

Answers

```<code>class Answer < ActivRecord::Base
  belongs_to :question
  belongs_to :user
  has_many :votes, :dependent => :destroy
end
</code>```

Votes

```<code>class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user
  belongs_to :question
end
</code>```

Users

```<code>class User < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy
  has_many :votes, :through => :answers , :dependent => :destroy
end
</code>```

答:
```<code><%= answer.user.answers.votes.count %>
</code>```

but

```<code>answer.user.answers
</code>```

is an array of answers so I suppose you wanted something like

```<code><%= answer.user.answers[id].votes.count %>
</code>```

UPDATE

```<code><% answer.user.answers.each do |answer| %>
    <%= answer.votes.count%>
<% end% >
</code>```

UPDATE

```<code> <%= (answer.user.answers.map{|x| x.votes.count}).sum%>
</code>```

I LOVE rails for such things

Body:
I have created a question an answer app for a client much like StackOverflow. I am not trying to implement some sort of point system (like SO reputation). I am trying to get certain record counts through associations (which I believe are set up correctly). Primarily I am trying to get counts for votes on users answers. Here is an example.

In /views/questions/show page I list all the answers to that question by calling a partial _answer.html.erb. With each answer I pull in the answer.user information (username, email, etc.) by simply doing answer.user.username. I am wanting to display in a badge like format some total point calculations. So if User A answered Question A, next to User A's answer I want to display a total of all User A's answer votes.

I can successfully get a count for a users answers in /views/answers/_answer.html.erb by doing the following:

<%= answer.user.answers.count %>

but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

<%= answer.user.answers.votes.count %>

Is my set up fundamentally wrong here or am I missing something.

That is a bit confusing so let me know if you need more detail.

UPDATE:

Here are the associations:

Answers

class Answer < ActivRecord::Base
  belongs_to :question
  belongs_to :user
  has_many :votes, :dependent => :destroy
end

Votes

class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user
  belongs_to :question
end

Users

class User < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy
  has_many :votes, :through => :answers , :dependent => :destroy
end

Body:
<%= answer.user.answers.votes.count %>

but

answer.user.answers

is an array of answers so I suppose you wanted something like

<%= answer.user.answers[id].votes.count %>

UPDATE

<% answer.user.answers.each do |answer| %>
    <%= answer.votes.count%>
<% end% >

UPDATE

 <%= (answer.user.answers.map{|x| x.votes.count}).sum%>

I LOVE rails for such things


问:
How to extract href links from anchor tags using BeautifulSoup?
I've been trying to extract just the links corresponding to the jobs on each page. But for some reason they dont print when I execute the script. No errors occur.
for the inputs I put engineering, toronto respectively. Here is my code.</p>

```<code>import requests
from bs4 import BeautifulSoup
import webbrowser

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

all_job_url = []

for tag in prettify.find_all('div', {'data-tn-element':"jobTitle"}):
    for links in tag.find_all('a'):
        print (links['href'])
</code>```

答:
You should be looking for the anchor a tag. It looks like this:

```<code><a class="turnstileLink" data-tn-element="jobTitle" href="/rc/clk?jk=3611ac98c0167102&fccid=459dce363200e1be" ...>Project <b>Engineer</b></a>
</code>```

Call soup.find_all and iterate over the result set, extracting the links through the href attribute.

```<code>import requests
from bs4 import BeautifulSoup

# valid query, replace with something else
url = "https://ca.indeed.com/jobs?q=engineer&l=Calgary%2C+AB"

r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")

all_job_url = []
for tag in soup.find_all('a', {'data-tn-element':"jobTitle"}):
    all_job_url.append(tag['href'])
</code>```

Body:
I've been trying to extract just the links corresponding to the jobs on each page. But for some reason they dont print when I execute the script. No errors occur.
for the inputs I put engineering, toronto respectively. Here is my code.

import requests
from bs4 import BeautifulSoup
import webbrowser

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

all_job_url = []

for tag in prettify.find_all('div', {'data-tn-element':"jobTitle"}):
    for links in tag.find_all('a'):
        print (links['href'])

Body:
You should be looking for the anchor a tag. It looks like this:

<a class="turnstileLink" data-tn-element="jobTitle" href="/rc/clk?jk=3611ac98c0167102&amp;fccid=459dce363200e1be" ...>Project <b>Engineer</b></a>

Call soup.find_all and iterate over the result set, extracting the links through the href attribute.

import requests
from bs4 import BeautifulSoup

# valid query, replace with something else
url = "https://ca.indeed.com/jobs?q=engineer&l=Calgary%2C+AB"

r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")

all_job_url = []
for tag in soup.find_all('a', {'data-tn-element':"jobTitle"}):
    all_job_url.append(tag['href'])


问:
Arbitrary filters for conv2d (as opposed to rectangular)
I using convolutional layers on data samples that consist of 2d images. One option for the shape of the filter is 1x2, which acts on a 1x2 contiguous block of two neighbor pixels. What if I want to have a filter which also acts on 2 pixels, but the pixels are separated by another one between them? Is it possible to encode such a filter for convolutions in the neural network?</p>

答:
Code to make it work

You can also watch a video of how to make it work with Keras

Here is some example code which defines a kernel for Conv2d and a 5x5 mask that only lets the center and outside values pass through.

```<code>image = np.array( range(25) ).reshape([1,5,5,1] ).astype( float )

kern = tf.Variable( tf.ones( [5,5,1,1] , dtype=tf.float32) )

mask = np.array([[ 1,  1,  1,  1,  1],
                 [ 1,  0,  0,  0,  1],
                 [ 1,  0,  1,  0,  1],
                 [ 1,  0,  0,  0,  1],
                 [ 1,  1,  1,  1,  1]]).reshape( [5,5,1,1] )

mask_variable = tf.constant( mask , dtype=tf.float32 )

output           = tf.nn.conv2d( image , kern        , strides=[1,1,1,1] , padding="VALID" )
output_with_mask = tf.nn.conv2d( image , kern * mask , strides=[1,1,1,1] , padding="VALID" )

print("Using whole kernal :",output.numpy())
print("Using kernal with a mask :",output_with_mask.numpy())
</code>```

And the output

```<code>Using whole kernal : [[[[ 300.]]]]
Using kernal with a mask : [[[[ 204.]]]]
</code>```

Furthermore, backprop will not change the mask because the mask is wrapped in tf.stop_gradient.

cheers

Body:
Code to make it work

You can also watch a video of how to make it work with Keras

Here is some example code which defines a kernel for Conv2d and a 5x5 mask that only lets the center and outside values pass through.

image = np.array( range(25) ).reshape([1,5,5,1] ).astype( float )

kern = tf.Variable( tf.ones( [5,5,1,1] , dtype=tf.float32) )

mask = np.array([[ 1,  1,  1,  1,  1],
                 [ 1,  0,  0,  0,  1],
                 [ 1,  0,  1,  0,  1],
                 [ 1,  0,  0,  0,  1],
                 [ 1,  1,  1,  1,  1]]).reshape( [5,5,1,1] )

mask_variable = tf.constant( mask , dtype=tf.float32 )

output           = tf.nn.conv2d( image , kern        , strides=[1,1,1,1] , padding="VALID" )
output_with_mask = tf.nn.conv2d( image , kern * mask , strides=[1,1,1,1] , padding="VALID" )

print("Using whole kernal :",output.numpy())
print("Using kernal with a mask :",output_with_mask.numpy())

And the output

Using whole kernal : [[[[ 300.]]]]
Using kernal with a mask : [[[[ 204.]]]]

Furthermore, backprop will not change the mask because the mask is wrapped in tf.stop_gradient.

cheers


问:
jQuery auto complete library return an error of not found url and no data displayed at the text box
I have to do an auto complete text box in my app using jquery-ui. I have this Ajax script to get data from database:

```<code><script>
$( function() {
  $("#searchTxt").on('keyup', function(){

    searchTxt = $("#searchTxt").val();
    $.ajax({
      url: '../php/autoComplete.php',
      data: {searchTxt: searchTxt},
      type: 'GET',
      dataType: 'JSON',
      success:function(resp)
      {
        $.each( resp, function(key, result)
        {
          var availableTags = result['patient_name_en'];
          $( "#searchTxt" ).autocomplete({
            source: availableTags
          });
        });

      },
      error:function(resp)
      {
        console.log(resp)
      }
    })

  } );

});
</script>
</code>```

And here is the autoComplete.php script:

```<code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');

$cid = $_SESSION['clinic_id'];
$searchTxt = '%'.$_GET['searchTxt'].'%';
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid and patient_name_en LIKE :searchTxt ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->bindValue(':searchTxt', $searchTxt);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>
</code>```

The problem is that I can see the data returned at the network tab of the developer tool but with another file returned with an error of The requested URL /ncd/... was not found on this server.

Here is an image of the situation where I can see an array returned with no errors:

And here is the other red file:

At the console:

I tried to change the type from get to post but still the same problem.

答:
You don't have this structured correctly. Your ajax call should be a function of autocomplete. You have it inverted and it looks like it's assigned unexpected parameters to your autocomplete element.

See this example here for reference: https://jqueryui.com/autocomplete/#remote

Following that example, if we assume your AJAX endpoint returns properly structured data, your code should look something like this:

```<code>$( "#searchTxt" ).autocomplete({
  // I'd recommend using an absolute url.
  source: "/ncd/php/autoComplete.php"
});
</code>```

If you open up your console and inspect the response in the documented example, the JSON data is structured like so:

```<code>[
  {"id":"Nycticorax nycticorax","label":"Black-crowned Night Heron","value":"Black-crowned Night Heron"},
  {"id":"Corvus cornix","label":"Hooded Crow","value":"Hooded Crow"},
  {"id":"Corvus corone","label":"Carrion Crow","value":"Carrion Crow"},
  etc...
]
</code>```

So you'll probably want to update the way your endpoint structures its response.

Body:
I have to do an auto complete text box in my app using jquery-ui. I have this Ajax script to get data from database:

And here is the autoComplete.php script:

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');

$cid = $_SESSION['clinic_id'];
$searchTxt = '%'.$_GET['searchTxt'].'%';
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid and patient_name_en LIKE :searchTxt ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->bindValue(':searchTxt', $searchTxt);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>

The problem is that I can see the data returned at the network tab of the developer tool but with another file returned with an error of The requested URL /ncd/... was not found on this server.

Here is an image of the situation where I can see an array returned with no errors:

And here is the other red file:

At the console:

I tried to change the type from get to post but still the same problem.

Body:
You don't have this structured correctly. Your ajax call should be a function of autocomplete. You have it inverted and it looks like it's assigned unexpected parameters to your autocomplete element.

See this example here for reference: https://jqueryui.com/autocomplete/#remote

Following that example, if we assume your AJAX endpoint returns properly structured data, your code should look something like this:

$( "#searchTxt" ).autocomplete({
  // I'd recommend using an absolute url.
  source: "/ncd/php/autoComplete.php"
});

If you open up your console and inspect the response in the documented example, the JSON data is structured like so:

[
  {"id":"Nycticorax nycticorax","label":"Black-crowned Night Heron","value":"Black-crowned Night Heron"},
  {"id":"Corvus cornix","label":"Hooded Crow","value":"Hooded Crow"},
  {"id":"Corvus corone","label":"Carrion Crow","value":"Carrion Crow"},
  etc...
]

So you'll probably want to update the way your endpoint structures its response.


问:
Validate file upload in rails
I need to control the weight and size in pixels of an image, this is my code:

```<code><div class="control-group row">
            <%= f.fields_for :activity_documents, @activity.activity_documents do |builder| %>

            <div class="span6">
                <%= builder.label "Nombre de la imagen"  %>
                <%= builder.text_field :name, class:'imagen_file',:required => true, data:{required:true}, :placeholder=>'Nombre de la imagen' %>
            </div>

            <div class="span5">
                <%= builder.label "Imagen"  %>
                <% if builder.object.document_file_name? %>

                <%= image_tag builder.object.document.url, :id=>"file" %>

            <% else %>
                <%= builder.file_field :document, class:'form-control',data:{required:true}, style:'background-color:#e9e9e9; width:200px;', :id => 'file' %>

                <% end %>
                <%= builder.link_to_remove class:'btn btn-danger' do %>
                <i class="fa fa-minus"></i>
                <% end %>
            </div>
            <% end %>
        </div>
</code>```

I need when I select an image check the resolution and weigh

答:
```<code>$(document).ready(function(){
 var width = $('#file').width();
 var height = $('#file').height();
 if(width > 400 || height > 200){
 alert('please try a small image');
}
});
</code>```

Title: Validate file upload in rails

Body:
I need to control the weight and size in pixels of an image, this is my code:

            <%= f.fields_for :activity_documents, @activity.activity_documents do |builder| %>

                <%= builder.label "Nombre de la imagen"  %>
                <%= builder.text_field :name, class:'imagen_file',:required => true, data:{required:true}, :placeholder=>'Nombre de la imagen' %>

                <%= builder.label "Imagen"  %>
                <% if builder.object.document_file_name? %>

                <%= image_tag builder.object.document.url, :id=>"file" %>

            <% else %>
                <%= builder.file_field :document, class:'form-control',data:{required:true}, style:'background-color:#e9e9e9; width:200px;', :id => 'file' %>

                <% end %>
                <%= builder.link_to_remove class:'btn btn-danger' do %>

                <% end %>

            <% end %>

I need when I select an image check the resolution and weigh


问:
Publishing multiple versions of one app on Google Market
I have an Android app that I would like to display high quality images with. However there are many different screen sizes and ratios. I know there are filters to show apps in Market only for devices with small/medium/large screens.

If I put images of both sizes in 1 app it will double the size of the app, right?

Is it a good practice to make multiple versions for different screen sizes?

I would like to make 1 app in 3 versions for such devices:

medium screen mdpi

medium screen hdpi + large screen mdpi

large (tablets)

If it's possible to do it how can I specify them in manifests? Or is it somewhere in market?

答:
As Donut mentions above android has excellent documentation for this here, here, here and here.

Note that all Manifest file changes and how to create one binary that will support different screen sizes, different densities AND different SDK's are at android website. But it requires careful planning and testing to do so.

The best way is to have ALL device configurations (listed here, including the Samsung Galaxy Tab simulater (large screen, hdpi) available here) in your development environment and test your app on them.


问:
Add default value for date column
I am trying to add an default value for my date column. The default value should be GETDATE(). I want to do this so I can see the date of the created row. When I try to save it I get the warning: Incorrect default value for date.

Does someone know why I am getting the warning and how I can fix it?

答:
Run this query

```<code>ALTER TABLE `YourDb.yourtable`
    CHANGE COLUMN `date` `date` DATETIME DEFAULT CURRENT_TIMESTAMP;
</code>```

The Change column is oldval newval and the type
make sure if your column name isnt date to change it appropriately

additionally if you want that timestamp to update when the row is modified use

```<code>CHANGE COLUMN `date` `date` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
</code>```

Title: Add default value for date column

Body:
Run this query

ALTER TABLE `YourDb.yourtable`
    CHANGE COLUMN `date` `date` DATETIME DEFAULT CURRENT_TIMESTAMP;

The Change column is oldval newval and the type
make sure if your column name isnt date to change it appropriately

additionally if you want that timestamp to update when the row is modified use

CHANGE COLUMN `date` `date` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP


问:
Get first element of sublist as dictionary key in python
I looked but i didn't found the answer (and I'm pretty new to python).

The question is pretty simple. I have a list made of sublists:

```<code>ll
[[1,2,3], [4,5,6], [7,8,9]]
</code>```

What I'm trying to do is to create a dictionary that has as key the first element of each sublist and as values the values of the coorresponding sublists, like:

```<code>d = {1:[2,3], 4:[5,6], 7:[8,9]}
</code>```

How can I do that?

答:
Another variation on the theme:</p>

```<code>d = {e.pop(0): e for e in ll}
</code>```

Body:
I looked but i didn't found the answer (and I'm pretty new to python).

The question is pretty simple. I have a list made of sublists:

ll
[[1,2,3], [4,5,6], [7,8,9]]

What I'm trying to do is to create a dictionary that has as key the first element of each sublist and as values the values of the coorresponding sublists, like:

d = {1:[2,3], 4:[5,6], 7:[8,9]}

How can I do that?

Body:
Another variation on the theme:

d = {e.pop(0): e for e in ll}


问:
Scala: Requiring members on companion objects of abstract classes
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

```<code>abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false
</code>```

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

答:
Many thanks to Yuval for teaching me about typeclasses; I have written a solution using his technique which satisfies all my original criteria:

```<code>// Fruit instance members
abstract class FruitClass(cultivar: String) {
    def getCultivar: String = cultivar
}

// Obviously not really an object but serves the purpose of
// the thing I envisioned as the "abstract object" which is not a thing
// I.e., a place to put fruit static members
trait FruitObject[A <: FruitClass] {
    // Any subclass of fruit must (statically) specify their set of tasty cultivars...
    val tastyCultivars: Set[String]
    // ...but they can inherit the common implementation of isTastyCultivar()
    def isTastyCultivar(x: A): Boolean = tastyCultivars contains x.getCultivar
}

// Subclass #1: Apples
class Apple(cultivar: String) extends FruitClass(cultivar)
implicit object AppleIsFruit extends FruitObject[Apple] {
    val tastyCultivars = Set("Red Delicious", "Granny Smith")
}

// Subclass #2: Tomatoes
class Tomato(cultivar: String) extends FruitClass(cultivar)
implicit object TomatoIsFruit extends FruitObject[Tomato] {
    val tastyCultivars = Set("Roma")
}

def isTastyCultivar[A <: FruitClass: FruitObject](thing: A) =
    implicitly[FruitObject[A]].isTastyCultivar(thing)

isTastyCultivar(new Apple("Red Delicious"))    // true
isTastyCultivar(new Apple("Honeycrisp"))    // false
isTastyCultivar(new Tomato("Roma"))            // true
isTastyCultivar(new Tomato("San Marzano"))    // false
</code>```

Gustek is quite right that object members cannot be overridden but this method seems to achieve the same effect without actually using a companion object for Fruit to declare static members.

Body:
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

Body:
Many thanks to Yuval for teaching me about typeclasses; I have written a solution using his technique which satisfies all my original criteria:

// Fruit instance members
abstract class FruitClass(cultivar: String) {
    def getCultivar: String = cultivar
}

// Obviously not really an object but serves the purpose of
// the thing I envisioned as the "abstract object" which is not a thing
// I.e., a place to put fruit static members
trait FruitObject[A <: FruitClass] {
    // Any subclass of fruit must (statically) specify their set of tasty cultivars...
    val tastyCultivars: Set[String]
    // ...but they can inherit the common implementation of isTastyCultivar()
    def isTastyCultivar(x: A): Boolean = tastyCultivars contains x.getCultivar
}

// Subclass #1: Apples
class Apple(cultivar: String) extends FruitClass(cultivar)
implicit object AppleIsFruit extends FruitObject[Apple] {
    val tastyCultivars = Set("Red Delicious", "Granny Smith")
}

// Subclass #2: Tomatoes
class Tomato(cultivar: String) extends FruitClass(cultivar)
implicit object TomatoIsFruit extends FruitObject[Tomato] {
    val tastyCultivars = Set("Roma")
}

def isTastyCultivar[A <: FruitClass: FruitObject](thing: A) =
    implicitly[FruitObject[A]].isTastyCultivar(thing)

isTastyCultivar(new Apple("Red Delicious"))    // true
isTastyCultivar(new Apple("Honeycrisp"))    // false
isTastyCultivar(new Tomato("Roma"))            // true
isTastyCultivar(new Tomato("San Marzano"))    // false

Gustek is quite right that object members cannot be overridden but this method seems to achieve the same effect without actually using a companion object for Fruit to declare static members.


问:
animate if a checkbox isn't checked and a user tries to proceed
This is what I have so far

```<code>$(document).on('click', '.signin', function() {
        if ($('#signinbox').prop('checked') == true) {
            window.location.href = '/api/login';
         }
}
</code>```

What I'm trying to achieve: If a user tries to log in without checking the box, then it invokes the shake animation in animate.css to give them feedback.

答:
Effectively, it seems you're just needing a conditional. Below, I'm casting the checkbox's checked attribute state to a Boolean and based on that, appropriating the desired action. In particular, I'm only navigating to the login URL if it is checked. The window.location.href line is only hit if the checkbox is checked.

Note, I haven't actually tested this code, but this seems like the barebones structure for what you're looking for.

```<code>$(document).on('click', '.signin', function() {
  const $signInBox = $('#signinbox');
  if (!$signInBox.prop('checked')) {
    return $signInBox.addClass('animated shake');
  } else
    return window.location.href = '/api/login';
  }
});
</code>```

Body:
This is what I have so far

$(document).on('click', '.signin', function() {
        if ($('#signinbox').prop('checked') == true) {
            window.location.href = '/api/login';
         }
}

What I'm trying to achieve: If a user tries to log in without checking the box, then it invokes the shake animation in animate.css to give them feedback.

Body:
Effectively, it seems you're just needing a conditional. Below, I'm casting the checkbox's checked attribute state to a Boolean and based on that, appropriating the desired action. In particular, I'm only navigating to the login URL if it is checked. The window.location.href line is only hit if the checkbox is checked.

Note, I haven't actually tested this code, but this seems like the barebones structure for what you're looking for.

$(document).on('click', '.signin', function() {
  const $signInBox = $('#signinbox');
  if (!$signInBox.prop('checked')) {
    return $signInBox.addClass('animated shake');
  } else
    return window.location.href = '/api/login';
  }
});


答:
Alright, the jist of what you want to do is to add the class 'shake' when the checkbox hasn't been checked and remove the class when the animation ends

```<code>var checkbox = document.getElementById('checkbox');
var form = document.getElementById('form');

form.addEventListener('animationend', function(e){
    e.target.classList.remove('shake');
})

document.getElementById('login').addEventListener('click', function(e){
    e.preventDefault();
  e.stopPropagation();

  if(!checkbox.checked){
    form.classList.add('shake');
  } else {
    console.log('logged in!');
  }
})
</code>```

https://jsfiddle.net/o3spo0qL/

Title: animate if a checkbox isn't checked and a user tries to proceed

Body:
Alright, the jist of what you want to do is to add the class 'shake' when the checkbox hasn't been checked and remove the class when the animation ends

var checkbox = document.getElementById('checkbox');
var form = document.getElementById('form');

form.addEventListener('animationend', function(e){
    e.target.classList.remove('shake');
})

document.getElementById('login').addEventListener('click', function(e){
    e.preventDefault();
  e.stopPropagation();

  if(!checkbox.checked){
    form.classList.add('shake');
  } else {
    console.log('logged in!');
  }
})

https://jsfiddle.net/o3spo0qL/


问:
Extracting ByteBuffer from GenericRecord sometimes has extra values
I serialise objects to avro format in spark. These objects include byte arrays (edit: polylines, which are represented as strings). When I inspect the file, the data is correct.

```<code>$ java -jar ~/data/avro-tools-1.8.1.jar tojson part-00000.avro | grep 123
{"key":123, "data":{"bytes":"gt_upA`mjrcE{Cw^uBwY"}}
# ^ this example has been simplified for this question
</code>```

gt_upA`mjrcE{Cw^uBwY is the correct string representation of the byte array.

I then try to deserialise these files in my plain Scala app. Most values are parsed correctly, but sometimes there are extra bytes in the parsed arrays.

```<code>val entity: GenericRecord
val byteBuffer = entity.get("data").asInstanceOf[ByteBuffer]
println(new String(byteBuffer.array, "UTF-8"))
</code>```

Results in gt_upA`mjrcE{Cw^uBwYB. Note the extra trailing B.

I am parsing the files in parallel, and I guess that the ByteBuffer instance is not thread safe and backing arrays are being overwritten.

How should I be parsing these files?

edit: While the question stands, I have since encoded the values as UTF-8 strings directly. It adds additional work when parsing, but avoids the problems with ByteBuffer's inability to be read concurrently.

答:
you can't print arbitrary binary data as UTF-8. Some byte combinations are invalid or ambiguous, and converting them to characters isn't well defined, and depends on the library you are using (and also on your terminal setting).

Just print them as hexademicals instead:

```<code>byteBuffer.array.foreach { b => print("%02X".format(b)) }
println
</code>```

Body:
I serialise objects to avro format in spark. These objects include byte arrays (edit: polylines, which are represented as strings). When I inspect the file, the data is correct.

$ java -jar ~/data/avro-tools-1.8.1.jar tojson part-00000.avro | grep 123
{"key":123, "data":{"bytes":"gt_upA`mjrcE{Cw^uBwY"}}
# ^ this example has been simplified for this question

gt_upA`mjrcE{Cw^uBwY is the correct string representation of the byte array.

I then try to deserialise these files in my plain Scala app. Most values are parsed correctly, but sometimes there are extra bytes in the parsed arrays.

val entity: GenericRecord
val byteBuffer = entity.get("data").asInstanceOf[ByteBuffer]
println(new String(byteBuffer.array, "UTF-8"))

Results in gt_upA`mjrcE{Cw^uBwYB. Note the extra trailing B.

I am parsing the files in parallel, and I guess that the ByteBuffer instance is not thread safe and backing arrays are being overwritten.

How should I be parsing these files?

edit: While the question stands, I have since encoded the values as UTF-8 strings directly. It adds additional work when parsing, but avoids the problems with ByteBuffer's inability to be read concurrently.

Body:
you can't print arbitrary binary data as UTF-8. Some byte combinations are invalid or ambiguous, and converting them to characters isn't well defined, and depends on the library you are using (and also on your terminal setting).

Just print them as hexademicals instead:

byteBuffer.array.foreach { b => print("%02X".format(b)) }
println


答:
You can do something like this:

If the checkbox is not checked, you can add the animated classes and then remove it after some time, like this:

$(document).on('click', '.signin', function() {
  if ($('#signinbox').prop('checked') == true) {
    window.location.href = '/api/login';
  } else {
    $('.signin').addClass('animated shake');

    setTimeout(function() {
      $('.signin').removeClass('animated shake');
    }, 1000);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" class="signin">Login</button>
  <input type="checkbox" id="signinbox">
</div></code>```

Body:
You can do something like this:

If the checkbox is not checked, you can add the animated classes and then remove it after some time, like this:

$(document).on('click', '.signin', function() {
  if ($('#signinbox').prop('checked') == true) {
    window.location.href = '/api/login';
  } else {
    $('.signin').addClass('animated shake');

    setTimeout(function() {
      $('.signin').removeClass('animated shake');
    }, 1000);
  }
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" class="signin">Login</button>
  <input type="checkbox" id="signinbox">
</div>


问:
How to change the screenshot path in Rails 5.1 system test
Using Rails 5.1.2
Creating a system test and using the take_screenshot method.

How do i change the location these screenshots are created at?

答: Looks like the image path is hardcoded in, so you won't be able to change it currently. Probably wouldn't be too difficult to change if you wanted to open an issue over there or create a pull request for them.</p>


答:
Try this:</p>

```<code>SELECT *
FROM [Order] O
INNER JOIN Users U ON O.UserId=U.UserId
INNER JOIN State S ON S.StateId=O.Billing_StateId
INNER JOIN OrderStatus OS ON O.OrderStatusId=OS.OrderStatusId
WHERE
(NULLIF(@Name,'') IS NULL OR O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%')
AND (NULLIF(@Email,'') IS NULL OR O.Billing_Email LIKE '%' + @Email + '%')
</code>```

Title: Using case statement getting error as incorrect syntax

Body:
In store procedure I am placing code as

SELECT *
FROM [Order] O
INNER JOIN Users U ON O.UserId=U.UserId
INNER JOIN State S ON S.StateId=O.Billing_StateId
INNER JOIN OrderStatus OS ON O.OrderStatusId=OS.OrderStatusId
WHERE (CASE WHEN ISNULL(@Name,'')='' THEN 0=0  ELSE O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%' END)
AND (CASE WHEN ISNULL(@Email,'')='' THEN 0=0  ELSE O.Billing_Email LIKE '%' + @Email + '%' END)

but it is giving error as Incorrect syntax near =

I dont know what I am doing wrong in placing THEN 0=0 ?

If it is wrong what should I wrote over there and is my query ok?

If @Name parameter is not there then it will not check 1st condition and will check for next condition

Body:
Try this:

SELECT *
FROM [Order] O
INNER JOIN Users U ON O.UserId=U.UserId
INNER JOIN State S ON S.StateId=O.Billing_StateId
INNER JOIN OrderStatus OS ON O.OrderStatusId=OS.OrderStatusId
WHERE
(NULLIF(@Name,'') IS NULL OR O.Billing_FirstName LIKE '%' + @Name + '%' OR O.Billing_LastName LIKE'%' + @Name + '%')
AND (NULLIF(@Email,'') IS NULL OR O.Billing_Email LIKE '%' + @Email + '%')


问:
javascript switch break unreachable code detected
I have the following code

```<code>   switch (attr.templateType) {

      case 'text': return tpl_default; break;
      case 'currency': return tpl_currency; break;
      case 'percentage': return tpl_percentage; break;
      case 'latlong': return tpl_latlong; break;
      case 'tel': return tpl_phone; break;
      case 'number': return tpl_number; break;
      case 'address': return tpl_address; break;
      case 'date': return tpl_date; break;
      case 'permissions': return tpl_permissions; break;
      case 'pagination': return tpl_pagination; break;
      case 'time': return tpl_time; break;
      case 'notEmpty': return tpl_notEmpty; break;

      default: return tpl_default; break;
    }
</code>```

and JavaScript lint tells me "unreachable code detected" for ALL the breaks.  If i take out the breaks, lint has no errors.

does anyone know why?  The code works and with out any errors.

答:
you don't need break because you are returning out of the function.
No code will execute after the return</p>

Body:
I have the following code

   switch (attr.templateType) {

      case 'text': return tpl_default; break;
      case 'currency': return tpl_currency; break;
      case 'percentage': return tpl_percentage; break;
      case 'latlong': return tpl_latlong; break;
      case 'tel': return tpl_phone; break;
      case 'number': return tpl_number; break;
      case 'address': return tpl_address; break;
      case 'date': return tpl_date; break;
      case 'permissions': return tpl_permissions; break;
      case 'pagination': return tpl_pagination; break;
      case 'time': return tpl_time; break;
      case 'notEmpty': return tpl_notEmpty; break;

      default: return tpl_default; break;
    }

and JavaScript lint tells me "unreachable code detected" for ALL the breaks.  If i take out the breaks, lint has no errors.

does anyone know why?  The code works and with out any errors.


答: why is break required after return? switch will return and break will never execute, that is why it is unreachable.</p>

Title: javascript switch break unreachable code detected


问:
mysql - selecting limited rows of duplicate columns

What I have

So I'm running this statement:

```<code>SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  i.date,
  COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v
    ON i.id = v.item_to_map_id
GROUP BY
  i.id, i.item_id, i.date, v.item_to_map_id
ORDER BY
  item_id asc, score desc;
</code>```

And I'm getting the following table:

```<code>+----+---------+----------------+---------------------+-------+
| id | item_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |       1 |              1 | 2017-07-05 09:38:23 |     3 |
|  3 |       1 |              3 | 2017-07-05 09:38:23 |     0 |
|  2 |       1 |              2 | 2017-07-05 09:38:23 |    -1 |
|  4 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  5 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  6 |       2 |           NULL | 2017-07-05 09:38:24 |     0 |
+----+---------+----------------+---------------------+-------+
</code>```

What I'm trying to do is select the first X of the repeated item_ids based on some ordering, for example, score or date.

What I've tried

I looked at this answer https://stackoverflow.com/a/1902167/6554121 and tried a modified version:

```<code>SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  i.date,
  COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v
    ON i.id = v.item_to_map_id
WHERE
     (
          SELECT
               COUNT(*)
          FROM
               item_to_map i2
          WHERE
               i2.item_id = i.item_id
     ) < 3
GROUP BY
 i.id, i.item_id, i.date, v.item_to_map_id
ORDER BY item_id asc, score desc;
</code>```

However this returns me no results

What I expected

If ordered by score:

```<code>+----+---------+----------------+---------------------+-------+
| id | item_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |       1 |              1 | 2017-07-05 09:38:23 |     3 |
|  3 |       1 |              3 | 2017-07-05 09:38:23 |     0 |
|  4 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  5 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
+----+---------+----------------+---------------------+-------+
</code>```

答:
You can achieve this using session variables which simulate row number functionality:

```<code>SET @row_number = 0;
SET @item_id = 1;

SELECT t.id, t.item_id, t.item_to_map_id, t.date, t.score
FROM
(
    SELECT
        @row_number:=CASE WHEN @item_id = t.item_id
                          THEN @row_number + 1 ELSE 1 END AS rn,
        @item_id:=t.item_id AS item_id,
        t.id, t.item_to_map_id, t.date, t.score
    FROM
    (
        SELECT
            i.id,
            i.item_id,
            v.item_to_map_id,
            i.date,
            COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
        FROM item_to_map i
        LEFT JOIN vote_item v
            ON i.id = v.item_to_map_id
        GROUP BY
            i.id, i.item_id, i.date, v.item_to_map_id
    ) t
    ORDER BY
        t.item_id, t.score DESC
) t
WHERE t.rn <= 2    -- this restricts to the first two rows per item_id group
                   -- as ordered by the logic in your ORDER BY clause
</code>```

As far as I know, there is no nice way to get the first X records of a group in MySQL, unless your schema coincidentally happens to have row numbers already for each group.  Using session variables as above is one way to handle this, and the performance might even be good as well.

Demo here:

Rextester

Body:
What I have

So I'm running this statement:

SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  i.date,
  COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v
    ON i.id = v.item_to_map_id
GROUP BY
  i.id, i.item_id, i.date, v.item_to_map_id
ORDER BY
  item_id asc, score desc;

And I'm getting the following table:

+----+---------+----------------+---------------------+-------+
| id | item_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |       1 |              1 | 2017-07-05 09:38:23 |     3 |
|  3 |       1 |              3 | 2017-07-05 09:38:23 |     0 |
|  2 |       1 |              2 | 2017-07-05 09:38:23 |    -1 |
|  4 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  5 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  6 |       2 |           NULL | 2017-07-05 09:38:24 |     0 |
+----+---------+----------------+---------------------+-------+

What I'm trying to do is select the first X of the repeated item_ids based on some ordering, for example, score or date.

What I've tried

I looked at this answer https://stackoverflow.com/a/1902167/6554121 and tried a modified version:

SELECT
  i.id,
  i.item_id,
  v.item_to_map_id,
  i.date,
  COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
FROM item_to_map i
LEFT JOIN
  vote_item v
    ON i.id = v.item_to_map_id
WHERE
     (
          SELECT
               COUNT(*)
          FROM
               item_to_map i2
          WHERE
               i2.item_id = i.item_id
     ) < 3
GROUP BY
 i.id, i.item_id, i.date, v.item_to_map_id
ORDER BY item_id asc, score desc;

However this returns me no results

What I expected

If ordered by score:

+----+---------+----------------+---------------------+-------+
| id | item_id | item_to_map_id | date                | score |
+----+---------+----------------+---------------------+-------+
|  1 |       1 |              1 | 2017-07-05 09:38:23 |     3 |
|  3 |       1 |              3 | 2017-07-05 09:38:23 |     0 |
|  4 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
|  5 |       2 |           NULL | 2017-07-05 09:38:23 |     0 |
+----+---------+----------------+---------------------+-------+

Body:
You can achieve this using session variables which simulate row number functionality:

SET @row_number = 0;
SET @item_id = 1;

SELECT t.id, t.item_id, t.item_to_map_id, t.date, t.score
FROM
(
    SELECT
        @row_number:=CASE WHEN @item_id = t.item_id
                          THEN @row_number + 1 ELSE 1 END AS rn,
        @item_id:=t.item_id AS item_id,
        t.id, t.item_to_map_id, t.date, t.score
    FROM
    (
        SELECT
            i.id,
            i.item_id,
            v.item_to_map_id,
            i.date,
            COALESCE( SUM(CAST(CAST(v.score AS char) AS SIGNED)), 0 ) AS score
        FROM item_to_map i
        LEFT JOIN vote_item v
            ON i.id = v.item_to_map_id
        GROUP BY
            i.id, i.item_id, i.date, v.item_to_map_id
    ) t
    ORDER BY
        t.item_id, t.score DESC
) t
WHERE t.rn <= 2    -- this restricts to the first two rows per item_id group
                   -- as ordered by the logic in your ORDER BY clause

As far as I know, there is no nice way to get the first X records of a group in MySQL, unless your schema coincidentally happens to have row numbers already for each group.  Using session variables as above is one way to handle this, and the performance might even be good as well.

Demo here:

Rextester


问:
Best way to represent constraints on values in Scala?
What is the best way to express that, say, an Int field or parameter should never be negative?

The first thing that comes to mind is an annotation on the type, like case class Foo(x: Int @NotNegative). But I'd have to invent my own annotation, and there wouldn't be any sort of compile-time checking or anything.

Is there a better way?

答: Slightly better (?), perhaps, but still no compiler check: require(x >= 0).


问:
Is there any conventional way to be notified of STL move and copy constructors?
I was wondering if there was a simple way to be notified of when STL containers themselves are copied or moved (without having to deal with the complexity of modifying or attempting to overload STL methods - as I imagine that to be cumbersome).

I use simple std::cout outputs to notify of moves and copies when I'm debugging single threaded applications (making sure my own reference types do what I intended).

I've been thinking about it for a while and I've only produced really, really, idiotic ideas (like overloading std::move to produce actual code so that it notifies of all attempts to create candidates for moving - lol). Or could you perhaps overload the real STL move and copy constructors and then make them invoke the real ones?

I'm thinking this could be useful for knowing where exactly copy elision is taking place, where things are actually being moved (and not decaying to a copy operation if the type is const).

Any insight would be interesting and appreciated.

答:
There is no good way to do this.  HeroicKatora's comment is the only possibility I'm aware of:  build a custom allocator that prints out messages when it is copy constructed and move constructed.  But there are issues...

To build a custom allocator, please feel free to use my allocator boilerplate (no copyright, reference, or link needed).  This is just a skeleton allocator to help you get started.  It contains nothing special.

I've used this to create the following straw man allocator for this question:

```<code>template <class T>
class allocator
{
public:
    using value_type    = T;

    allocator() = default;
    allocator(allocator const&) = default;
    allocator(allocator&&)
    {
        std::cout << "container move construction\n";
    }

    template <class U> allocator(allocator<U> const&) noexcept {}

    value_type*  // Use pointer if pointer is not a value_type*
    allocate(std::size_t n)
    {
        return static_cast<value_type*>(::operator new (n*sizeof(value_type)));
    }

    void
    deallocate(value_type* p, std::size_t) noexcept  // Use pointer if pointer is not a value_type*
    {
        ::operator delete(p);
    }

    allocator
    select_on_container_copy_construction() const
    {
        std::cout << "container copy construction\n";
        return *this;
    }
};

template <class T, class U>
bool
operator==(allocator<T> const&, allocator<U> const&) noexcept
{
    return true;
}

template <class T, class U>
bool
operator!=(allocator<T> const& x, allocator<U> const& y) noexcept
{
    return !(x == y);
}
</code>```

When a container copy constructs, it is required to call std::allocator_traits<your_allocator>::select_on_container_copy_construction() to obtain the allocator for the copy constructed container.  If you don't implement this function in your allocator, std::allocator_traits just returns a copy of your allocator.  I've overridden this default behavior to output a message as well.

When a container move constructs, it is required to move construct the allocator.  So I've modified the allocator move constructor to print out a message.

The problem with this approach is that there is no requirement that the container move or copy your allocator only once!

Using vector as an example container, gcc provides the ideal results for this driver:

```<code>template <class T> using vector = std::vector<T, allocator<T>>;
template <class T> using deque = std::deque<T, allocator<T>>;

int
main()
{
    vector<int> v;
    std::cout << "Begin move\n";
    auto v2 = std::move(v);
    std::cout << "End move\n";
    std::cout << "Begin copy\n";
    auto v3 = v2;
    std::cout << "End copy\n";
}
</code>```

gcc outputs:

```<code>Begin move
container move construction
End move
Begin copy
container copy construction
End copy
</code>```

Visual Studio adds a gratuitous move construction to the copy:

```<code>Begin move
container move construction
End move
Begin copy
container copy construction
container move construction
End copy
</code>```

And LLVM's libc++ doubles down on the move constructions:

```<code>Begin move
container move construction
container move construction
End move
Begin copy
container copy construction
container move construction
container move construction
End copy
</code>```

In summary, an unsatisfactory "sort of". :-\

Body:
There is no good way to do this.  HeroicKatora's comment is the only possibility I'm aware of:  build a custom allocator that prints out messages when it is copy constructed and move constructed.  But there are issues...

To build a custom allocator, please feel free to use my allocator boilerplate (no copyright, reference, or link needed).  This is just a skeleton allocator to help you get started.  It contains nothing special.

I've used this to create the following straw man allocator for this question:

template <class T>
class allocator
{
public:
    using value_type    = T;

    allocator() = default;
    allocator(allocator const&) = default;
    allocator(allocator&&)
    {
        std::cout << "container move construction\n";
    }

    template <class U> allocator(allocator<U> const&) noexcept {}

    value_type*  // Use pointer if pointer is not a value_type*
    allocate(std::size_t n)
    {
        return static_cast<value_type*>(::operator new (n*sizeof(value_type)));
    }

    void
    deallocate(value_type* p, std::size_t) noexcept  // Use pointer if pointer is not a value_type*
    {
        ::operator delete(p);
    }

    allocator
    select_on_container_copy_construction() const
    {
        std::cout << "container copy construction\n";
        return *this;
    }
};

template <class T, class U>
bool
operator==(allocator<T> const&, allocator<U> const&) noexcept
{
    return true;
}

template <class T, class U>
bool
operator!=(allocator<T> const& x, allocator<U> const& y) noexcept
{
    return !(x == y);
}

When a container copy constructs, it is required to call std::allocator_traits<your_allocator>::select_on_container_copy_construction() to obtain the allocator for the copy constructed container.  If you don't implement this function in your allocator, std::allocator_traits just returns a copy of your allocator.  I've overridden this default behavior to output a message as well.

When a container move constructs, it is required to move construct the allocator.  So I've modified the allocator move constructor to print out a message.

The problem with this approach is that there is no requirement that the container move or copy your allocator only once!

Using vector as an example container, gcc provides the ideal results for this driver:

template <class T> using vector = std::vector<T, allocator<T>>;
template <class T> using deque = std::deque<T, allocator<T>>;

int
main()
{
    vector<int> v;
    std::cout << "Begin move\n";
    auto v2 = std::move(v);
    std::cout << "End move\n";
    std::cout << "Begin copy\n";
    auto v3 = v2;
    std::cout << "End copy\n";
}

gcc outputs:

Begin move
container move construction
End move
Begin copy
container copy construction
End copy

Visual Studio adds a gratuitous move construction to the copy:

Begin move
container move construction
End move
Begin copy
container copy construction
container move construction
End copy

And LLVM's libc++ doubles down on the move constructions:

Begin move
container move construction
container move construction
End move
Begin copy
container copy construction
container move construction
container move construction
End copy

In summary, an unsatisfactory "sort of". :-\


问:
WPF Application should start on the Left or Right side on any PC/Laptop
I want to open my c# application on any PC at the left corner of the screen always (Left or right side of the screen). For this what should I do? I did in this way;

```<code><Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
    </StackPanel>
</Window>
</code>```

I can set the Height and Width parameters but the PCs screens are different. I want that on any PC the application should open with full height (Equal to the PC/Laptop screen) with width of 400.
I want to make application start on the right side of the laptop/PC screen (On each laptop/PC), Application's right side should be attached with the right side of the laptop screen.

答:
You need to add this code of your wpf app code behind.

```<code> private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
    var workingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = 0;
    this.Top = workingArea.Bottom - this.Height;
}
</code>```

Add xaml code. You have to change this property " Width="400" "

```<code><Window x:Class="BPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BPF"
   Title="MainWindow" Height="350" Width="400">
<StackPanel>
    <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
</StackPanel>
</code>```

if you want to set right

```<code> private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
    var workingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = workingArea.Right - this.Width;
    this.Top = workingArea.Bottom - this.Height;
}
</code>```

I fixed this code and add code for set right.

Body:
I want to open my c# application on any PC at the left corner of the screen always (Left or right side of the screen). For this what should I do? I did in this way;

<Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
    </StackPanel>
</Window>

I can set the Height and Width parameters but the PCs screens are different. I want that on any PC the application should open with full height (Equal to the PC/Laptop screen) with width of 400.
I want to make application start on the right side of the laptop/PC screen (On each laptop/PC), Application's right side should be attached with the right side of the laptop screen.

Body:
You need to add this code of your wpf app code behind.

 private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
    var workingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = 0;
    this.Top = workingArea.Bottom - this.Height;
}

Add xaml code. You have to change this property " Width="400" "

<Window x:Class="BPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:BPF"
   Title="MainWindow" Height="350" Width="400">
<StackPanel>
    <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
    <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
</StackPanel>

if you want to set right

 private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
    var workingArea = System.Windows.SystemParameters.WorkArea;
    this.Left = workingArea.Right - this.Width;
    this.Top = workingArea.Bottom - this.Height;
}

I fixed this code and add code for set right.


问:
How to return HTTP 500 from ASP.NET Core RC2 Web Api?
Back in RC1, I would do this:

```<code>[HttpPost]
public IActionResult Post([FromBody]string something)
{
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}
</code>```

In RC2, there no longer is HttpStatusCodeResult, and there is nothing I can find that lets me return a 500 type of IActionResult.

Is the approach now entirely different for what I'm asking? Do we no longer try-catch in Controller code? Do we just let the framework throw a generic 500 exception back to the API caller? For development, how can I see the exact exception stack?

答:
```<code>return StatusCode((int)HttpStatusCode.InternalServerError, e);
</code>```

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

Body:
Back in RC1, I would do this:

[HttpPost]
public IActionResult Post([FromBody]string something)
{
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}

In RC2, there no longer is HttpStatusCodeResult, and there is nothing I can find that lets me return a 500 type of IActionResult.

Is the approach now entirely different for what I'm asking? Do we no longer try-catch in Controller code? Do we just let the framework throw a generic 500 exception back to the API caller? For development, how can I see the exact exception stack?

Body:
return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.


问:
how can access the age field of parent's parent in class C?
I teach some students.

How I can access A class's attribute age?

```<code>class A {
    protected int age;
    public A(int age){
        this.age = age+2;
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }
}
class C extends B{
    protected int age;
    public C(int age){
        super(age);
        this.age = age;
    }
    public void showInfo(){
//      System.out.println(A.this.age);
        System.out.println(super.age);
        System.out.println(this.age);
    }
}
</code>```

答:
It violates principles of object oriented design and is not possible in Java. There are some ugly workarounds, but if you're teaching students then it may be best to not even introduce this idea, or at least explain why it doesn't make sense.

This question is almost a duplicate if you really need a way of doing this: Why is super.super.method(); not allowed in Java?

Body:
I teach some students.

How I can access A class's attribute age?

class A {
    protected int age;
    public A(int age){
        this.age = age+2;
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }
}
class C extends B{
    protected int age;
    public C(int age){
        super(age);
        this.age = age;
    }
    public void showInfo(){
//      System.out.println(A.this.age);
        System.out.println(super.age);
        System.out.println(this.age);
    }
}