问:
Why is name mangling used with the WinMain() function?
Based on my understanding, name mangling is used when there is function overloading, so that the functions with the same name can be distinguished.

But I have noticed that name mangling is also used with the WinMain() function (which is not overloaded). After name mangling it becomes _WinMain@16.

So why is name mangling used with the WinMain() function?

This is the code that I used:

```<code>#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{

    return 0;
}
</code>```

答:
This is not what's commonly called name mangling. Name mangling is for C++ to create distinguished symbol names from functions of the same name (and is unfortunately implementation defined). Here you have a simple "decorated name" by the conventions of win32 ABI. Windows uses them to distiguish different calling conventions available on that platform.

In this case, the single @ denotes the stdcall calling convention and the number following is the number of bytes in the argument list. The WINAPI macro expands to some compiler-specific attribute that selects stdcall as the calling convention.

Different ABIs use different name decorations. E.g. on Linux, your standard calling convention is cdecl and it doesn't use any decoration at all. But you could have decorations containing a symbol version (coincidentally after an @ sign)

Body:
Based on my understanding, name mangling is used when there is function overloading, so that the functions with the same name can be distinguished.

But I have noticed that name mangling is also used with the WinMain() function (which is not overloaded). After name mangling it becomes _WinMain@16.

So why is name mangling used with the WinMain() function?

This is the code that I used:

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{

    return 0;
}


来源: stackexchange

问:
Not able to "findViewById" in Kotlin. Getting error "Type inference failed"
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

```<code>class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}
</code>```

答:
Try something like:

```<code>val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
</code>```

You can use Kotlin Android Extensions too for that. Check the doc here.

With it, you can call recycler_view directly in your code.

Kotlin Android Extensions:

In your app gradle.build add apply plugin: 'kotlin-android-extensions'

In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout.

That's it, you can call recycler_view directly in your code.

How does it work? The first time that you call recycler_view, a call to findViewById is done and cached.

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

Body:
Try something like:

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)

You can use Kotlin Android Extensions too for that. Check the doc here.

With it, you can call recycler_view directly in your code.

Kotlin Android Extensions:

In your app gradle.build add apply plugin: 'kotlin-android-extensions'

In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout.

That's it, you can call recycler_view directly in your code.

How does it work? The first time that you call recycler_view, a call to findViewById is done and cached.


问:
NoReverseMatch pattern not found
Having trouble figuring out why I keep getting the NoReverseMatch.

app/url.py

```<code>from django.conf.urls import url, patterns

from . import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<contact_id>\d+)/detail/$', views.details, name='details'),

)
</code>```

views.py

```<code>from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.views import generic

from django.template import RequestContext, loader

from .models import Person
# Create your views here.

class IndexView(generic.ListView):
    template_name = 'ContactManager/index.html'
    context_object_name = 'contact_list'

    def get_queryset(self):
        return Person.objects.order_by('lname')

def details(request, contact_id):
    contact = get_object_or_404(Person, id=contact_id)
    return render(request, 'ContactManager/details.html', {'contact': contact})

# class DetailView(generic.ListView):
#     model = Person
#     context_object_name = 'contact'
#     template_name = 'ContactManager/details.html'
#
#     def get_queryset(self):
#
</code>```

template index.html

```<code>{% if contact_list %}
    <ul>
        {% for contact in contact_list %}
            <li>
               <a href="{% url 'contact:details' contact_id=contact.id %}"> {{ contact.fname }}   {{ contact.lname }}</a>
            </li>
        {% endfor %}
    </ul>
{% else %}
    <p>You don't have any contacts currently.</p>
{% endif %}
</code>```

The error I am getting:

```<code>Reverse for 'details' with arguments '()' and keyword arguments '{'contact_id': 1}' not found. 1 pattern(s) tried: ['$(?P<contact_id>\\d+)/detail/$']
</code>```

I have tried using generic views and a host of arguments in the {% url ... %}
Any help would be much appreciated.

答:
Note that this error can also arise if you do not define name in your urlpatterns.

Doing something like

```<code>urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^error_containing_view/$', views.error_containing_view, name='error_containing_view'),
]
</code>```

in your app's urls.py would fix the error.

Title: NoReverseMatch pattern not found

Body:
Having trouble figuring out why I keep getting the NoReverseMatch.

app/url.py

from django.conf.urls import url, patterns

from . import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<contact_id>\d+)/detail/$', views.details, name='details'),

)

views.py

from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.views import generic

from django.template import RequestContext, loader

from .models import Person
# Create your views here.

class IndexView(generic.ListView):
    template_name = 'ContactManager/index.html'
    context_object_name = 'contact_list'

    def get_queryset(self):
        return Person.objects.order_by('lname')

def details(request, contact_id):
    contact = get_object_or_404(Person, id=contact_id)
    return render(request, 'ContactManager/details.html', {'contact': contact})

# class DetailView(generic.ListView):
#     model = Person
#     context_object_name = 'contact'
#     template_name = 'ContactManager/details.html'
#
#     def get_queryset(self):
#

template index.html

{% if contact_list %}

        {% for contact in contact_list %}

                {{ contact.fname }}   {{ contact.lname }}

        {% endfor %}

{% else %}

You don't have any contacts currently.

{% endif %}

The error I am getting:

Reverse for 'details' with arguments '()' and keyword arguments '{'contact_id': 1}' not found. 1 pattern(s) tried: ['$(?P<contact_id>\\d+)/detail/$']

I have tried using generic views and a host of arguments in the {% url ... %}
Any help would be much appreciated.

Body:
Note that this error can also arise if you do not define name in your urlpatterns.

Doing something like

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^error_containing_view/$', views.error_containing_view, name='error_containing_view'),
]

in your app's urls.py would fix the error.


答:
Solution:

```<code> library('data.table')
 Max900.930am <- apply.daily(XTS1, function(x) max(x['T09:00:00/T09:15:00']))
 y <- merge(XTS1, Max900.930am, fill = na.locf)
 y$Max900.930am <- shift(y$Max900.930am, n=53, type=c("lead"))
</code>```

Thanks to @jbaums for this.

Title: Get highest value in time range every day (xts)

Body:
XTS object XTS1 has about three days of data in 15 minute intervals. I want to find the maximum values registered every day between 900am and 930am, and then record such values on a vector. As shown in the example.

I would then do the same for the minimum. The objective is to record the daily opening range for a financial instrument (daily opening range = daily max & min during a time range). To keep it simple I'm ignoring the minimum on this example.

The question is very similar if not a duplicate of this one. Yet the solution provided there is for finding weekly maximums in a database with daily frequency, whereas this one is for finding hourly maximums in a database with intraday frequency. More importantly, the solution provided there does not work for this case (see below).

library('xts')
XTS1 <- structure(c(0.2284, 0.2283, 0.2284, 0.2288, 0.2307, 0.2319, 0.2322, 0.2327, 0.2328, 0.2327, 0.2327, 0.2327, 0.2331, 0.2338, 0.2338, 0.2346, 0.2348, 0.2348, 0.236, 0.2361, 0.2362, 0.236, 0.2365, 0.2364, 0.2363, 0.236, 0.2359, 0.2364, 0.2365, 0.2363, 0.2363, 0.2362, 0.2363, 0.2364, 0.2365, 0.2365, 0.2364, 0.2364, 0.2363, 0.2363, 0.2364, 0.2363, 0.2363, 0.2363, 0.2364, 0.2364, 0.2364, 0.2364, 0.2365, 0.2365, 0.2365, 0.2365, 0.2365, 0.2366, 0.2366, 0.2365, 0.2365, 0.2364, 0.2364, 0.2364, 0.2364, 0.2363, 0.2365, 0.2365, 0.2366, 0.2365, 0.2365, 0.2364, 0.2364, 0.2368, 0.2373,
                    0.2378, 0.2379, 0.2382, 0.2383, 0.2384, 0.2384, 0.2384, 0.2383, 0.2385, 0.2385, 0.2387, 0.2385, 0.2385, 0.2385, 0.2386, 0.2387, 0.2387, 0.24, 0.2394, 0.2396, 0.2394, 0.2398, 0.2394, 0.2396, 0.24, 0.24, 0.2401, 0.2397, 0.2399, 0.2492, 0.2398, 0.2203, 0.2104, 0.2104, 0.2404, 0.2398, 0.24, 0.2401, 0.2402, 0.2399, 0.24, 0.24, 0.2403, 0.2406, 0.2401, 0.2404, 0.2406, 0.2406, 0.2405, 0.241, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.241, 0.2405, 0.2406, 0.2405, 0.2404, 0.2404, 0.2406, 0.2408, 0.2406, 0.2406, 0.2407, 0.2407, 0.2407, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2411, 0.241, 0.241, 0.2411, 0.2411, 0.2412, 0.2412, 0.2411, 0.2411, 0.2411, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2411, 0.2412, 0.2412, 0.2412, 0.2413, 0.2412, 0.2411, 0.2411, 0.241, 0.241, 0.2411, 0.2409, 0.2417, 0.2422, 0.2421, 0.2428, 0.2426, 0.2428, 0.2421, 0.2421, 0.2419, 0.2422, 0.2424, 0.2427, 0.2437, 0.2438, 0.2441, 0.2442), .Dim = c(199L, 1L), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000, 1413990900, 1413991800, 1413992700, 1413993600, 1413994500, 1413995400, 1413996300, 1413997200, 1413998100, 1413999000, 1413999900, 1414000800, 1414001700, 1414002600, 1414003500, 1414004400, 1414005300, 1414006200, 1414007100, 1414008000, 1414009800, 1414010700, 1414011600, 1414015200, 1414016100, 1414017000, 1414017900, 1414018800, 1414019700, 1414020600, 1414021500, 1414022400, 1414023300, 1414024200, 1414025100, 1414026000, 1414026900, 1414027800, 1414028700, 1414029600, 1414030500, 1414031400, 1414032300, 1414033200, 1414034100, 1414035000, 1414035900, 1414036800, 1414037700, 1414038600, 1414039500, 1414040400, 1414041300, 1414042200, 1414043100, 1414044000, 1414044900, 1414045800, 1414046700, 1414047600, 1414048500, 1414049400, 1414050300, 1414051200, 1414052100, 1414053000, 1414053900, 1414054800, 1414055700, 1414056600, 1414057500, 1414058400, 1414059300, 1414060200, 1414061100, 1414062000, 1414062900, 1414063800, 1414064700, 1414065600, 1414066500, 1414067400, 1414068300, 1414069200, 1414070100, 1414071000, 1414071900, 1414072800, 1414073700, 1414074600, 1414075500, 1414076400, 1414077300, 1414078200, 1414079100, 1414080000, 1414080900, 1414081800, 1414082700, 1414083600, 1414084500, 1414085400, 1414086300, 1414087200, 1414088100, 1414089000, 1414089900, 1414090800, 1414091700, 1414092600, 1414093500, 1414094400, 1414096200, 1414097100, 1414098000, 1414101600, 1414102500, 1414103400, 1414104300, 1414105200, 1414106100, 1414107000, 1414107900, 1414108800, 1414109700, 1414110600, 1414111500, 1414112400, 1414113300, 1414114200, 1414115100, 1414116000, 1414116900, 1414117800, 1414118700, 1414119600, 1414120500, 1414121400, 1414122300, 1414123200, 1414124100, 1414125000, 1414125900, 1414126800, 1414127700, 1414128600, 1414129500, 1414130400, 1414131300, 1414132200, 1414133100, 1414134000, 1414134900, 1414135800, 1414136700, 1414137600, 1414138500, 1414139400, 1414140300, 1414141200, 1414142100, 1414143000, 1414143900, 1414144800, 1414145700, 1414146600, 1414147500, 1414148400, 1414149300, 1414150200, 1414151100, 1414152000, 1414152900, 1414153800, 1414154700, 1414155600, 1414156500, 1414157400, 1414158300, 1414159200, 1414160100, 1414161000, 1414161900, 1414162800, 1414163700, 1414164600, 1414165500, 1414166400, 1414167300), tzone = "", tclass = c("POSIXct", "POSIXt")))

#DESIRED OUTPUT
                      [,1]  Max900.930am
2014-10-22 08:45:00 0.2284            NA
2014-10-22 09:00:00 0.2283        0.2283
2014-10-22 09:15:00 0.2284        0.2284
2014-10-22 09:30:00 0.2288        0.2288
2014-10-22 09:45:00 0.2307        0.2288
2014-10-22 10:00:00 0.2319        0.2288
.....

#This records max on desired time range, but in whole database rather than for every day
max(XTS1['T09:00:00/T09:30:00'])

#This says "Error: width > 0 is not TRUE"
xxx = rollapply(data = XTS1, width = XTS1['T09:00:00/T09:30:00'], FUN = max)

#This is derived from solution by @JoshuaUlrich to the other question
#Doesn't work: records max on desired time range, in whole database rather than every day
 Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], function(x) max(XTS1))
 y <- merge(XTS1, Max900.930am, fill = na.locf)

#Printout of Max900.930am, showing the problem
                      [,1]
2014-10-22 09:30:00 0.2492
2014-10-23 09:30:00 0.2492
2014-10-24 09:30:00 0.2492

Body:
Solution:

 library('data.table')
 Max900.930am <- apply.daily(XTS1, function(x) max(x['T09:00:00/T09:15:00']))
 y <- merge(XTS1, Max900.930am, fill = na.locf)
 y$Max900.930am <- shift(y$Max900.930am, n=53, type=c("lead"))

Thanks to @jbaums for this.


问:
Copy UI element with adorner
I am working on taking screenshot of UI Element (WPF) in various size and i'm able to achieve this using "RenderTargetBitmap. But the UIElement which has an Adorner part is not coming while take copy. What should i do to achieve this. Any reference or code snippet?

答:
In my case all I needed was call the AdornerLayer class like so:

```<code>    public void GetScreenshotWithAdorner(Canvas canvas, string filename)
    {
      AdornerLayer adornerlayer = AdornerLayer.GetAdornerLayer(canvas);

      RenderTargetBitmap rtb = new RenderTargetBitmap(
        (int)canvas.ActualWidth,
        (int)canvas.ActualHeight,
        96, //dip X
        96, //dpi Y
        PixelFormats.Pbgra32);
      rtb.Render(canvas); //renders the canvas screen first...
      rtb.Render(adornerlayer); //... then it renders the adorner layer

      SaveRTBAsPNG(rtb, filename);
    }

    private void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
    {
      PngBitmapEncoder pngImage = new PngBitmapEncoder();

      pngImage.Frames.Add(BitmapFrame.Create(bmp));
      using (var filestream = System.IO.File.Create(filename))
      {
        pngImage.Save(filestream);
      }
    }
</code>```

This works if you want to include ALL adorners in your canvas.

Title: Copy UI element with adorner

Body:
In my case all I needed was call the AdornerLayer class like so:

    public void GetScreenshotWithAdorner(Canvas canvas, string filename)
    {
      AdornerLayer adornerlayer = AdornerLayer.GetAdornerLayer(canvas);

      RenderTargetBitmap rtb = new RenderTargetBitmap(
        (int)canvas.ActualWidth,
        (int)canvas.ActualHeight,
        96, //dip X
        96, //dpi Y
        PixelFormats.Pbgra32);
      rtb.Render(canvas); //renders the canvas screen first...
      rtb.Render(adornerlayer); //... then it renders the adorner layer

      SaveRTBAsPNG(rtb, filename);
    }

    private void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
    {
      PngBitmapEncoder pngImage = new PngBitmapEncoder();

      pngImage.Frames.Add(BitmapFrame.Create(bmp));
      using (var filestream = System.IO.File.Create(filename))
      {
        pngImage.Save(filestream);
      }
    }

This works if you want to include ALL adorners in your canvas.


问:
How can I convert bash script output to json
How can I convert the following script output to json.  i'm trying to use it with Zabbix and it advises that the output must be in json.

```<code>/usr/bin/find /home/user/*/current/config -name "sidekiq.yml"|awk -F"/" '{ print " { \"{#DIRNAME}\":\""$4"\"}'
</code>```

Thanks

答: Problem was solved using the zabbix lld documentation.  Thanks to everyone that helped....</p>

Body:
How can I convert the following script output to json.  i'm trying to use it with Zabbix and it advises that the output must be in json.

/usr/bin/find /home/user/*/current/config -name "sidekiq.yml"|awk -F"/" '{ print " { \"{#DIRNAME}\":\""$4"\"}'

Thanks


问:
Single file volume mounted as directory in Docker
Docker documentation says that it's possible to mount a single file into a Docker container:

The -v flag can also be used to mount a single file - instead of just directories - from the host machine.

$ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash

This will drop you into a bash shell in a new container, you will have your bash history from the host and when you exit the container, the host will have the history of the commands typed while in the container.

When I try that however the file mounts as a directory:

```<code>tom@u ~/project $ docker run --rm -it -v file.json:/file.json test
total 80K
drwxr-xr-x  9 root root 4.0K Dec  7 12:58 .
drwxr-xr-x 63 root root 4.0K Dec  7 12:58 ..
drwxr-xr-x  2 root root 4.0K Dec  4 16:10 file.json
</code>```

My Dockerfile looks like this:

```<code>FROM ubuntu:14.04
MAINTAINER Tom
CMD ["ls", "-lah", "/test"]
</code>```

Docker version is 1.9.1, build a34a1d5.

Is this a documentation issue, a misunderstanding on my side, or is there something else going on?

答:
Maybe that's clear in the answers above... but it took me some time to figure it out in my case.

The underlying reason causing the file being shared with -v to appear as a directory instead of a file is that Docker could not find the file on the host.  So Docker creates a new directory in the container with the name being the name of the non existing file on the host as docker thinks that the user just want to share a volume/directory that will be created in the future.

So in the problem reported above, if you used a relative directory in the -v command and docker does not understand relative directories, that means that the file was not found on the host and so docker created a directory. And the answer above which suggests to use $(pwd) will be the correct solution when the problem is due to a relative directory.

But for those reading this page who are not using a relative directory and are having the same problem... then try to understand why the file is missing on the host.

It could just be a stupid typo...

It could be that you're running the "docker run" command from a client which spawns the docker container on a different host and the file being shared does not exist on that different host. The file being shared with -v must exist on the host where the docker agent will spawn the container... not necessarily on the client where the "docker run -v ..." command is executed (although they will be the same in many cases).

There are other possible explanations above for Mac and Windows... that could be it too.

So the file missing from the host is the problem... troubleshoot the problem in your setup... using $(pwd) could be the solution but not always.

Body:
Docker documentation says that it's possible to mount a single file into a Docker container:

The -v flag can also be used to mount a single file - instead of just directories - from the host machine.

$ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash

This will drop you into a bash shell in a new container, you will have your bash history from the host and when you exit the container, the host will have the history of the commands typed while in the container.

When I try that however the file mounts as a directory:

tom@u ~/project $ docker run --rm -it -v file.json:/file.json test
total 80K
drwxr-xr-x  9 root root 4.0K Dec  7 12:58 .
drwxr-xr-x 63 root root 4.0K Dec  7 12:58 ..
drwxr-xr-x  2 root root 4.0K Dec  4 16:10 file.json

My Dockerfile looks like this:

FROM ubuntu:14.04
MAINTAINER Tom
CMD ["ls", "-lah", "/test"]

Docker version is 1.9.1, build a34a1d5.

Is this a documentation issue, a misunderstanding on my side, or is there something else going on?


问:
how to remove default-jre java installation from Ubuntu?
I had no java (i.e. java -version said java no found or similar)

I installed it like this:

```<code>sudo apt-get install default-jre
</code>```

This results in installing java 1.6 - I need java 1.7

So the next probelem is how to uninstall it.

I tried this:

```<code>sudo apt-get --purge -remove default-jre
</code>```

Which seemed to work, but when I do:

```<code>java -version
</code>```

I still java respond with 1.6 - i.e. id didnt uninstall java.

Ok, so I guess -remove does not remove the thing it installed. Is there a way to o this?

答:
Bary12's answer worked for me:

sudo apt-get autoremove default-jre

Body:
I had no java (i.e. java -version said java no found or similar)

I installed it like this:

sudo apt-get install default-jre

This results in installing java 1.6 - I need java 1.7

So the next probelem is how to uninstall it.

I tried this:

sudo apt-get --purge -remove default-jre

Which seemed to work, but when I do:

java -version

I still java respond with 1.6 - i.e. id didnt uninstall java.

Ok, so I guess -remove does not remove the thing it installed. Is there a way to o this?


问:
Mock Ajax (Reactjs + Mobx)
I want to make some fake my ajax calls so when on localhost I can bring back dummy data from a fake method instead of doing real calls to my server(where the structure might not exist).

What is the best way to do this in reactjs + mobx?

I was thinking of making a fake store as this is where all my actions are with my ajax calls but that would involve always making the entire store with all functions.

I then though of maybe extracting out the ajax calls from the store and then mockup those calls but I am not sure the best way to do that.

答:
Do you know superagent?

It's very interesting http client and has a very cool mocker plugin.

It works fine in a nodejs server or in a webbrowser. I use it in a everyday base. Very easy and well documented.

You can write custom callbacks to handle requests to certain urls or urls patterns.

Title: Mock Ajax (Reactjs + Mobx)


问:
Angular 2 Lifecycle and VMware Clarity UI Grid
I'm making a rest call inside of a component.  I'm rendering the data in a clr-datagrid.  When it is first rendered, the data is skewed and misaligned.  If I sort the data, or do anything on the grid, the data becomes properly aligned.  I'm assuming this is due to the grid not having all of the data in time to calculate the proper column widths.  I'm making the REST call inside of the constructor, though I've also tried moving this into the ngOnInit() function with no improvement.

Where is the recommended location for a REST call in a component?  Once the data is properly returned, is there something I need to call to cause the UI to "refresh" it calculations on widths?

Because this code is making a REST call to an internal server, I am unable to provide a Plunker reproducing it.

Component code:

```<code>export class NodesComponent implements OnInit {

nodes: Node[] = [];
currentNode: Node;

constructor(private dataService: DataService) {
    this.dataService.getNodes().subscribe(nodesAsJson => {
        for (let nodeAsJson of nodesAsJson) {
            let node: Node = new Node(nodeAsJson);
            this.nodes.push(node);
        }
    });
}
</code>```

HTML Code

```<code><h4><clr-icon shape="server" size="24"></clr-icon>Nodes ({{ nodes.length }})</h4>
<clr-datagrid>
    <clr-dg-column [clrDgField] = "'id'">ID</clr-dg-column>
    <clr-dg-column [clrDgField] = "'name'">Name</clr-dg-column>
    <clr-dg-column [clrDgField] = "'type'">Type</clr-dg-column>

    <clr-dg-row *clrDgItems="let node of nodes">
        <clr-dg-cell>{{ node.id }}</clr-dg-cell>
        <clr-dg-cell>{{ node.name }}</clr-dg-cell>
        <clr-dg-cell>{{ node.type }}</clr-dg-cell>
    </clr-dg-row>
    <clr-dg-footer>
        {{pagination1.firstItem + 1}} - {{pagination1.lastItem + 1}} of     {{pagination1.totalItems}} Nodes
        <clr-dg-pagination #pagination1 [clrDgPageSize]="5"></clr-dg-pagination>
</clr-dg-footer>
</code>```

Misaligned Grid after rest call is made

Aligned properly after clicking header sort

答: Check the console for javascript errors. I have found when using the datagrid if the data isnt fully loaded yet, you are probably accessing a property or a function of an object that doesnt exist. This will throw an error which the datagrid seems to halt on causing the skewing. Maybe initialize your data fields with somethings (even if empty) to avoid these errors.</p>

Body:
I'm making a rest call inside of a component.  I'm rendering the data in a clr-datagrid.  When it is first rendered, the data is skewed and misaligned.  If I sort the data, or do anything on the grid, the data becomes properly aligned.  I'm assuming this is due to the grid not having all of the data in time to calculate the proper column widths.  I'm making the REST call inside of the constructor, though I've also tried moving this into the ngOnInit() function with no improvement.

Where is the recommended location for a REST call in a component?  Once the data is properly returned, is there something I need to call to cause the UI to "refresh" it calculations on widths?

Because this code is making a REST call to an internal server, I am unable to provide a Plunker reproducing it.

Component code:

export class NodesComponent implements OnInit {

nodes: Node[] = [];
currentNode: Node;

constructor(private dataService: DataService) {
    this.dataService.getNodes().subscribe(nodesAsJson => {
        for (let nodeAsJson of nodesAsJson) {
            let node: Node = new Node(nodeAsJson);
            this.nodes.push(node);
        }
    });
}

HTML Code

<clr-icon shape="server" size="24"></clr-icon>Nodes ({{ nodes.length }})

<clr-datagrid>
    <clr-dg-column [clrDgField] = "'id'">ID</clr-dg-column>
    <clr-dg-column [clrDgField] = "'name'">Name</clr-dg-column>
    <clr-dg-column [clrDgField] = "'type'">Type</clr-dg-column>

    <clr-dg-row *clrDgItems="let node of nodes">
        <clr-dg-cell>{{ node.id }}</clr-dg-cell>
        <clr-dg-cell>{{ node.name }}</clr-dg-cell>
        <clr-dg-cell>{{ node.type }}</clr-dg-cell>
    </clr-dg-row>
    <clr-dg-footer>
        {{pagination1.firstItem + 1}} - {{pagination1.lastItem + 1}} of     {{pagination1.totalItems}} Nodes
        <clr-dg-pagination #pagination1 [clrDgPageSize]="5"></clr-dg-pagination>
</clr-dg-footer>

Misaligned Grid after rest call is made

Aligned properly after clicking header sort


问:
3 way calculation
I have a data object with three fields, A, B and C. The problem is that the user can set any of them because:

A * B = C

So if a user starts off by setting A & B, C will be calculated.  but then if a user set C, A gets recalculated, so there is an implicit anchoring that is happening based off the last field that the user set.

i want to avoid a solution with a lot of flag member variables.  Any best practices on how i can code this class up without having a lot of stuff  like this below

```<code>public class Object
{
     private double _A;
     private double _B;
     private double _C;

     private bool _enteredA;
     private bool _enteredB;
     private bool _enteredC;

public double A
{
get
    {
     if (_enteredC)
     {
          return _C / _B;
     }
     else
     {
        return _A;
     }
  }
}
</code>```

should the logic of setting A, B, and C always be on the "get" or the "set".

Is there any cleaner way to doing this?

答:
You state that your properties have the relationship "A * B = C".  So, your class should express this.  A and B are independent variables, so they have simple setters and getters that merely get and set a filed.  C is a Dependant variable and so it should only have a getter and perform the calculation based on A and B:

```<code>class Foo
{
    private double m_a;
    public double A
    {
        get { return m_a; }
        set { m_a = value; }
    }

    private double m_b;
    public double B
    {
        get { return m_b; }
        set { m_b = value; }
    }

    public double C
    {
        get { return A * B; }
    }
}
</code>```

An editor can be written that allows A and B to edited trivially.  It can also allow the user to edit C if (and only if) the user has edited A or B already.  The view would store some state to indicate which (if any) field was last edited and can therefore apply the appropriate change to A or B when the conceptual C is edited.

Now, if the View is unaware of the calculation of C, you can add methods to the Foo class to "SetAGivenC()" and "SetBGivenC()":

```<code>class Foo
{
    ... as above ...

    public void SetAGivenC( double newC )
    {
        A = newC/B;
    }

    public void SetBGivenC( double newC )
    {
        B = newC/A;
    }
}
</code>```

Now your GUI just calls one of these methods when "C" is edited.

I am confused as to what "last field that the user set" means.  Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A in the first editor, then B in the second, then C in the first.  What gets adjusted when C is set? A or B?  If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view?  I expect that A would be adjusted in this case and the view tracks the last edited field.  But that's an issue for another day!

Edit:

Jeepers - I even stuffed up my own pathological case!

I'll try that last paragraph again:

I am confused as to what "last field that the user set" means.  Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A then B in the first editor, the user then edits B then A in the second, the user then edits C in the first.  What gets adjusted when C is set? A or B?  If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view?  I expect that A would be adjusted in this case and the view tracks the last edited field.  But that's an issue for another day!

OwnerDisplayName: ak

ContentLicense: CC BY-SA 2.5

Title: 3 way calculation

Body:
I have a data object with three fields, A, B and C. The problem is that the user can set any of them because:

A * B = C

So if a user starts off by setting A & B, C will be calculated.  but then if a user set C, A gets recalculated, so there is an implicit anchoring that is happening based off the last field that the user set.

i want to avoid a solution with a lot of flag member variables.  Any best practices on how i can code this class up without having a lot of stuff  like this below

public class Object
{
     private double _A;
     private double _B;
     private double _C;

     private bool _enteredA;
     private bool _enteredB;
     private bool _enteredC;

public double A
{
get
    {
     if (_enteredC)
     {
          return _C / _B;
     }
     else
     {
        return _A;
     }
  }
}

should the logic of setting A, B, and C always be on the "get" or the "set".

Is there any cleaner way to doing this?

LastEditorDisplayName: ak

Body:
You state that your properties have the relationship "A * B = C".  So, your class should express this.  A and B are independent variables, so they have simple setters and getters that merely get and set a filed.  C is a Dependant variable and so it should only have a getter and perform the calculation based on A and B:

class Foo
{
    private double m_a;
    public double A
    {
        get { return m_a; }
        set { m_a = value; }
    }

    private double m_b;
    public double B
    {
        get { return m_b; }
        set { m_b = value; }
    }

    public double C
    {
        get { return A * B; }
    }
}

An editor can be written that allows A and B to edited trivially.  It can also allow the user to edit C if (and only if) the user has edited A or B already.  The view would store some state to indicate which (if any) field was last edited and can therefore apply the appropriate change to A or B when the conceptual C is edited.

Now, if the View is unaware of the calculation of C, you can add methods to the Foo class to "SetAGivenC()" and "SetBGivenC()":

class Foo
{
    ... as above ...

    public void SetAGivenC( double newC )
    {
        A = newC/B;
    }

    public void SetBGivenC( double newC )
    {
        B = newC/A;
    }
}

Now your GUI just calls one of these methods when "C" is edited.

I am confused as to what "last field that the user set" means.  Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A in the first editor, then B in the second, then C in the first.  What gets adjusted when C is set? A or B?  If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view?  I expect that A would be adjusted in this case and the view tracks the last edited field.  But that's an issue for another day!

Edit:

Jeepers - I even stuffed up my own pathological case!

I'll try that last paragraph again:

I am confused as to what "last field that the user set" means.  Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A then B in the first editor, the user then edits B then A in the second, the user then edits C in the first.  What gets adjusted when C is set? A or B?  If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view?  I expect that A would be adjusted in this case and the view tracks the last edited field.  But that's an issue for another day!

OwnerDisplayName: Daniel Paull

LastEditorDisplayName: Daniel Paull


问:
"multiple definition of..." error for a full specialisation of a template function

 I have a project with configuration:

```<code>./main.cpp
./type_traints/TypeTraints.cpp
./type_traints/TypeTraints.hpp
./type_traints/chapter_20.hpp
</code>```

The ./type_traints/CMakeLists.txt file is:

```<code> cmake_minimum_required (VERSION 2.8)
 add_library(chapter_20 TypeTraints.cpp)
</code>```

and the ./CMakeLists.txt follows:

```<code>cmake_minimum_required (VERSION 2.8)
project (mpl)

add_subdirectory(type_traints)
include_directories(type_traints)
link_directories(type_traints)

add_executable (mpl main.cpp)
target_link_libraries(mpl chapter_20)
</code>```

Relevant parts of files (most includes omitted) include:

./type_traints/chapter_20.hpp

```<code>#ifndef CHAPTER_20_GUARD
#define CHAPTER_20_GUARD
#include <TypeTraints.hpp>

void chapter_20() {
  test_23();
}
#endif //CHAPTER_20_GUARD
</code>```

./type_traints/TypeTraints.hpp

```<code>#ifndef TYPE_TRAINTS_GUARD
#define TYPE_TRAINTS_GUARD
namespace details {

  template<class T> const char* class2name() {
    return "unknown";
  };

  template<> const char* class2name<int>() {
    return "int";
  };
}

template<class T>
class type_descriptor {
  friend std::ostream& operator << (std::ostream& stream,
                                    const type_descriptor<T>& desc) {
    stream << desc.getName();
    return stream;
  }

public:
  std::string getName() const;
};

template<class T>
std::string type_descriptor<T>::getName() const {
  return details::class2name<T>();
}

void test_23();
#endif // TYPE_TRAINTS_GUARD
</code>```

./type_traints/TypeTraints.cpp

```<code>#include<TypeTraints.hpp>

void test_23() {
  cout << type_descriptor<int>() << endl;
}
</code>```

and ./main.cpp

```<code>#include <chapter_20.hpp>

int main(int argc, char* argv[]) {
chapter_20();
  return 0;
}
</code>```

The project compiles but fails to link:

```<code>[ 50%] Building CXX object type_traints/CMakeFiles/chapter_20.dir/TypeTraints.cpp.o
Linking CXX static library libchapter_20.a
[ 50%] Built target chapter_20
[100%] Building CXX object CMakeFiles/mpl.dir/main.cpp.o
Linking CXX executable mpl
type_traints/libchapter_20.a(TypeTraints.cpp.o): In function `char const* details::cl
ass2name<int>()':
/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:312: multiple definition of `c
har const* details::class2name<int>()'
CMakeFiles/mpl.dir/main.cpp.o:/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:
312: first defined here
collect2: ld returned 1 exit status
make[2]: *** [mpl] Błąd 1
make[1]: *** [CMakeFiles/mpl.dir/all] Error 2
make: *** [all] Error 2
23:56:20@marcin-laptop ~/P
</code>```

The project links fine if I remove the class2name specialization (class2name<int>()) from TypeTraints.hpp and use only the generic implementation.

Does anybody have an idea Why is that? Did I miss-configure cmake files?

答:
This is a violation of the one definition rule :

There can be more than one definition
  of a class type (clause 9),
  enumeration type (7.2), inline
  function with external linkage
  (7.1.2), class template (clause 14),
  non-static function template (14.5.5),
  static data member of a class template
  (14.5.1.3), member function of a class
  template (14.5.1.1), or template
  specialization for which some template
  parameters are not specified (14.7,
  14.5.4) in a program provided that each definition appears in a different
  translation unit, and provided the
  definitions satisfy the following
  requirements.

An explicit specialization of the class2name template function does not fall in any of these cases. For this reason, I believe that moving class2name<int>() definition into an implementation file should fix the issue. I also think you should have a look on "Why not specialize function templates ?".

Body:
 I have a project with configuration:

./main.cpp
./type_traints/TypeTraints.cpp
./type_traints/TypeTraints.hpp
./type_traints/chapter_20.hpp

The ./type_traints/CMakeLists.txt file is:

 cmake_minimum_required (VERSION 2.8)
 add_library(chapter_20 TypeTraints.cpp)

and the ./CMakeLists.txt follows:

cmake_minimum_required (VERSION 2.8)
project (mpl)

add_subdirectory(type_traints)
include_directories(type_traints)
link_directories(type_traints)

add_executable (mpl main.cpp)
target_link_libraries(mpl chapter_20)

Relevant parts of files (most includes omitted) include:

./type_traints/chapter_20.hpp

#ifndef CHAPTER_20_GUARD
#define CHAPTER_20_GUARD
#include <TypeTraints.hpp>

void chapter_20() {
  test_23();
}
#endif //CHAPTER_20_GUARD

./type_traints/TypeTraints.hpp

#ifndef TYPE_TRAINTS_GUARD
#define TYPE_TRAINTS_GUARD
namespace details {

  template<class T> const char* class2name() {
    return "unknown";
  };

  template<> const char* class2name<int>() {
    return "int";
  };
}

template<class T>
class type_descriptor {
  friend std::ostream& operator << (std::ostream& stream,
                                    const type_descriptor<T>& desc) {
    stream << desc.getName();
    return stream;
  }

public:
  std::string getName() const;
};

template<class T>
std::string type_descriptor<T>::getName() const {
  return details::class2name<T>();
}

void test_23();
#endif // TYPE_TRAINTS_GUARD

./type_traints/TypeTraints.cpp

#include<TypeTraints.hpp>

void test_23() {
  cout << type_descriptor<int>() << endl;
}

and ./main.cpp

#include <chapter_20.hpp>

int main(int argc, char* argv[]) {
chapter_20();
  return 0;
}

The project compiles but fails to link:

[ 50%] Building CXX object type_traints/CMakeFiles/chapter_20.dir/TypeTraints.cpp.o
Linking CXX static library libchapter_20.a
[ 50%] Built target chapter_20
[100%] Building CXX object CMakeFiles/mpl.dir/main.cpp.o
Linking CXX executable mpl
type_traints/libchapter_20.a(TypeTraints.cpp.o): In function `char const* details::cl
ass2name<int>()':
/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:312: multiple definition of `c
har const* details::class2name<int>()'
CMakeFiles/mpl.dir/main.cpp.o:/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:
312: first defined here
collect2: ld returned 1 exit status
make[2]: *** [mpl] Błąd 1
make[1]: *** [CMakeFiles/mpl.dir/all] Error 2
make: *** [all] Error 2
23:56:20@marcin-laptop ~/P

The project links fine if I remove the class2name specialization (class2name<int>()) from TypeTraints.hpp and use only the generic implementation.

Does anybody have an idea Why is that? Did I miss-configure cmake files?


问:
How to get the last character of a string?
How to get the last character of the string:

```<code>"linto.yahoo.com."
</code>```

The last character of this string is "."

How can I find this?

答:
You can achieve this using different ways but with different performance,

1. Using bracket notation:

var str = "Test";
  var lastLetter = str[str.length - 1];

But it's not recommended to use brackets. Check the reasons here

2. charAt[index]:

var lastLetter = str.charAt(str.length - 1)

This is readable and fastest among others. It is most recommended way.

3. substring:

str.substring(str.length - 1);

4. slice:

str.slice(-1);

It's slightly faster than substring.

You can check the performance here

With ES6:

You can use str.endsWith("t");

But it is not supported in IE. Check more details about endsWith here

ContentLicense: CC BY-SA 4.0

Body:
How to get the last character of the string:

"linto.yahoo.com."

The last character of this string is "."

How can I find this?


答:
```<code>ips = [ip.split()[0] for ip in data if ip[0].isdigit()]
sort = sorted(ips, key= lambda ip: int(ip.split('.')[-1]))
i, l, c = 0, len(sort), 1
pools = {}
while i < l:
    if int(sort[i].split('.')[-1]) == int(sort[i+1]).split('.')[-1])-1:
        pools[c] = (sort[i], sort[i+1])
        i += 2
    else:
        pools[c] = (sort[i],)
        i += 1
    c += 1
</code>```

Title: Pair IP addresses in a list pulled from xlrd

Body:
I have used xlrd to pull data from a column (Data Below). I need to group together the ip addressess. So ip address that appear next together in the output belong to the same pool and single ones are in a pool of their own. For example (10.100.33.183,10.100.33.184) belong to (pool1). (Pool6 =10.100.33.89)

How do I go about achieving this all help welcome.

['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']


问:
How to generate the html report in intern js
We use intern JS for the automation of functional tests, but we can't generate a report html

I used locvhtml https://theintern.github.io/intern/#reporter-lcov but it just gets me an empty html report

答: Intern doesn't currently include a reporter that generates HTML test result reports as files. Its built in HTML reporter is DOM-based and only generates in-browser reports, and while the lcovhtml reporter generates file-based HTML reports, they're for code coverage rather than test results.</p>


问:
fatal error: unexpectedly found nil while unwrapping an Optional value on adding audio Swift
I'm trying to add some audio when a button is pressed and the code I use doesnt have any error until I run then I get the 'fatal error: unexpectedly found nil while unwrapping an Optional value' in the out put this line of code:

```<code>let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
</code>```

This is my entire code just for reference:

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOf: url)

            audioPlayers.append(audioPlayer)
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}
</code>```

}

答:
If the file names are not needed later there is a more reliable way to get all mp3 files in the resources folder

```<code>let audioURLs = Bundle.main.urls(forResourcesWithExtension: "mp3", subdirectory: nil)!
for url in audioURLs {
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayers.append(audioPlayer)
    }
    catch {
        audioPlayers.append(AVAudioPlayer())
    }
}
</code>```

or - inspired by Alexander's comment – shortly

```<code>let audioURLs = Bundle.main.urls(forResourcesWithExtension: "mp3", subdirectory: nil)!
audioPlayers = audioURLs.flatMap{ try? AVAudioPlayer(contentsOf: $0) }
</code>```

Body:
I'm trying to add some audio when a button is pressed and the code I use doesnt have any error until I run then I get the 'fatal error: unexpectedly found nil while unwrapping an Optional value' in the out put this line of code:

let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!

This is my entire code just for reference:

import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOf: url)

            audioPlayers.append(audioPlayer)
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

}

Body:
If the file names are not needed later there is a more reliable way to get all mp3 files in the resources folder

let audioURLs = Bundle.main.urls(forResourcesWithExtension: "mp3", subdirectory: nil)!
for url in audioURLs {
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayers.append(audioPlayer)
    }
    catch {
        audioPlayers.append(AVAudioPlayer())
    }
}

or - inspired by Alexander's comment – shortly

let audioURLs = Bundle.main.urls(forResourcesWithExtension: "mp3", subdirectory: nil)!
audioPlayers = audioURLs.flatMap{ try? AVAudioPlayer(contentsOf: $0) }


问:
Recover current value in checkBox during gridView Editing - WebForm C#
I have a simple checkBox in Editable gridView :

```<code><asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>
</code>```

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

```<code>public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}
</code>```

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

```<code>SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"
</code>```

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy

答: I added the property Checked=<%# BindItem.IsEditable %> on CheckBox Control and it works perfectly.

Body:
I have a simple checkBox in Editable gridView :

<asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy


问:
bash script and command definition
Got a little bash script like so:

```<code>#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

${TIME_CMD} ls
</code>```

Only problem: doesn't work:

```<code>/usr/bin/time: cannot run execution: No such file or directory
Command exited with non-zero status 127
"0:00.00
</code>```

What am I doing wrong?

答:
Storing commands in variables is generally a bad idea (see BashFAQ #050 for details).  The reason it's not working as you expect is that quoting inside variable values is ignored (unless you run it through something like eval, which then tends to lead to other parsing oddities).

In your case, I see three fairly straightforward ways to do it.  First, you can use an alias instead of a variable:

```<code>alias TIME_CMD='/usr/bin/time -f "%E execution time"'
TIME_CMD ls
</code>```

Second, you can use a function:

```<code>TIME_CMD() { /usr/bin/time -f "%E execution time" "$@"; }
TIME_CMD ls
</code>```

Third, you can use an array rather than a simple variable:

```<code>TIME_CMD=(/usr/bin/time -f "%E execution time")
"${TIME_CMD[@]}" ls
</code>```

Note that with an array, you need to expand it with the "${array[@]}" idiom to preserve word breaks properly.

Title: bash script and command definition

Body:
Got a little bash script like so:

#!/bin/bash
TIME_CMD='/usr/bin/time -f "%E execution time"'

${TIME_CMD} ls

Only problem: doesn't work:

/usr/bin/time: cannot run execution: No such file or directory
Command exited with non-zero status 127
"0:00.00

What am I doing wrong?

Body:
Storing commands in variables is generally a bad idea (see BashFAQ #050 for details).  The reason it's not working as you expect is that quoting inside variable values is ignored (unless you run it through something like eval, which then tends to lead to other parsing oddities).

In your case, I see three fairly straightforward ways to do it.  First, you can use an alias instead of a variable:

alias TIME_CMD='/usr/bin/time -f "%E execution time"'
TIME_CMD ls

Second, you can use a function:

TIME_CMD() { /usr/bin/time -f "%E execution time" "$@"; }
TIME_CMD ls

Third, you can use an array rather than a simple variable:

TIME_CMD=(/usr/bin/time -f "%E execution time")
"${TIME_CMD[@]}" ls

Note that with an array, you need to expand it with the "${array[@]}" idiom to preserve word breaks properly.


问:
How to loop through DIV id element to check style None or Block
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tbNewStyleWrapper" style="position: relative;">
  <div id="loadingProgressContainer" style="display: block;">
  <div id="loadingProgressElement">
  <p><h1>Test Please...</h1></p>
   <img src="http://www.dev.tasch.co.za/airportshuttle2/components/com_taxibooking/assets/images/ajax-loader-bar.gif">
  </div>
  </div>
    </div></code>```

答:
```<code>$(function() {
$('div').each(function() {
   /* Check the CSS Display Property. */
   console.log($(this));
   console.log($(this).css('display'));
});
});
</code>```

Body:
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");

Test Please...


问:
Spring MongoTemplate - Mapping aggregation result to collections (e.g. List and Map)
aggregate method of MongoTemplate returns AggregationResults<T>, where T being the class that corresponds to mongo collection.

Sometimes, we only want the single (say property abc) or a couple of properties (pqr and xyz) from that collection depending on particular criteria. In these cases, we can either retrieve the whole collection into T class or create a new class that contains properties (abc) or (pqr, xyz).

Is there a way to map these single property to List<String> or two properties as a key-value pair in HashMap<String, String>?

答:
Use BasicDBObject (backed by LinkedHashMap) / Document (from 2.0.0 spring mongo version) along with java 8 stream methods to parse them into collection types.

Single Property (abc) -  List type

```<code>Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("abc"));
List<String> singleResults = mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getMappedResults().stream().map(item -> item.getString("abc")).collect(Collectors.toList());
</code>```

Multiple properties (pqr, xyz) -  Map type

```<code>Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("pqr, xyz"));
List<Map> multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getMappedResults().stream().map (item -> (LinkedHashMap) item).collect(Collectors.toList());
</code>```

Update ( Reading from server )

Single Property (abc) -  List type

```<code>Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("abc").as("abc"));
List<String> singleResults = (List<String>) mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getUniqueMappedResult().get("abc");
</code>```

Multiple properties (pqr, xyz) - Map type

```<code>Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz"));
Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult();
</code>```

Body:
Use BasicDBObject (backed by LinkedHashMap) / Document (from 2.0.0 spring mongo version) along with java 8 stream methods to parse them into collection types.

Single Property (abc) -  List type

Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("abc"));
List<String> singleResults = mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getMappedResults().stream().map(item -> item.getString("abc")).collect(Collectors.toList());

Multiple properties (pqr, xyz) -  Map type

Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("pqr, xyz"));
List<Map> multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getMappedResults().stream().map (item -> (LinkedHashMap) item).collect(Collectors.toList());

Update ( Reading from server )

Single Property (abc) -  List type

Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("abc").as("abc"));
List<String> singleResults = (List<String>) mongoOperations.aggregate(aggregation, "collectioname", BasicDBObject.class).getUniqueMappedResult().get("abc");

Multiple properties (pqr, xyz) - Map type

Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().push("pqr").as("pqr").push("xyz").as("xyz"));
Map multipleResults = mongoOperations.aggregate(aggregation,"collectioname", BasicDBObject.class).getUniqueMappedResult();


问:
Composer is using a different version of php
So apparently I have 2 versions of Php installed. I have 5.6 and 7.
I use Xampp on Mac and it works on 5.6, I tried downloading composer and it refuses to install cakephp bwith this error

```<code>- cakephp/cakephp 3.4.9 requires ext-intl * -> the requested PHP extension intl is missing from your system.
</code>```

and down at the end of the message it says

```<code>o enable extensions, verify that they are enabled in your .ini files:
- /usr/local/etc/php/7.0/php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
</code>```

so it runs on php 7 that doesn't even work in the first place. I did try to remove the semi-colon from php.ini
nothing worked
thanks

答:
As indicated the cakePHP framework requires the internationalization extension (ext-intl). As a best practice (and to save you time down the line), I recommend spinning up a virtual machine or containers that are the same platform that your server will be (windows,linux,unix,osx). This way you're development env and production environments are the same.

As for how to enable the ext-intl:

http://php.net/manual/en/intl.installation.php

how can i enable PHP Extension intl?

https://daveismyname.blog/install-php-intl-on-mac-using-homebrew

Body:
So apparently I have 2 versions of Php installed. I have 5.6 and 7.
I use Xampp on Mac and it works on 5.6, I tried downloading composer and it refuses to install cakephp bwith this error

- cakephp/cakephp 3.4.9 requires ext-intl * -> the requested PHP extension intl is missing from your system.

and down at the end of the message it says

o enable extensions, verify that they are enabled in your .ini files:
- /usr/local/etc/php/7.0/php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

so it runs on php 7 that doesn't even work in the first place. I did try to remove the semi-colon from php.ini
nothing worked
thanks


问:
Laravel: php artisan serve doesn't start
I've dug through a few of the other answers here and nothing seems to fit the bill. I'm probably going to leave some information out initially so just let me know what else you might need and thanks!

Currently running ubuntu 7, using composer and laravel both of which seem to be installed properly:

When I type 'php artisan serve' and 'php artisan serve --port:8000' into terminal I get this error:

PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 PHP
  Fatal error:  require(): Failed opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

When I attempt to run 'php -S localhost:8000 -t public/' just as an attempt I get the following error upon refresh:

PHP 7.0.18-0ubuntu0.17.04.1 Development Server started at Thu Jul  6
  09:15:36 2017 Listening on http://localhost:8000 Document root is
  /home/user/Projects/thingy/public Press Ctrl-C to quit. [Thu Jul  6
  09:15:40 2017] PHP Warning:
  require(/home/user/Projects/thingy/bootstrap/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] PHP Fatal error:  require(): Failed opening
  required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17 [Thu
  Jul  6 09:15:40 2017] 127.0.0.1:57214 [500]: / - require(): Failed
  opening required
  '/home/user/Projects/thingy/bootstrap/../vendor/autoload.php'
  (include_path='.:/usr/share/php') in
  /home/user/Projects/thingy/bootstrap/autoload.php on line 17

I checked to see if maybe a server was already running using the 'ps -ef | grep php' command in terminal and I don't see any servers running at all.

I have run 'composer install' and I get the following error:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Loading composer
  repositories with package information Installing dependencies
  (including require-dev) from lock file Your requirements could not be
  resolved to an installable set of packages.

Problem 1
      - Installation request for laravel/framework v5.4.28 -> satisfiable by laravel/framework[v5.4.28].
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.

  Problem 2
      - Installation request for phpunit/php-code-coverage 4.0.8 -> satisfiable by phpunit/php-code-coverage[4.0.8].
      - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 3
      - Installation request for phpunit/phpunit 5.7.21 -> satisfiable by phpunit/phpunit[5.7.21].
      - phpunit/phpunit 5.7.21 requires ext-dom * -> the requested PHP extension dom is missing from your system.   Problem 4
      - laravel/framework v5.4.28 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
      - laravel/tinker v1.0.1 requires illuminate/console ~5.1 -> satisfiable by laravel/framework[v5.4.28].
      - Installation request for laravel/tinker v1.0.1 -> satisfiable by laravel/tinker[v1.0.1].

To enable extensions, verify that they are enabled in your .ini
  files:
      - /etc/php/7.0/cli/php.ini
      - /etc/php/7.0/cli/conf.d/10-opcache.ini
      - /etc/php/7.0/cli/conf.d/10-pdo.ini
      - /etc/php/7.0/cli/conf.d/20-calendar.ini
      - /etc/php/7.0/cli/conf.d/20-ctype.ini
      - /etc/php/7.0/cli/conf.d/20-exif.ini
      - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
      - /etc/php/7.0/cli/conf.d/20-ftp.ini
      - /etc/php/7.0/cli/conf.d/20-gettext.ini
      - /etc/php/7.0/cli/conf.d/20-iconv.ini
      - /etc/php/7.0/cli/conf.d/20-json.ini
      - /etc/php/7.0/cli/conf.d/20-pdo_pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-pgsql.ini
      - /etc/php/7.0/cli/conf.d/20-phar.ini
      - /etc/php/7.0/cli/conf.d/20-posix.ini
      - /etc/php/7.0/cli/conf.d/20-readline.ini
      - /etc/php/7.0/cli/conf.d/20-shmop.ini
      - /etc/php/7.0/cli/conf.d/20-sockets.ini
      - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
      - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
      - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
      - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
      - /etc/php/7.0/cli/conf.d/20-zip.ini   You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

When running 'composer dump-autoload' I get the following:

Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Cannot create cache
  directory /home/user/.composer/cache/files/, or directory is not
  writable. Proceeding without cache Cannot create cache directory
  /home/user/.composer/cache/repo/https---packagist.org/, or directory
  is not writable. Proceeding without cache Generating optimized
  autoload files

After following the advice of Nishan Karunarathna and Alex I now get the following error when I run 'php artisan serve':

PHP Fatal error:  Uncaught Error: Class
  'Illuminate\Foundation\Application' not found in
  /home/joshua/Projects/thingy/bootstrap/app.php:14 Stack trace:

0 /home/joshua/Projects/thingy/artisan(18): require_once()

1 {main}   thrown in /home/joshua/Projects/thingy/bootstrap/app.php on line 14

Thanks for any help you give!

答:
I think you should:

1) Install additional php extensions. Run into your terminal something like:
$ sudo apt-get install php7.0-opcache php7.0-calendar php7.0-ctype php7.0-gettext ...

2) Then give permissions to cache dir of composer:
$ sudo chmod -R u+w /home/joshua/.composer or if this directory is absent your should create its before $ sudo mkdir /home/joshua/.composer

3) Run $ composer install

But I'd like to pay your attention on:

1) Check your home directory on write permissions. If you don't have them, the most part of programs can't work correctly

2) Probably you have needed php extensions but they are not loaded. In this case check your .ini files and enable extensions.


问:
XPATH: Get row number of a query in RobotFramework
See code

https://prnt.sc/fscdi5

I want to get the row number containing the specific date string and the String TestTraining..

I can then use this to go to the Download Certificate link to click the correct link.

答:
to get row by any containing text:

```<code>//*[contains(text(),'someText')]/preceding::tr[1]
</code>```

actually you can find any tr part by any attribute and use found locator to get it's row:

```<code>locator/preceding::tr[1]
</code>```

Body:
to get row by any containing text:

//*[contains(text(),'someText')]/preceding::tr[1]

actually you can find any tr part by any attribute and use found locator to get it's row:

locator/preceding::tr[1]


问:
cuda install error on Ubuntu 17.04
```<code>   abigail@abilina:~/Downloads$ sudo dpkg -i cuda-repo-ubuntu1604_8.0.61-1_amd64.deb
Selecting previously unselected package cuda-repo-ubuntu1604.
(Reading database ... 205999 files and directories currently installed.)
Preparing to unpack cuda-repo-ubuntu1604_8.0.61-1_amd64.deb ...
Unpacking cuda-repo-ubuntu1604 (8.0.61-1) ...
Setting up cuda-repo-ubuntu1604 (8.0.61-1) ...
Warning: The postinst maintainerscript of the package cuda-repo-ubuntu1604
Warning: seems to use apt-key (provided by apt) without depending on gnupg or gnupg2.
Warning: This will BREAK in the future and should be fixed by the package maintainer(s).
Note: Check first if apt-key functionality is needed at all - it probably isn't!
Warning: apt-key should not be used in scripts (called from postinst maintainerscript of the package cuda-repo-ubuntu1604)
OK

abigail@abilina:~/Downloads$ sudo apt-get install cuda
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 cuda : Depends: cuda-8-0 (>= 8.0.61) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

My ubuntu version is 17.04. Does this mean my Linux currently can't install CUDA? I want to install TensorFlow with GPU support.

Per suggestion:

```<code>abigail@abilina:~/Downloads$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

答:
I have successfully installed CUDA 8.0 + the latest patch from NVIDIA on Ubuntu 17.04:

Download the .run file from https://developer.nvidia.com/cuda-downloads, choosing Ubuntu 16.04 (Base Installer)

You will not be able to install it by just running, because it is looking for a file called InstallUtils.pm which is not present in Ubuntu 17.04, but curiously, is present in the .run file - so: unpack the .run file using ./cuda*.run --tar mxvf

copy InstallUtils.pm (should be in the /bin path) to /usr/lib/x86_64-linux-gnu/perl-base

Run the installer (You may want to say no to the driver install step to keep the one you install through apt - I'm using 381.22, because 375.26, which is provided by the .run file does not support my 1080ti)

gcc 6 is incompatible with CUDA, but this is easily remedied for compiling the sample files: just add export EXTRA_NVCCFLAGS="-Xcompiler -std=c++98" to your bashrc file, and comment out

from one of the headers (I think it was host_config.h, but you'll see it once you try to compile) - comment out these lines:

```<code>#if __GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ > 3)
     #error -- unsupported GNU version! gcc versions later than 5.3 are not supported!
</code>```

This is all from memory, so hopefully it's accurate enough.

I managed to find this solution thanks to these useful posts:

https://devtalk.nvidia.com/default/topic/983777/can-t-locate-installutils-pm-in-inc/

https://devtalk.nvidia.com/default/topic/949770/cuda-8-0rc-supporting-gcc6-/

Title: cuda install error on Ubuntu 17.04

Body:
   abigail@abilina:~/Downloads$ sudo dpkg -i cuda-repo-ubuntu1604_8.0.61-1_amd64.deb
Selecting previously unselected package cuda-repo-ubuntu1604.
(Reading database ... 205999 files and directories currently installed.)
Preparing to unpack cuda-repo-ubuntu1604_8.0.61-1_amd64.deb ...
Unpacking cuda-repo-ubuntu1604 (8.0.61-1) ...
Setting up cuda-repo-ubuntu1604 (8.0.61-1) ...
Warning: The postinst maintainerscript of the package cuda-repo-ubuntu1604
Warning: seems to use apt-key (provided by apt) without depending on gnupg or gnupg2.
Warning: This will BREAK in the future and should be fixed by the package maintainer(s).
Note: Check first if apt-key functionality is needed at all - it probably isn't!
Warning: apt-key should not be used in scripts (called from postinst maintainerscript of the package cuda-repo-ubuntu1604)
OK

abigail@abilina:~/Downloads$ sudo apt-get install cuda
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 cuda : Depends: cuda-8-0 (>= 8.0.61) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

My ubuntu version is 17.04. Does this mean my Linux currently can't install CUDA? I want to install TensorFlow with GPU support.

Per suggestion:

abigail@abilina:~/Downloads$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Body:
I have successfully installed CUDA 8.0 + the latest patch from NVIDIA on Ubuntu 17.04:

Download the .run file from https://developer.nvidia.com/cuda-downloads, choosing Ubuntu 16.04 (Base Installer)

You will not be able to install it by just running, because it is looking for a file called InstallUtils.pm which is not present in Ubuntu 17.04, but curiously, is present in the .run file - so: unpack the .run file using ./cuda*.run --tar mxvf

copy InstallUtils.pm (should be in the /bin path) to /usr/lib/x86_64-linux-gnu/perl-base

Run the installer (You may want to say no to the driver install step to keep the one you install through apt - I'm using 381.22, because 375.26, which is provided by the .run file does not support my 1080ti)

gcc 6 is incompatible with CUDA, but this is easily remedied for compiling the sample files: just add export EXTRA_NVCCFLAGS="-Xcompiler -std=c++98" to your bashrc file, and comment out

from one of the headers (I think it was host_config.h, but you'll see it once you try to compile) - comment out these lines:

#if __GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ > 3)
     #error -- unsupported GNU version! gcc versions later than 5.3 are not supported!

This is all from memory, so hopefully it's accurate enough.

I managed to find this solution thanks to these useful posts:

https://devtalk.nvidia.com/default/topic/983777/can-t-locate-installutils-pm-in-inc/

https://devtalk.nvidia.com/default/topic/949770/cuda-8-0rc-supporting-gcc6-/


问:
How to iterate over an object and get the correct keys with jQuery
I have the following object:

```<code>{
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
  etc...
}
</code>```

Now i need to create a loop that iterates through the object, and i need the product id and the brand and display those. How do i do that?

I have looked at dozens of stack overflow questions and i don't find any that are about exactly my use case.

答:
If you want to do this using jQuery, you're looking for jQuery.each().

var data = {
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
}

$.each(data, function(i, obj) {
  console.log(i+': '+obj.ProductType+' | '+obj.ProductId+' | '+obj.Brand);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have the following object:

{
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
  etc...
}

Now i need to create a loop that iterates through the object, and i need the product id and the brand and display those. How do i do that?

I have looked at dozens of stack overflow questions and i don't find any that are about exactly my use case.

Body:
If you want to do this using jQuery, you're looking for jQuery.each().

var data = {
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
}

$.each(data, function(i, obj) {
  console.log(i+': '+obj.ProductType+' | '+obj.ProductId+' | '+obj.Brand);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Not able to "findViewById" in Kotlin. Getting error "Type inference failed"
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

```<code>class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}
</code>```

答:
Usually Kotlin can infer your type using the info provided in the brackets.

In this case, it can't so you would have to specify it explicitly like this

```<code>findViewById<RecyclerView>(R.id.recycler_view)
</code>```

Not really sure about the type though but that is how you should specify it

I'd like to add that, using Anko, you can further simplify your code like this:

```<code>val recycler_view : RecyclerView =  find(R.id.recycler_view)
</code>```

Body:
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

Body:
Usually Kotlin can infer your type using the info provided in the brackets.

In this case, it can't so you would have to specify it explicitly like this

findViewById<RecyclerView>(R.id.recycler_view)

Not really sure about the type though but that is how you should specify it

I'd like to add that, using Anko, you can further simplify your code like this:

val recycler_view : RecyclerView =  find(R.id.recycler_view)


问:
How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

```<code>@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}
<div class="">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                <div class="x_title">
                    <h2><i class="fa fa-filter"></i> </h2>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">
                    <br />
                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                        <div class="col-md-12 col-sm-12">
                            <div class="col-md-12 col-sm-12">
                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })
                            </div>
                        </div>

                    }

                }
            }
        }
    }
}
</code>```

Controller action:

```<code>public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}
</code>```

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

答:
Since you've requested how to do this with a strongly typed model instead of a ViewBag....

Right now your view requires a model of type IEnumerable<Language>. Change this to be a new class that holds all values your page needs.

```<code>public class LanguagesViewModel
{
    List<Language> ActiveLanguages { get; set; }
}
</code>```

Then in your controller:

```<code>var model = new LanguagesViewModel();
model.ActiveLanguages = activeLanguages;
return View(model);
</code>```

Change your View to require a LanguagesViewModel:

```<code>@model LanguagesViewModel
</code>```

Now you won't be working with the dynamic view bag.

```<code>@Html.DropDownListFor(m => m.LanguageId, Model.ActiveLanguages, new { @class = "form-control" })
</code>```

Body:
I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:

The type arguments for method
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable,
  string)' cannot be inferred from the usage. Try specifying the type
  arguments explicitly.

And here is my code:

@model IEnumerable<Language>
@using Web.Helpers
@{
    ViewBag.Title = "";
}

                    @using (Html.BeginForm("Settings","Language", FormMethod.Post, new { @class = "form-horizontal form-label-left" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)

                                @Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { @class = "form-control" })

                    }

                }
            }
        }
    }
}

Controller action:

public ActionResult Settings()
{
   List<Language> activeL = LanguageController.GetAll();
   ViewBag.Languagess = activeLanguages;

   return View(activeL);
}

Maybe I could delete ViewBag.Languagess at all, so I can use  (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")

Body:
Since you've requested how to do this with a strongly typed model instead of a ViewBag....

Right now your view requires a model of type IEnumerable<Language>. Change this to be a new class that holds all values your page needs.

public class LanguagesViewModel
{
    List<Language> ActiveLanguages { get; set; }
}

Then in your controller:

var model = new LanguagesViewModel();
model.ActiveLanguages = activeLanguages;
return View(model);

Change your View to require a LanguagesViewModel:

@model LanguagesViewModel

Now you won't be working with the dynamic view bag.

@Html.DropDownListFor(m => m.LanguageId, Model.ActiveLanguages, new { @class = "form-control" })


问:
In remote Visual SVN Server Post Commit Cook is not working properly,
In remote repo need to be auto updated but VISUAL SVN Server Post commit hook is not working Properly. This is my webhook code..
PATH=%PATH%;"C:\Program Files\VisualSVN Server\bin\"
set SVN_WORK_DIR=C:\Svn\Test"
svn update %SVN_WORK_DIR%

It's returns below error:

Error: post-commit hook failed (exit code 1) with output:

Error: svn: E155004: Run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)

Error: svn: E155004: Failed to lock working copy 'C:\Svn\Test'.

Error: svn: E200031: sqlite[S8]: attempt to write a readonly database

Error: svn: E200042: Additional errors:

Error: svn: E200031: sqlite[S8]: attempt to write a readonly database

I have try various code, but it's not working. Any one can help me????

答:
The error that you receive is most likely caused by lack of access permissions to C:\Svn\Test. You must provide the service account with Read/Write access to this directory.

The hook scripts run under the account that runs VisualSVN Server service. VisualSVN Server runs as Network Service account, by default.


问:
How do I install django-ckeditor?
In Stack Overflow there's two questions about this editor, and nobody answers!!!

So I'm asking how to install this Django package to my project??
I've followed these steps already, have no errors, nothing, and still the form stays the same. Why??

Edit: heres model

```<code>from datetime import datetime

from django.db                import models
from django.utils.translation import ugettext_lazy as _, ugettext
from ckeditor.fields          import RichTextField

class Newsletter(models.Model):

    title = models.CharField(
        _(u'Title'),
        max_length=200,
        help_text=_(u'Newsletter title'),
        )

    body = RichTextField()

    date = models.DateField(
         _(u'Date'),
         help_text=_(u'Set date when this newsletter should be send')
    )

    class Meta:
        ordering = ['title',]
</code>```

forms.py

```<code>from models import Newsletter, Mail
class NewsletterForm(forms.ModelForm):
    class Meta:
       model = Newsletter
</code>```

view:

```<code>from newsletter.models import Newsletter, Mail
from newsletter.forms  import NewsletterForm, MailForm

def newsletters_add(request):
    form = NewsletterForm()
    tpl  = "form_newsletter.html"

    return render_to_response(tpl, RequestContext(request, {
        'form': form,
    }))
</code>```

All form outputed succesfully with {{ form }} tag

settings.py (of the project)

```<code>CKEDITOR_MEDIA_PREFIX  = "/media/ckeditor/"
CKEDITOR_UPLOAD_PATH   = "/www/vhosts/sender/media/newsletter/uploads/"
CKEDITOR_UPLOAD_PREFIX = "http://******/media/newsletter/uploads/"
CKEDITOR_RESTRICT_BY_USER = True

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Basic',
    },
}

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.admin',
    #'tagging',
    'debug_toolbar',
    'ckeditor',
    'mailer',
    'newsletter'

)
</code>```

答:
ok sorry i was an idiot. in documentation there's no words about including JS manually somehow! so just include it

```<code><script src="http://****/media/ckeditor/ckeditor/ckeditor.js"></script>
</code>```

Developers are blind in there or something?

Title: How do I install django-ckeditor?

Body:
In Stack Overflow there's two questions about this editor, and nobody answers!!!

So I'm asking how to install this Django package to my project??
I've followed these steps already, have no errors, nothing, and still the form stays the same. Why??

Edit: heres model

from datetime import datetime

from django.db                import models
from django.utils.translation import ugettext_lazy as _, ugettext
from ckeditor.fields          import RichTextField

class Newsletter(models.Model):

    title = models.CharField(
        _(u'Title'),
        max_length=200,
        help_text=_(u'Newsletter title'),
        )

    body = RichTextField()

    date = models.DateField(
         _(u'Date'),
         help_text=_(u'Set date when this newsletter should be send')
    )

    class Meta:
        ordering = ['title',]

forms.py

from models import Newsletter, Mail
class NewsletterForm(forms.ModelForm):
    class Meta:
       model = Newsletter

view:

from newsletter.models import Newsletter, Mail
from newsletter.forms  import NewsletterForm, MailForm

def newsletters_add(request):
    form = NewsletterForm()
    tpl  = "form_newsletter.html"

    return render_to_response(tpl, RequestContext(request, {
        'form': form,
    }))

All form outputed succesfully with {{ form }} tag

settings.py (of the project)

CKEDITOR_MEDIA_PREFIX  = "/media/ckeditor/"
CKEDITOR_UPLOAD_PATH   = "/www/vhosts/sender/media/newsletter/uploads/"
CKEDITOR_UPLOAD_PREFIX = "http://******/media/newsletter/uploads/"
CKEDITOR_RESTRICT_BY_USER = True

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Basic',
    },
}

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.admin',
    #'tagging',
    'debug_toolbar',
    'ckeditor',
    'mailer',
    'newsletter'

)

Body:
ok sorry i was an idiot. in documentation there's no words about including JS manually somehow! so just include it

<script src="http://****/media/ckeditor/ckeditor/ckeditor.js"></script>

Developers are blind in there or something?


问:
Oracle SQL - SELECT with Variable arguments stored procedure
I'm struggling with a variable argument stored procedure that has to perform a SELECT on a table using every argument passed to it in its WHERE clause.

Basically I have N account numbers as parameter and I want to return a table with the result of selecting three fields for each account number.

This is what I've done so far:

```<code>function sp_get_minutes_expiration_default(retval IN OUT char, gc IN OUT GenericCursor,
        p_account_num IN CLIENT_ACCOUNTS.ACCOUNT_NUM%TYPE) return number
        is
    r_cod integer := 0;
    begin
        open gc for select account_num, concept_def, minutes_expiration_def from CLIENT_ACCOUNTS
            where p_account_num = account_num;  -- MAYBE A FOR LOOP HERE?
        return r_cod;
    exception

        -- EXCEPTION HANDLING

    end sp_get_minutes_expiration_default;
</code>```

My brute force solution would be to maybe loop over a list of account numbers, select and maybe do a UNION or append to the result table?

答:
If you cast your input parameter as a table, then you can join it to CLIENT_ACCOUNTS

```<code>select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(p_account_num) a
where a.account_num = ca.account_num
</code>```

But I would recommend you select the output into another collection that is the output of the function (or procedure). I would urge you to not use reference cursors.

ADDENDUM 1

A more complete example follows:

```<code>create or replace type id_type_array as table of number;
/

declare
   ti id_type_array := id_type_array();
   n number;
begin
   ti.extend();
   ti(1) := 42;
   select column_value into n from table(ti) where rownum = 1;
end;
/
</code>```

In your code, you would need to use the framework's API to:

create an instance of the collection (of type id_type_array)

populate the collection with the list of numbers

Execute the anonymous PL/SQL block, binding in the collection

But you should immediately see that you don't have to put the query into an anonymous PL/SQL block to execute it (even though many experienced Oracle developers advocate it). You can execute the query just like any other query so long as you bind the correct parameter:

```<code>select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(:p_account_num) a
where a.column_value = ca.account_num
</code>```

Body:
I'm struggling with a variable argument stored procedure that has to perform a SELECT on a table using every argument passed to it in its WHERE clause.

Basically I have N account numbers as parameter and I want to return a table with the result of selecting three fields for each account number.

This is what I've done so far:

function sp_get_minutes_expiration_default(retval IN OUT char, gc IN OUT GenericCursor,
        p_account_num IN CLIENT_ACCOUNTS.ACCOUNT_NUM%TYPE) return number
        is
    r_cod integer := 0;
    begin
        open gc for select account_num, concept_def, minutes_expiration_def from CLIENT_ACCOUNTS
            where p_account_num = account_num;  -- MAYBE A FOR LOOP HERE?
        return r_cod;
    exception

        -- EXCEPTION HANDLING

    end sp_get_minutes_expiration_default;

My brute force solution would be to maybe loop over a list of account numbers, select and maybe do a UNION or append to the result table?

Body:
If you cast your input parameter as a table, then you can join it to CLIENT_ACCOUNTS

select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(p_account_num) a
where a.account_num = ca.account_num

But I would recommend you select the output into another collection that is the output of the function (or procedure). I would urge you to not use reference cursors.

ADDENDUM 1

A more complete example follows:

create or replace type id_type_array as table of number;
/

declare
   ti id_type_array := id_type_array();
   n number;
begin
   ti.extend();
   ti(1) := 42;
   select column_value into n from table(ti) where rownum = 1;
end;
/

In your code, you would need to use the framework's API to:

create an instance of the collection (of type id_type_array)

populate the collection with the list of numbers

Execute the anonymous PL/SQL block, binding in the collection

But you should immediately see that you don't have to put the query into an anonymous PL/SQL block to execute it (even though many experienced Oracle developers advocate it). You can execute the query just like any other query so long as you bind the correct parameter:

select account_num, concept_def, minutes_expiration_def
from CLIENT_ACCOUNTS ca, table(:p_account_num) a
where a.column_value = ca.account_num