问:
How to call the parent thread function from the separately running child thread in loop in Qt
I have the QMainWindow::show() and hide() functions respectively in the MainWindow class that creates the Qt window (GUI) and returns the exec(). From the same class constructor, I have called made the thread to another class slot function that runs in a background continuously listening to the global mouse coordinates and it should toggle display/hide the GUI mainwindow when the mouse is at the bottom of the screen and is moving along the x axis. Here is the code :

```<code>#include "mainwindow.hpp"
#include "Xmousetrack.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{

    MouseTrack * mT = new MouseTrack;
    mT->moveToThread(&mouseThread);

    connect(&mouseThread, SIGNAL(finished()), mT, SLOT(deleteLater()));
    connect(this, SIGNAL(signalPointer(int&,int&)), mT, SLOT(trackPointer(int&,int&)));
    mouseThread.start();
}

void MainWindow::showDisplay()
{
    MainWindow::show();
}

void MainWindow::hideDisplay()
{
    MainWindow::hide();
}

MainWindow::~MainWindow()
{
    mouseThread.requestInterruption();
    mouseThread.quit();
    mouseThread.wait();
}

// class blueprint in Xmousetrack.hpp
MouseTrack::MouseTrack()
{
    dpr = XOpenDisplay(NULL);
    if (!dpr)
    {
      std::cerr << "XOpenDisplay(0x0) returned 0x0" << std::endl;
      std::exit(EXIT_FAILURE);
    }

    Xheight = HeightOfScreen(dpr);
    Xheight -= (Xheight - 20); //the last 20 height in pixels of the screen
    xdo = xdo_new(NULL);
}

MouseTrack::~MouseTrack() { xdo_free(xdo); }

void MouseTrack::trackpointer(int &x, int &y) //slot function
{
    xdo_get_mouse_location(xdo, &x , &y , CURRENTWINDOW); // libx11 fucntion
    prev_x = x;

    while(!QThread::currentThread()->isInterruptionRequested())
    {
        usleep(1000);
        xdo_get_mouse_location(xdo, &x , &y , CURRENTWINDOW);
        if ( abs(x - prev_x) > 10 and y >= Xheight)
        {
            hide = 1 - hide;
            if (hide == 0)
           {
            // I NEED TO CALL MainWindow::showDisplay() here
           }

        }

    }
}
</code>```

I have tried all the Qt mouse functions for the purpose and failed and now I am using X11 lib and it works fine as a separate module. This is my problem in combined all in one and calling the MainWindow::showDisplay() function of the parent thread.

答:
The way you've set this up, the MainWindow and the MouseTrack objects live in different threads. So directly calling the MainWindow::showDisplay() member function from MouseTrack::trackpointer() is not a good idea. This is exactly what signals and slots are for.

Add a signal to your MouseTrack class, called something like requestHide(bool), and connect it to the MainWindow::setVisible() slot. In the MouseTrack::trackpointer() function, emit the signal with emit requestHide(hide). The MainWindow will then toggle its visibility.

Body:
I have the QMainWindow::show() and hide() functions respectively in the MainWindow class that creates the Qt window (GUI) and returns the exec(). From the same class constructor, I have called made the thread to another class slot function that runs in a background continuously listening to the global mouse coordinates and it should toggle display/hide the GUI mainwindow when the mouse is at the bottom of the screen and is moving along the x axis. Here is the code :

#include "mainwindow.hpp"
#include "Xmousetrack.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{

    MouseTrack * mT = new MouseTrack;
    mT->moveToThread(&mouseThread);

    connect(&mouseThread, SIGNAL(finished()), mT, SLOT(deleteLater()));
    connect(this, SIGNAL(signalPointer(int&,int&)), mT, SLOT(trackPointer(int&,int&)));
    mouseThread.start();
}

void MainWindow::showDisplay()
{
    MainWindow::show();
}

void MainWindow::hideDisplay()
{
    MainWindow::hide();
}

MainWindow::~MainWindow()
{
    mouseThread.requestInterruption();
    mouseThread.quit();
    mouseThread.wait();
}

// class blueprint in Xmousetrack.hpp
MouseTrack::MouseTrack()
{
    dpr = XOpenDisplay(NULL);
    if (!dpr)
    {
      std::cerr << "XOpenDisplay(0x0) returned 0x0" << std::endl;
      std::exit(EXIT_FAILURE);
    }

    Xheight = HeightOfScreen(dpr);
    Xheight -= (Xheight - 20); //the last 20 height in pixels of the screen
    xdo = xdo_new(NULL);
}

MouseTrack::~MouseTrack() { xdo_free(xdo); }

void MouseTrack::trackpointer(int &x, int &y) //slot function
{
    xdo_get_mouse_location(xdo, &x , &y , CURRENTWINDOW); // libx11 fucntion
    prev_x = x;

    while(!QThread::currentThread()->isInterruptionRequested())
    {
        usleep(1000);
        xdo_get_mouse_location(xdo, &x , &y , CURRENTWINDOW);
        if ( abs(x - prev_x) > 10 and y >= Xheight)
        {
            hide = 1 - hide;
            if (hide == 0)
           {
            // I NEED TO CALL MainWindow::showDisplay() here
           }

        }

    }
}

I have tried all the Qt mouse functions for the purpose and failed and now I am using X11 lib and it works fine as a separate module. This is my problem in combined all in one and calling the MainWindow::showDisplay() function of the parent thread.


来源: stackexchange

问:
How to deploy a Falcon MVC REST API in Azure Functions?
I deployed my Falcon app in azure functions using bitbucket. But I cannot see any of the files in the function app. I also tried by pulling the repo to azure function folder but that didn't work either becuase my routes didn't work as expected. I use MVC architecture in my app. My run.py looks like

```<code>import falcon
from wsgiref import simple_server
from project.routes import *

    if __name__ == "__main__":
        host = '127.0.0.1'
        port = 5000
        httpd = simple_server.make_server(host, port, app)
        print("Serving on %s:%s" % (host, port))
        httpd.serve_forever()
</code>```

Is there any way to deploy my app as it is or should I change the structure.

Current folder structure

答:
Azure Functions is not an appropriate place to just place a web application and expect it to run as normal. It is a "serverless" framework, so having your app use a MVC architecture is a sign that your app is currently not a good fit for Azure Functions. In your application's current state, it is better suited for an Azure Web App.

Azure Functions apps should be built around small functions that are called in response to events. To make your application a better fit for Azure Functions, it would involve refactoring your application into individual functions, that are triggered by events such as HTTP requests, timers, and many others that can be found here.

ContentLicense: CC BY-SA 3.0

Body:
I deployed my Falcon app in azure functions using bitbucket. But I cannot see any of the files in the function app. I also tried by pulling the repo to azure function folder but that didn't work either becuase my routes didn't work as expected. I use MVC architecture in my app. My run.py looks like

import falcon
from wsgiref import simple_server
from project.routes import *

    if __name__ == "__main__":
        host = '127.0.0.1'
        port = 5000
        httpd = simple_server.make_server(host, port, app)
        print("Serving on %s:%s" % (host, port))
        httpd.serve_forever()

Is there any way to deploy my app as it is or should I change the structure.

Current folder structure


问:
Retrieve entire HTML with urlopen(url)
I have noticed if I request a url using

```<code>urllib.request.urlopen([my_url]).read()
</code>```

I get something like this:

```<code> <html>
<head>
</head>
<body>
    <span>...</span>
<body>
<script>
</script>

</html>
</code>```

All the info I want for beautifulsoup is in that ... section.  If I use a webdriver, then that section is included.  But a webdriver seems to take longer, and causes my code to be a bit more messy.  Is there way to retrieve the entirety of the HTML doc without using a webdriver?

答:
You can use the famous request library, see if the below code will help you</p>

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

page = requests.get('https://www.google.com/')
soup = BeautifulSoup(page.text, 'lxml')

span = soup.find_all('span')
print(span)
</code>```

Title: Retrieve entire HTML with urlopen(url)

Body:
I have noticed if I request a url using

urllib.request.urlopen([my_url]).read()

I get something like this:

    ...

All the info I want for beautifulsoup is in that ... section.  If I use a webdriver, then that section is included.  But a webdriver seems to take longer, and causes my code to be a bit more messy.  Is there way to retrieve the entirety of the HTML doc without using a webdriver?

Body:
You can use the famous request library, see if the below code will help you

import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.google.com/')
soup = BeautifulSoup(page.text, 'lxml')

span = soup.find_all('span')
print(span)


问:
d3.json in d3-ng2-service?
I am currently upgrading a project from Angularjs and d3 v3 to Angular5 and d3-ng2-service.The new versions work together nicely and d3 works for simple examples. My challenge is: How to upgrade d3.json() to d3-ng2-service?

```<code>d3.json gives me the editor error: "Property 'json' does not exist on type 'typeof "d3-ng2-service"
</code>```

Other types like d3.arc, etc. work.

My questions:
A) Was d3.json dropped from d3-ng2-service?
B) If yes, can anybody please provide an example for replacing it by an Angular5 functionality?

答:
to B) How to replace the function d3.json() within Angular2 and higher?
The function

```<code>d3.json('filename.json',function(error, object){let o = object});
</code>```

creates a regular 'object' based on the structures used in the 'filename.json'-file. With the d3-ng2-service library I use instead:

```<code>this.http.get('filename.json').subscribe(res =>{let o = res.json()},error =>{console.log('Error'});
</code>```

The more detailed description for loading a JSON file in Angular2 can be found in this article.

Title: d3.json in d3-ng2-service?

Body:
I am currently upgrading a project from Angularjs and d3 v3 to Angular5 and d3-ng2-service.The new versions work together nicely and d3 works for simple examples. My challenge is: How to upgrade d3.json() to d3-ng2-service?

d3.json gives me the editor error: "Property 'json' does not exist on type 'typeof "d3-ng2-service"

Other types like d3.arc, etc. work.

My questions:
A) Was d3.json dropped from d3-ng2-service?
B) If yes, can anybody please provide an example for replacing it by an Angular5 functionality?

Body:
to B) How to replace the function d3.json() within Angular2 and higher?
The function

d3.json('filename.json',function(error, object){let o = object});

creates a regular 'object' based on the structures used in the 'filename.json'-file. With the d3-ng2-service library I use instead:

this.http.get('filename.json').subscribe(res =>{let o = res.json()},error =>{console.log('Error'});

The more detailed description for loading a JSON file in Angular2 can be found in this article.


问:
How to configure Realm Object Server v2.0.4 for HTTPS connections?
I have deployed Realm Object Server v2.0.4 onto Ubuntu and also implemented LetsEncrypt.  I can connect using the new Realm Studio - all seems good.

Now that the base server is in place I need to configure it to use HTTPS and disable HTTP - and this is where I'm struggling.

I have created a new Realm project using ros init bb (bb is just a temp project name) and the folder structure looks like this:

```<code>bb
└───src
│   │   index.ts
</code>```

I have updated index.ts to contain the following:

```<code>import { BasicServer } from 'realm-object-server'
import * as path from 'path'

const BasicServer = require('realm-object-server').BasicServer
const path = require('path')
const server = new BasicServer()

server.start({
        console.log(`Does this get logged?`),
        dataPath: path.join(__dirname, '../data'),
        https-enable: true,
        https-key: '/etc/letsencrypt/live/{my domain in here}/privkey.pem',
        https-cert: '/etc/letsencrypt/live/{my domain in here}/cert.pem',
        https-address: 0.0.0.0,
        https-port: 9443
    })
    .then(() => {
        console.log(`Your server is started `, server.address)
    })    .then(() => {
        console.log(`Your server is started `, server.address)
    })
    .catch(err => {
        console.error(`There was an error starting your file`)
    })
</code>```

When I start ros (ros start) the console outputs:

```<code>info: Realm Object Server version 2.0.4 is starting
info: Realm sync server started ([realm-core-4.0.2], [realm-sync-2.0.2]) service=sync
info: Directory holding persistent state: /home/ros_admin/bb/data/sync/user_data service=sync
info: Operating mode: master_with_no_slave service=sync
info: Listening on 127.0.0.1:36580 (sync protocol version 22) service=sync
info: sync-client: Connection[1]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55292')
info: sync-client: Connection[2]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55294')
info: sync-client: Connection[3]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55296')
info: Starting auth provider 'password'
info: sync-client: Connection[4]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55298')
info: 127.0.0.1 - GET /realms/files/%2F__admin HTTP/1.1 200 41 - 6.342 ms
info: 127.0.0.1 - GET /realms/files/%2F__revocation HTTP/1.1 200 46 - 1.071 ms
info: 127.0.0.1 - GET /realms/files/%2F__wildcardpermissions HTTP/1.1 200 55 - 1.201 ms
info: 127.0.0.1 - GET /realms/files/%2F__password HTTP/1.1 200 44 - 0.629 ms
info: Realm Object Server has started and is listening on http://0.0.0.0:9080
info: sync-client: Connection[5]: Connected to endpoint '0.0.0.0:9080' (from '127.0.0.1:33262')
info: sync-client: Connection[6]: Connected to endpoint '0.0.0.0:9080' (from '127.0.0.1:33266')
</code>```

Because I'm not seeing any of the console log output I have to assume my configuration is not being called.  Which leads me to think that I've placed the configuration in the wrong file or location or that there is an extra step that I'm missing.

Can anyone advise?  Or does anyone have an example configuration they can share?

答:
Your config object is malformed. It should be a valid JSON value.

The first console.log() line is invalid JSON

The key names you have provided which have hyphens and are unquoted are invalid

The IP value needs to be quoted as a string

The command line flag names are different than their javascript equivalent in the config object you pass to server.start().

server.start({
        dataPath: path.join(__dirname, '../data'),
        https: true,
        httpsKeyPath: '/etc/letsencrypt/live/{my domain in here}/privkey.pem',
        httpsCertChainPath: '/etc/letsencrypt/live/{my domain in here}/cert.pem',
        httpsAddress: '0.0.0.0',
        httpsPort: 9443
    })
```

See the example Typescript or Javascript config here for more information.

Body:
I have deployed Realm Object Server v2.0.4 onto Ubuntu and also implemented LetsEncrypt.  I can connect using the new Realm Studio - all seems good.

Now that the base server is in place I need to configure it to use HTTPS and disable HTTP - and this is where I'm struggling.

I have created a new Realm project using ros init bb (bb is just a temp project name) and the folder structure looks like this:

bb
└───src
│   │   index.ts

I have updated index.ts to contain the following:

import { BasicServer } from 'realm-object-server'
import * as path from 'path'

const BasicServer = require('realm-object-server').BasicServer
const path = require('path')
const server = new BasicServer()

server.start({
        console.log(`Does this get logged?`),
        dataPath: path.join(__dirname, '../data'),
        https-enable: true,
        https-key: '/etc/letsencrypt/live/{my domain in here}/privkey.pem',
        https-cert: '/etc/letsencrypt/live/{my domain in here}/cert.pem',
        https-address: 0.0.0.0,
        https-port: 9443
    })
    .then(() => {
        console.log(`Your server is started `, server.address)
    })    .then(() => {
        console.log(`Your server is started `, server.address)
    })
    .catch(err => {
        console.error(`There was an error starting your file`)
    })

When I start ros (ros start) the console outputs:

info: Realm Object Server version 2.0.4 is starting
info: Realm sync server started ([realm-core-4.0.2], [realm-sync-2.0.2]) service=sync
info: Directory holding persistent state: /home/ros_admin/bb/data/sync/user_data service=sync
info: Operating mode: master_with_no_slave service=sync
info: Listening on 127.0.0.1:36580 (sync protocol version 22) service=sync
info: sync-client: Connection[1]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55292')
info: sync-client: Connection[2]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55294')
info: sync-client: Connection[3]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55296')
info: Starting auth provider 'password'
info: sync-client: Connection[4]: Connected to endpoint '127.0.0.1:36580' (from '127.0.0.1:55298')
info: 127.0.0.1 - GET /realms/files/%2F__admin HTTP/1.1 200 41 - 6.342 ms
info: 127.0.0.1 - GET /realms/files/%2F__revocation HTTP/1.1 200 46 - 1.071 ms
info: 127.0.0.1 - GET /realms/files/%2F__wildcardpermissions HTTP/1.1 200 55 - 1.201 ms
info: 127.0.0.1 - GET /realms/files/%2F__password HTTP/1.1 200 44 - 0.629 ms
info: Realm Object Server has started and is listening on http://0.0.0.0:9080
info: sync-client: Connection[5]: Connected to endpoint '0.0.0.0:9080' (from '127.0.0.1:33262')
info: sync-client: Connection[6]: Connected to endpoint '0.0.0.0:9080' (from '127.0.0.1:33266')

Because I'm not seeing any of the console log output I have to assume my configuration is not being called.  Which leads me to think that I've placed the configuration in the wrong file or location or that there is an extra step that I'm missing.

Can anyone advise?  Or does anyone have an example configuration they can share?

Body:
Your config object is malformed. It should be a valid JSON value.

The first console.log() line is invalid JSON

The key names you have provided which have hyphens and are unquoted are invalid

The IP value needs to be quoted as a string

The command line flag names are different than their javascript equivalent in the config object you pass to server.start().

server.start({
        dataPath: path.join(__dirname, '../data'),
        https: true,
        httpsKeyPath: '/etc/letsencrypt/live/{my domain in here}/privkey.pem',
        httpsCertChainPath: '/etc/letsencrypt/live/{my domain in here}/cert.pem',
        httpsAddress: '0.0.0.0',
        httpsPort: 9443
    })

See the example Typescript or Javascript config here for more information.


问:
How to split a huge folder?
We have a folder on Windows that's ... huge. I ran "dir > list.txt". The command lost response after 1.5 hours. The output file is about 200 MB. It shows there're at least 2.8 million files. I know the situation is stupid but let's focus the problem itself. If I have such a folder, how can I split it to some "manageable" sub-folders? Surprisingly all the solutions I have come up with all involve getting all the files in the folder at some point, which is a no-no in my case. Any suggestions?

Thank Keith Hill and Mehrdad. I accepted Keith's answer because that's exactly what I wanted to do but I couldn't quite get PS working quickly.

With Mehrdad's tip, I wrote this little program. It took 7+ hours to move 2.8 million files. So the initial dir command did finish. But somehow it didn't return to console.

```<code>namespace SplitHugeFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            var destination = args[1];

            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            var di = new DirectoryInfo(args[0]);

            var batchCount = int.Parse(args[2]);
            int currentBatch = 0;

            string targetFolder = GetNewSubfolder(destination);

            foreach (var fileInfo in di.EnumerateFiles())
            {
                if (currentBatch == batchCount)
                {
                    Console.WriteLine("New Batch...");
                    currentBatch = 0;
                    targetFolder = GetNewSubfolder(destination);
                }

                var source = fileInfo.FullName;
                var target = Path.Combine(targetFolder, fileInfo.Name);
                File.Move(source, target);
                currentBatch++;
            }
        }

        private static string GetNewSubfolder(string parent)
        {
            string newFolder;
            do
            {
                newFolder = Path.Combine(parent, Path.GetRandomFileName());
            } while (Directory.Exists(newFolder));
            Directory.CreateDirectory(newFolder);
            return newFolder;
        }
    }
}
</code>```

答:
I found out the GetChildItem is the slowest option when working with many items in a directory.

Look at the results:

```<code>Measure-Command { Get-ChildItem C:\Windows -rec | Out-Null }
TotalSeconds      : 77,3730275
Measure-Command { listdir C:\Windows | Out-Null }
TotalSeconds      : 20,4077132
measure-command { cmd /c dir c:\windows /s /b | out-null }
TotalSeconds      : 13,8357157
</code>```

(with listdir function defined like this:

```<code>function listdir($dir) {
    $dir
    [system.io.directory]::GetFiles($dir)
    foreach ($d in [system.io.directory]::GetDirectories($dir)) {
        listdir $d
    }
}
</code>```

)

With this in mind, what I would do: I would stay in PowerShell but use more lowlevel approach with .NET methods:

```<code>function DoForFirst($directory, $max, $action) {
    function go($dir, $options)
    {
        foreach ($f in [system.io.Directory]::EnumerateFiles($dir))
        {
            if ($options.Remaining -le 0) { return }
            & $action $f
            $options.Remaining--
        }
        foreach ($d in [system.io.directory]::EnumerateDirectories($dir))
        {
            if ($options.Remaining -le 0) { return }
            go $d $options
        }
    }
    go $directory (New-Object PsObject -Property @{Remaining=$max })
}
doForFirst c:\windows 100 {write-host File: $args }
# I use PsObject to avoid global variables and ref parameters.
</code>```

To use the code you have to switch to .NET 4.0 runtime -- enumerating methods are new in .NET 4.0.

You can specify any scriptblock as -action parameter, so in your case it would be something like {Move-item -literalPath $args -dest c:\dir }.

Just try to list first 1000 items, I hope it will finish very quickly:

```<code>doForFirst c:\yourdirectory 1000 {write-host '.' -nonew }
</code>```

And of course you can process all items at once, just use

```<code>doForFirst c:\yourdirectory ([long]::MaxValue) {move-item ... }
</code>```

and each item should be processed immediately after it is returned. So the whole list is not read at once and then processed, but it is processed during reading.

ContentLicense: CC BY-SA 2.5

Title: How to split a huge folder?

Body:
We have a folder on Windows that's ... huge. I ran "dir > list.txt". The command lost response after 1.5 hours. The output file is about 200 MB. It shows there're at least 2.8 million files. I know the situation is stupid but let's focus the problem itself. If I have such a folder, how can I split it to some "manageable" sub-folders? Surprisingly all the solutions I have come up with all involve getting all the files in the folder at some point, which is a no-no in my case. Any suggestions?

Thank Keith Hill and Mehrdad. I accepted Keith's answer because that's exactly what I wanted to do but I couldn't quite get PS working quickly.

With Mehrdad's tip, I wrote this little program. It took 7+ hours to move 2.8 million files. So the initial dir command did finish. But somehow it didn't return to console.

namespace SplitHugeFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            var destination = args[1];

            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            var di = new DirectoryInfo(args[0]);

            var batchCount = int.Parse(args[2]);
            int currentBatch = 0;

            string targetFolder = GetNewSubfolder(destination);

            foreach (var fileInfo in di.EnumerateFiles())
            {
                if (currentBatch == batchCount)
                {
                    Console.WriteLine("New Batch...");
                    currentBatch = 0;
                    targetFolder = GetNewSubfolder(destination);
                }

                var source = fileInfo.FullName;
                var target = Path.Combine(targetFolder, fileInfo.Name);
                File.Move(source, target);
                currentBatch++;
            }
        }

        private static string GetNewSubfolder(string parent)
        {
            string newFolder;
            do
            {
                newFolder = Path.Combine(parent, Path.GetRandomFileName());
            } while (Directory.Exists(newFolder));
            Directory.CreateDirectory(newFolder);
            return newFolder;
        }
    }
}

Body:
I found out the GetChildItem is the slowest option when working with many items in a directory.

Look at the results:

Measure-Command { Get-ChildItem C:\Windows -rec | Out-Null }
TotalSeconds      : 77,3730275
Measure-Command { listdir C:\Windows | Out-Null }
TotalSeconds      : 20,4077132
measure-command { cmd /c dir c:\windows /s /b | out-null }
TotalSeconds      : 13,8357157

(with listdir function defined like this:

function listdir($dir) {
    $dir
    [system.io.directory]::GetFiles($dir)
    foreach ($d in [system.io.directory]::GetDirectories($dir)) {
        listdir $d
    }
}

)

With this in mind, what I would do: I would stay in PowerShell but use more lowlevel approach with .NET methods:

function DoForFirst($directory, $max, $action) {
    function go($dir, $options)
    {
        foreach ($f in [system.io.Directory]::EnumerateFiles($dir))
        {
            if ($options.Remaining -le 0) { return }
            & $action $f
            $options.Remaining--
        }
        foreach ($d in [system.io.directory]::EnumerateDirectories($dir))
        {
            if ($options.Remaining -le 0) { return }
            go $d $options
        }
    }
    go $directory (New-Object PsObject -Property @{Remaining=$max })
}
doForFirst c:\windows 100 {write-host File: $args }
# I use PsObject to avoid global variables and ref parameters.

To use the code you have to switch to .NET 4.0 runtime -- enumerating methods are new in .NET 4.0.

You can specify any scriptblock as -action parameter, so in your case it would be something like {Move-item -literalPath $args -dest c:\dir }.

Just try to list first 1000 items, I hope it will finish very quickly:

doForFirst c:\yourdirectory 1000 {write-host '.' -nonew }

And of course you can process all items at once, just use

doForFirst c:\yourdirectory ([long]::MaxValue) {move-item ... }

and each item should be processed immediately after it is returned. So the whole list is not read at once and then processed, but it is processed during reading.


问:
Genesis Theme- Anchor links stopped scrolling down in Chrome
I've got a site built on the Genesis framework with Cafe Pro child theme.

http://salat.md/

The main menu has anchor links that scroll to the relevant section of the front page. They work perfectly fine in Firefox, but stopped working in Chrome and Opera.

I've checked the demo site of the Cafe Pro Theme, and the same problem persists.
https://my.studiopress.com/themes/cafe/#demo-full

I didn't build the site and can't reach the guy who built it, so I don't have access to studiopress members' area.

Any input is appreciated.

答:
I'm not using Cafe Pro, but another Genesis child theme and was able to resolve this issue by updating to the latest release of both jQuery.localScroll and jQuery.ScrollTo. The files were both of these were included in my theme's /js/ directory. I updated the files there and then updated the wp_enqueue_script lines to contain the latest version numbers.

```<code>wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '2.0.0', true );
wp_enqueue_script( 'scrollTo', get_stylesheet_directory_uri() . '/js/jquery.scrollTo.min.js', array( 'jquery' ), '2.1.2', true );
</code>```

Body:
I'm not using Cafe Pro, but another Genesis child theme and was able to resolve this issue by updating to the latest release of both jQuery.localScroll and jQuery.ScrollTo. The files were both of these were included in my theme's /js/ directory. I updated the files there and then updated the wp_enqueue_script lines to contain the latest version numbers.

wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '2.0.0', true );
wp_enqueue_script( 'scrollTo', get_stylesheet_directory_uri() . '/js/jquery.scrollTo.min.js', array( 'jquery' ), '2.1.2', true );


问:
Android Webview reset Zoom second time in a fragment
I have a webview that you can pinch to zoom just fine.  I added a context menu to allow you to reset the zoom in addition to pinching out.  However if I pinch a second time to zoom in, the same exact call to reset the zoom does not appear to reset the view?  I've tried the following in various combinations but can not get a consistent reset zoom to work  Thoughts?</p>

```<code>myfrag.getWebView().getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
myfrag.getWebView().getSettings().setBuiltInZoomControls(true);
myfrag.getWebView().scrollTo(0,0);
</code>```

答:
Not sure why but this works:

myfrag.getWebView().getSettings().setLoadWithOverviewMode(false);                myfrag.getWebView().getSettings().setLoadWithOverviewMode(true);
myfrag.getWebView().setInitialScale(0);

Body:
I have a webview that you can pinch to zoom just fine.  I added a context menu to allow you to reset the zoom in addition to pinching out.  However if I pinch a second time to zoom in, the same exact call to reset the zoom does not appear to reset the view?  I've tried the following in various combinations but can not get a consistent reset zoom to work  Thoughts?

myfrag.getWebView().getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
myfrag.getWebView().getSettings().setBuiltInZoomControls(true);
myfrag.getWebView().scrollTo(0,0);


问:
I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)
Below is the code:

```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)
</code>```

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
Below is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
You could even use a set

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

c = filter(set(a).__contains__, b)
print(list(c))
# [1, 2, 3, 5, 8, 13]


问:
can't send PUT to Philips Hue (same origin policy)
I'm trying to send a PUT-request to a Philips Hue bridge, so I can change the current state in which the lamp is. I do this from a webserver on my PC. With CORS I already managed to send GET and POST- request, but if I send a PUT I get an error that tells "method not found in Access-Control-Allow-Methods". I'm pretty sure that would make no sense to block just that method.

I'm using that code to do so, it is the same as the code for GET and POST, just the if clause is not needed.

var lightReq = new XMLHttpRequest();

  if ("withCredentials" in lightReq) {
   lightReq.open('PUT',stringChange,true);
   if (value == false) {
    lightReq.send("{\"on\":true}");
   }
   else {
    lightReq.send("{\"on\":false}");
   }
  } ```

Maybe someone had a similar problem and got a solution, or there are steps I should check. I'm glad for every help.

EDIT:
Here is a screenshot of the header, it shows that the PUT-method should be accepted.

EDIT2:
For roryhewitt here is what you asked for, i think:

Best Regards,
Adrian

答:
It looks from your screenshot as if that's the response to a POST request (I'm looing at the Anfragemethode field)?

Most of those CORS response headers (except ACAC) should only be returned in the response to a preflight OPTIONS request - they have no 'meaning' if they are returned in the response to any other request. That's the 'fault' of the bridge, though, not of anything you're doing in the browser code.

Anyway, when your JS code makes a PUT request via XMLHttpRequest, if you look at the network traffic from your browser, you should see an OPTIONS requests (CORS preflight) followed by your PUT request. If you only see the OPTIONS request, can you provide the response headers for that request?

Body:
I'm trying to send a PUT-request to a Philips Hue bridge, so I can change the current state in which the lamp is. I do this from a webserver on my PC. With CORS I already managed to send GET and POST- request, but if I send a PUT I get an error that tells "method not found in Access-Control-Allow-Methods". I'm pretty sure that would make no sense to block just that method.

I'm using that code to do so, it is the same as the code for GET and POST, just the if clause is not needed.

var lightReq = new XMLHttpRequest();

  if ("withCredentials" in lightReq) {
   lightReq.open('PUT',stringChange,true);
   if (value == false) {
    lightReq.send("{\"on\":true}");
   }
   else {
    lightReq.send("{\"on\":false}");
   }
  }

Maybe someone had a similar problem and got a solution, or there are steps I should check. I'm glad for every help.

EDIT:
Here is a screenshot of the header, it shows that the PUT-method should be accepted.

EDIT2:
For roryhewitt here is what you asked for, i think:

Best Regards,
Adrian


问:
Same test for different states of the same object without persisting changes
I am trying to run the same exact test on a single obj which is a models.Model instance and has some relations with other models. I do not want to persist changes in that instance, so effectively I want the same effect of the tearDown method which rollbacks transactions.

To illustrate this:

```<code>class MyTestCase(django.test.TestCase):

    def test():
        # main test that calls the same test using all
        # different states of `obj` that need to be tested

        # different values of data that update the state of `obj`
        # with state I simply mean the values of `obj`'s attributes and relationships
        data = [state1, state2, state3]
        for state in data:
            obj = Obj.objects.get(pk=self.pk)  # gets that SINGLE object from the test db
            # applies the state data to `obj` to change its state
            obj.update(state)
            # performs the actual test on `obj` with this particular state
            self._test_obj(obj)

    def _test_obj(self, obj):
        self.assertEqual(len(obj.vals), 10)
        self.assertLess(obj.threshold, 99)
        # more assert statements...
</code>```

This design has two problems:

The changes on obj persist on the test database, so on the next iteration the data would be tainted. I would want to rollback those changes and get a fresh instance of obj as if the test method was just called and we are getting the data straight from the fixtures.

If an assert statement fails I will be able to see which one it it, but I won't be able to determine what case (state) failed because of the for loop. I can try-except the _test_obj_ call in the test method but then I wouldn't be able to tell what assert failed.

Does django.test provide any tool to run the same test for different states of the same model? If it doesn't, how can I do what I am trying to do while solving both points mentioned above?

答:
Simply rollback after you're done with the object.

You can use the new subTest in python 3.4+

Here's how your code should look:

```<code>class TestProductApp(TestCase):
    def setUp(self):
        self.product1 = ...

    def test_multistate(self):
        state1 = dict(name='p1')
        state2 = dict(name='p2')

        data = [state1, state2]

        for i, state in enumerate(data):
            with self.subTest(i=i):
                try:
                    with transaction.atomic():
                        product = Product.objects.get(id=self.product1.id)
                        product.name = state['name']
                        product.save()
                        self.assertEqual(len(product.name), 2)
                        raise DatabaseError #forces a rollback
                except DatabaseError:
                    pass
                print(Product.objects.get(id=self.product1.id)) #prints data created in setUp/fixture
</code>```

Body:
I am trying to run the same exact test on a single obj which is a models.Model instance and has some relations with other models. I do not want to persist changes in that instance, so effectively I want the same effect of the tearDown method which rollbacks transactions.

To illustrate this:

class MyTestCase(django.test.TestCase):

    def test():
        # main test that calls the same test using all
        # different states of `obj` that need to be tested

        # different values of data that update the state of `obj`
        # with state I simply mean the values of `obj`'s attributes and relationships
        data = [state1, state2, state3]
        for state in data:
            obj = Obj.objects.get(pk=self.pk)  # gets that SINGLE object from the test db
            # applies the state data to `obj` to change its state
            obj.update(state)
            # performs the actual test on `obj` with this particular state
            self._test_obj(obj)

    def _test_obj(self, obj):
        self.assertEqual(len(obj.vals), 10)
        self.assertLess(obj.threshold, 99)
        # more assert statements...

This design has two problems:

The changes on obj persist on the test database, so on the next iteration the data would be tainted. I would want to rollback those changes and get a fresh instance of obj as if the test method was just called and we are getting the data straight from the fixtures.

If an assert statement fails I will be able to see which one it it, but I won't be able to determine what case (state) failed because of the for loop. I can try-except the _test_obj_ call in the test method but then I wouldn't be able to tell what assert failed.

Does django.test provide any tool to run the same test for different states of the same model? If it doesn't, how can I do what I am trying to do while solving both points mentioned above?

Body:
Simply rollback after you're done with the object.

You can use the new subTest in python 3.4+

Here's how your code should look:

class TestProductApp(TestCase):
    def setUp(self):
        self.product1 = ...

    def test_multistate(self):
        state1 = dict(name='p1')
        state2 = dict(name='p2')

        data = [state1, state2]

        for i, state in enumerate(data):
            with self.subTest(i=i):
                try:
                    with transaction.atomic():
                        product = Product.objects.get(id=self.product1.id)
                        product.name = state['name']
                        product.save()
                        self.assertEqual(len(product.name), 2)
                        raise DatabaseError #forces a rollback
                except DatabaseError:
                    pass
                print(Product.objects.get(id=self.product1.id)) #prints data created in setUp/fixture


问:
How to call another intent without prompting to user in Lex?
Is it possible to trigger intent-B from the lambda function of intent-A without prompting to user?

Suppose user typed something and an intent-A is fired, after some processing I want to trigger some other intent i.e intent-B.

User can also directly trigger intent-B through specific utterances.
Any help is appreciated.

答:
Yes it is possible .From the lambda of Intent-A , you can write the below code :

```<code>        intentRequest.currentIntent.name='Intent-B';
        var param1={
                slot-B:null
            };
            intentRequest.currentIntent.slots=param1;
          callback(elicitSlot(outputSessionAttributes, 'Intent-B', intentRequest.currentIntent.slots, 'slot-B'));
</code>```

Below is the function for  elicitSlot

```<code>function elicitSlot(sessionAttributes, intentName, slots, slotToElicit, message) {
return {
    sessionAttributes,
    dialogAction: {
        type: 'ElicitSlot',
        intentName,
        slots,
        slotToElicit,
        message,
    },
};
</code>```

}

Body:
Yes it is possible .From the lambda of Intent-A , you can write the below code :

        intentRequest.currentIntent.name='Intent-B';
        var param1={
                slot-B:null
            };
            intentRequest.currentIntent.slots=param1;
          callback(elicitSlot(outputSessionAttributes, 'Intent-B', intentRequest.currentIntent.slots, 'slot-B'));

Below is the function for  elicitSlot

function elicitSlot(sessionAttributes, intentName, slots, slotToElicit, message) {
return {
    sessionAttributes,
    dialogAction: {
        type: 'ElicitSlot',
        intentName,
        slots,
        slotToElicit,
        message,
    },
};

}


问:
Modifiying Sublime Text Syntax Highlighting for HTML Tags
I've tried numerous colour schemes for Sublime Text 2 and I've found a number that look great for javascript and php, but they also have terrible distinction between text and tags in HTML.

What I'm looking to do is make HTML tags the same colour as the beginning and end tag (<>). Right now the left and right chevrons appear the same colour as plain text, which can be dizzying to read.

Colour scheme Frontier

Realizing it's not the colour scheme but the syntax definitions for HTML, I looked in ~/Library/Application Support/Sublime Text 2/Packages/HTML/HTML.tmLanguage to make the modification.

Problem is, the XML file is littered with > and < and no documentation for the file itself other than the unofficial documentation for syntax definitions. Anyone know how I could merge the beginning and end tag definitions to be the same as the tags themselves?

The other option, of course, it to edit each theme I like and make sure the tags and the chrevrons are coloured the same, but I figured a global edit would make more sense in my case.

Colour scheme Phoenix Dark Blue

For example, Phoenix Dark Blue solves this problem by using the following definition,

```<code><dict>
    <key>name</key>
    <string>Variable, String Link, Tag Name</string>
    <key>scope</key>
    <string>variable, support.other.variable, string.other.link, entity.name.tag, entity.other.attribute-name, meta.tag, declaration.tag</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#787878</string>
    </dict>
</dict>
</code>```

答:
ST2 is no longer supported (or running, as far as I know). Here is a quick ST3 solution.

To customize colors of 'tag' angle brackets, you must create a dict scope for tag activity, with foreground key and color string. Here is the correct syntax.

```<code><dict>
<key>name</key>
<string>tag</string>
<key>scope</key>
<string>entity.name.tag, punctuation.definition.tag.begin, punctuation.definition.tag.end</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#CCCCAA</string> <!-- custom tag color here -->
</dict>
</dict>
</code>```

This scope is explained here.

More scopes to explore here.

Body:
I've tried numerous colour schemes for Sublime Text 2 and I've found a number that look great for javascript and php, but they also have terrible distinction between text and tags in HTML.

What I'm looking to do is make HTML tags the same colour as the beginning and end tag (<>). Right now the left and right chevrons appear the same colour as plain text, which can be dizzying to read.

Colour scheme Frontier

Realizing it's not the colour scheme but the syntax definitions for HTML, I looked in ~/Library/Application Support/Sublime Text 2/Packages/HTML/HTML.tmLanguage to make the modification.

Problem is, the XML file is littered with > and < and no documentation for the file itself other than the unofficial documentation for syntax definitions. Anyone know how I could merge the beginning and end tag definitions to be the same as the tags themselves?

The other option, of course, it to edit each theme I like and make sure the tags and the chrevrons are coloured the same, but I figured a global edit would make more sense in my case.

Colour scheme Phoenix Dark Blue

For example, Phoenix Dark Blue solves this problem by using the following definition,

<dict>
    <key>name</key>
    <string>Variable, String Link, Tag Name</string>
    <key>scope</key>
    <string>variable, support.other.variable, string.other.link, entity.name.tag, entity.other.attribute-name, meta.tag, declaration.tag</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#787878</string>
    </dict>
</dict>

Body:
ST2 is no longer supported (or running, as far as I know). Here is a quick ST3 solution.

To customize colors of 'tag' angle brackets, you must create a dict scope for tag activity, with foreground key and color string. Here is the correct syntax.

<dict>
<key>name</key>
<string>tag</string>
<key>scope</key>
<string>entity.name.tag, punctuation.definition.tag.begin, punctuation.definition.tag.end</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#CCCCAA</string> <!-- custom tag color here -->
</dict>
</dict>

This scope is explained here.

More scopes to explore here.


问:
A charset problem about parsing HTML with lxml.html
I've being trying to parse an html page in Python using lxml.html.

I used the following code:

```<code>import lxml.html as H
page = open('page.html', 'r').read()
doc = H.fromstring(page)
print H.tostring(doc)
</code>```

The page.html is a web page I downloaded with a proxy program I wrote before which do some work about using proxy and encoding transfer. The encoding of the file has been changed to  utf-8 while the charset declaration in the page is like this:

```<code><meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</code>```

btw, gb2312 is a kind of Chinese character set.

At first, I ran the above python code, but it printed nothing but an empty html structure which is wrong and not what I wanted.

I tried some ways and at last I found the problem happened because of the charset declaration: when I replaced the 'charset=gb2312' with an empty string, the parsing code worked as I expected.

But I don't quite understand why this happen. And is the way I solved the problem the right method or just a coincidence?

答:
http://lxml.de/parsing.html#python-unicode-strings says:

You should generally avoid converting
  XML/HTML data to unicode before
  passing it into the parsers. It is
  both slower and error prone.

Body:
I've being trying to parse an html page in Python using lxml.html.

I used the following code:

import lxml.html as H
page = open('page.html', 'r').read()
doc = H.fromstring(page)
print H.tostring(doc)

The page.html is a web page I downloaded with a proxy program I wrote before which do some work about using proxy and encoding transfer. The encoding of the file has been changed to  utf-8 while the charset declaration in the page is like this:

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

btw, gb2312 is a kind of Chinese character set.

At first, I ran the above python code, but it printed nothing but an empty html structure which is wrong and not what I wanted.

I tried some ways and at last I found the problem happened because of the charset declaration: when I replaced the 'charset=gb2312' with an empty string, the parsing code worked as I expected.

But I don't quite understand why this happen. And is the way I solved the problem the right method or just a coincidence?


答:
Easy peasy...

```<code>c = [i for i in set(a) if i in b]
</code>```

the set(a) call eliminates any dups in the first list, and that takes care of the entire answer.  This uses what's known as "list comprehension," which makes for very concise but powerful code.

Title: I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)

Body:
Easy peasy...

c = [i for i in set(a) if i in b]

the set(a) call eliminates any dups in the first list, and that takes care of the entire answer.  This uses what's known as "list comprehension," which makes for very concise but powerful code.


问:
moving to httpClient from http throwing error in angular 5
I am trying to create new wrapper for restservice, i am trying to move angular 4 to 5 and upgrading the same service. i get error like below. If i change Observable<Response> to Observable<HttpResponse> also i get error:

Argument of type 'HttpHeaders' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

  Property 'headers' is private in type 'HttpHeaders' but not in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?:

below is code.

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpRequest, HttpHeaders, HttpResponse } from '@angular/common/http';

@Injectable()
export class httpService {
    private requestHeaders: HttpHeaders;

    constructor(private _http: HttpClient) {
        this.requestHeaders = new HttpHeaders();
        this.requestHeaders.append('Content-Type', 'application/json');
        this.requestHeaders.append('Accept', 'application/json');
    }

    post(url: string, requestData?: any): Observable<Response> {
        return this._http.post(url, requestData, this.requestHeaders);
    }
}
</code>```

Above is fixed by using {headers: this.requestHeaders}

but while line  return this._http.post(url, requestData, this.requestHeaders); throws error like

```<code>Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<Response>'.
Type 'ArrayBuffer' is not assignable to type 'Response'.
Property 'body' is missing in type 'ArrayBuffer'.
</code>```

答:
headers is only one parameter of the options, so you should be passing in

```<code>{headers: this.requestHeaders}
</code>```

This will also fix the Property 'headers' is private... error you are seeing.

Also, HttpHeaders is immutable. So every mutation operator returns a new instance. This means to properly set the headers you will need to do

```<code>this.requestHeaders = new HttpHeaders()
    .append('Content-Type', 'application/json')
    .append('Accept', 'application/json');
</code>```

or

```<code>this.requestHeaders = new HttpHeaders();
this.requestHeaders = this.requestHeaders.append('Content-Type', 'application/json');
this.requestHeaders = this.requestHeaders.append('Accept', 'application/json');
</code>```

Updated:

So the post observable is returning of type Observable<ArrayBuffer> but your method is declared to return type Observable<Response> causing the type mismatch. The HttpClient expects you to pass in the return type to the method this.http.post<YourResponseType>(...) (or it will assume the return type). So your method should be updated to

```<code>post<T>(url: string, requestData?: any): Observable<T> {
    return this.http.post<T>(url, requestData, {headers: this.requestHeaders});
}
</code>```

where T is the response type. Now the http method is expecting to return type Observable<T> and your post method is returning type Observable<T>. The types match. You would use your method like so

```<code>this.post<MyResponse>(myUrl, myRequestData).subscribe(...);
</code>```

Body:
I am trying to create new wrapper for restservice, i am trying to move angular 4 to 5 and upgrading the same service. i get error like below. If i change Observable<Response> to Observable<HttpResponse> also i get error:

Argument of type 'HttpHeaders' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

  Property 'headers' is private in type 'HttpHeaders' but not in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?:

below is code.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpRequest, HttpHeaders, HttpResponse } from '@angular/common/http';

@Injectable()
export class httpService {
    private requestHeaders: HttpHeaders;

    constructor(private _http: HttpClient) {
        this.requestHeaders = new HttpHeaders();
        this.requestHeaders.append('Content-Type', 'application/json');
        this.requestHeaders.append('Accept', 'application/json');
    }

    post(url: string, requestData?: any): Observable<Response> {
        return this._http.post(url, requestData, this.requestHeaders);
    }
}

Above is fixed by using {headers: this.requestHeaders}

but while line  return this._http.post(url, requestData, this.requestHeaders); throws error like

Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<Response>'.
Type 'ArrayBuffer' is not assignable to type 'Response'.
Property 'body' is missing in type 'ArrayBuffer'.

Body:
headers is only one parameter of the options, so you should be passing in

{headers: this.requestHeaders}

This will also fix the Property 'headers' is private... error you are seeing.

Also, HttpHeaders is immutable. So every mutation operator returns a new instance. This means to properly set the headers you will need to do

this.requestHeaders = new HttpHeaders()
    .append('Content-Type', 'application/json')
    .append('Accept', 'application/json');

or

this.requestHeaders = new HttpHeaders();
this.requestHeaders = this.requestHeaders.append('Content-Type', 'application/json');
this.requestHeaders = this.requestHeaders.append('Accept', 'application/json');

Updated:

So the post observable is returning of type Observable<ArrayBuffer> but your method is declared to return type Observable<Response> causing the type mismatch. The HttpClient expects you to pass in the return type to the method this.http.post<YourResponseType>(...) (or it will assume the return type). So your method should be updated to

post<T>(url: string, requestData?: any): Observable<T> {
    return this.http.post<T>(url, requestData, {headers: this.requestHeaders});
}

where T is the response type. Now the http method is expecting to return type Observable<T> and your post method is returning type Observable<T>. The types match. You would use your method like so

this.post<MyResponse>(myUrl, myRequestData).subscribe(...);


问:
How to repeat sequence when condition is met
I have found variations of this question, and I know modulos can possibly be used but I am having a difficult time putting it all together.

I have a sequence of observations by ID and seconds. When the cumulitive amount of seconds by id increments greater than 5 seconds, I would like to restart the count. Could someone help me answer this question in dplyr?

Original df

```<code>df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df
   id val
1   1   2
2   1  10
3   1  12
4   1  15
5   1  17
6   2   2
7   2   4
8   2   7
9   2   8
10  3  12
11  3  15
12  3  20
13  3  25
</code>```

Desired Outcome

```<code>finalResult
   id val reset
1   1   2     1
2   1  10     2
3   1  12     2
4   1  15     3
5   1  17     3
6   2   2     1
7   2   4     1
8   2   7     2
9   2   8     2
10  3  12     1
11  3  15     1
12  3  20     2
13  3  25     3
</code>```

Edit

Thanks for the responses yesterday but I encountered some problems with the given solutions.

On this data set the code works on some instances.

```<code>sub.df <- structure(list(`ID` = c("1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1"
), dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061
), class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), .Names = c("ID",
                                                                           "dateFormat"), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))
</code>```

Solution Used:

```<code>jj <- sub.df %>%
  group_by(`ID`) %>%
  arrange(`ID`,`dateFormat`)%>%
  mutate(totalTimeInt = difftime(dateFormat,first(dateFormat),units = 'secs'))%>%
  mutate(totalTimeFormat   = as.numeric(totalTimeInt))%>%
  mutate(reset = cumsum(
    Reduce(
      function(x, y)
        if (x + y >= 5) 0
        else x + y,

        diff(totalTimeFormat), init = 0, accumulate = TRUE
    ) == 0
  ))%>%
  mutate(reset_2 = cumsum(
    accumulate(
      diff(totalTimeFormat),
      ~if (.x + .y >= 5) 0 else .x + .y,
      .init = 0
    ) == 0
  ))
</code>```

Outcome

```<code># A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     3       3
5     1 2017-01-06 05:55:13  9680654 secs         9680654     4       4
6     1 2017-05-19 05:46:49 21167750 secs        21167750     5       5
7     1 2017-05-19 05:46:49 21167750 secs        21167750     6       6
8     1 2017-06-12 05:57:59 23242020 secs        23242020     7       7
9     1 2017-06-12 05:57:59 23242020 secs        23242020     8       8
</code>```

What happens is that for the first two observation it correctly counts that as 1 instance. When it reaches the third and fourth observation this should only be counted as two observations as there was essentially no time that passed between those two instances.

Correct Output:

```<code># A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
5     1 2017-01-06 05:55:13  9680654 secs         9680654     3       3
6     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
7     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
8     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
9     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
</code>```

答:
I might be wrong (EDIT: I was proven wrong, by alistaire's brilliant answer, though I'm leaving this approach here for now), but I think this is one of the instances where you actually need a loop because the value of reset in each row is going to depend on what happened for previous rows. I'm hopeful Joseph Wood will come up with something smarter than this, but in the meantime here is a naive approach, which utilizes dplyr as requested. We can make the following function

```<code>count_resets <- function(x) {
    N <- length(x)
    value <- 1
    result <- rep(1, N)
    threshold <- x[1]
    for ( i in 2:N ) {
        if ( abs(x[i] - threshold) >= 5) {
            value <- value + 1
            threshold <- x[i]
        }
        result[i] <- value
    }
    return(result)
}
</code>```

And apply it by id using dplyr's group_by():

```<code>library(dplyr)

df %>%
    group_by(id) %>%
    mutate(reset = count_resets(val))

# A tibble: 13 x 3
# Groups:   id [3]
      id   val reset
   <dbl> <dbl> <dbl>
 1     1     2     1
 2     1    10     2
 3     1    12     2
 4     1    15     3
 5     1    17     3
 6     2     2     1
 7     2     4     1
 8     2     7     2
 9     2     8     2
10     3    12     1
11     3    15     1
12     3    20     2
13     3    25     3
</code>```

Body:
I have found variations of this question, and I know modulos can possibly be used but I am having a difficult time putting it all together.

I have a sequence of observations by ID and seconds. When the cumulitive amount of seconds by id increments greater than 5 seconds, I would like to restart the count. Could someone help me answer this question in dplyr?

Original df

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3),
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df
   id val
1   1   2
2   1  10
3   1  12
4   1  15
5   1  17
6   2   2
7   2   4
8   2   7
9   2   8
10  3  12
11  3  15
12  3  20
13  3  25

Desired Outcome

finalResult
   id val reset
1   1   2     1
2   1  10     2
3   1  12     2
4   1  15     3
5   1  17     3
6   2   2     1
7   2   4     1
8   2   7     2
9   2   8     2
10  3  12     1
11  3  15     1
12  3  20     2
13  3  25     3

Edit

Thanks for the responses yesterday but I encountered some problems with the given solutions.

On this data set the code works on some instances.

sub.df <- structure(list(`ID` = c("1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1",
                                                "1", "1"
), dateFormat = structure(c(1479955726, 1479955726, 1483703713,
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061
), class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), .Names = c("ID",
                                                                           "dateFormat"), row.names = c(NA, -9L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

Solution Used:

jj <- sub.df %>%
  group_by(`ID`) %>%
  arrange(`ID`,`dateFormat`)%>%
  mutate(totalTimeInt = difftime(dateFormat,first(dateFormat),units = 'secs'))%>%
  mutate(totalTimeFormat   = as.numeric(totalTimeInt))%>%
  mutate(reset = cumsum(
    Reduce(
      function(x, y)
        if (x + y >= 5) 0
        else x + y,

        diff(totalTimeFormat), init = 0, accumulate = TRUE
    ) == 0
  ))%>%
  mutate(reset_2 = cumsum(
    accumulate(
      diff(totalTimeFormat),
      ~if (.x + .y >= 5) 0 else .x + .y,
      .init = 0
    ) == 0
  ))

Outcome

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     3       3
5     1 2017-01-06 05:55:13  9680654 secs         9680654     4       4
6     1 2017-05-19 05:46:49 21167750 secs        21167750     5       5
7     1 2017-05-19 05:46:49 21167750 secs        21167750     6       6
8     1 2017-06-12 05:57:59 23242020 secs        23242020     7       7
9     1 2017-06-12 05:57:59 23242020 secs        23242020     8       8

What happens is that for the first two observation it correctly counts that as 1 instance. When it reaches the third and fourth observation this should only be counted as two observations as there was essentially no time that passed between those two instances.

Correct Output:

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
5     1 2017-01-06 05:55:13  9680654 secs         9680654     3       3
6     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
7     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
8     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
9     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5

Body:
I might be wrong (EDIT: I was proven wrong, by alistaire's brilliant answer, though I'm leaving this approach here for now), but I think this is one of the instances where you actually need a loop because the value of reset in each row is going to depend on what happened for previous rows. I'm hopeful Joseph Wood will come up with something smarter than this, but in the meantime here is a naive approach, which utilizes dplyr as requested. We can make the following function

count_resets <- function(x) {
    N <- length(x)
    value <- 1
    result <- rep(1, N)
    threshold <- x[1]
    for ( i in 2:N ) {
        if ( abs(x[i] - threshold) >= 5) {
            value <- value + 1
            threshold <- x[i]
        }
        result[i] <- value
    }
    return(result)
}

And apply it by id using dplyr's group_by():

library(dplyr)

df %>%
    group_by(id) %>%
    mutate(reset = count_resets(val))

# A tibble: 13 x 3
# Groups:   id [3]
      id   val reset
   <dbl> <dbl> <dbl>
 1     1     2     1
 2     1    10     2
 3     1    12     2
 4     1    15     3
 5     1    17     3
 6     2     2     1
 7     2     4     1
 8     2     7     2
 9     2     8     2
10     3    12     1
11     3    15     1
12     3    20     2
13     3    25     3


问:
How to perform double sort inside an array?
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

```<code>class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1
</code>```

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

```<code>bar.sort(key=foo.sort,reverse=True)
</code>```

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

```<code>foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2
</code>```

How can I do this?

答:
```<code>bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)
</code>```

And you don't need to define foo.sort

Body:
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

bar.sort(key=foo.sort,reverse=True)

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2

How can I do this?

Body:
bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)

And you don't need to define foo.sort


问:
Is there a SQL Server collation option that will allow matching different apostrophes?
I'm currently using SQL Server 2016 with SQL_Latin1_General_CP1_CI_AI collation.  As expected, queries with the letter e will match values with the letters e, è, é, ê, ë, etc because of the accent insensitive option of the collation.  However, queries with a ' (U+0027) do not match values containing a ’ (U+2019). I would like to know if such a collation exists where this case would match, since it's easier to type ' than it is to know that ’ is keystroke Alt-0146.</p>

答:
The other answer is correct. There is no such collation. You can easily verify this with the below.</p>

```<code>DECLARE @dynSql NVARCHAR(MAX) =
'SELECT * FROM ('  +
(
SELECT SUBSTRING(
(
SELECT ' UNION ALL SELECT ''' + name + ''' AS name, IIF( NCHAR(0x0027) = NCHAR(0x2019) COLLATE ' + name + ', 1,0) AS Equal'
FROM sys.fn_helpcollations()
FOR XML PATH('')
), 12, 0+ 0x7fffffff)
)
 + ') t
 ORDER BY Equal, name';

PRINT @dynSql;

EXEC (@dynSql);
</code>```

Body:
The other answer is correct. There is no such collation. You can easily verify this with the below.

DECLARE @dynSql NVARCHAR(MAX) =
'SELECT * FROM ('  +
(
SELECT SUBSTRING(
(
SELECT ' UNION ALL SELECT ''' + name + ''' AS name, IIF( NCHAR(0x0027) = NCHAR(0x2019) COLLATE ' + name + ', 1,0) AS Equal'
FROM sys.fn_helpcollations()
FOR XML PATH('')
), 12, 0+ 0x7fffffff)
)
 + ') t
 ORDER BY Equal, name';

PRINT @dynSql;

EXEC (@dynSql);


问:
select query call a function which return varray in Oracle
I want to create a function which return VArray and populate the values in select query.

My VArray is:

```<code>create  type array_squad_t is varray(2) of VARCHAR2(200);
</code>```

My function is

```<code>CREATE OR REPLACE FUNCTION test_varray(
  id number
  )
    RETURN array_squad_t
IS
    v_array array_squad_t;
BEGIN
  v_array(1) := '1 Val';
  v_array(2) := '2 Val';
    RETURN v_array;
END;
</code>```

I want to call it like

```<code>SELECT column_value1, column_value2, e.Name FROM employees e, TABLE ( test_varray(1) );
</code>```

Expected Result:

```<code>column_value1 | column_value2 | Name
1 Val         | 2 Val         | SomeName
</code>```

答:
Firstly, you must initialize your collection appropriately with a constructor array_squad_t().

```<code>CREATE OR REPLACE FUNCTION test_varray(
  id number
  )
    RETURN array_squad_t
IS
    v_array array_squad_t := array_squad_t() ;
BEGIN
  v_array.extend(2);
  v_array(1) := '1 Val';
  v_array(2) := '2 Val';
    RETURN v_array;
END;
</code>```

You can then use the TABLE function and column_value to fetch from the varray in a select statement like this.

```<code>SELECT
    column_value,
    e.*
FROM
    employees e,
    TABLE ( test_varray(1) );
</code>```

Body:
I want to create a function which return VArray and populate the values in select query.

My VArray is:

create  type array_squad_t is varray(2) of VARCHAR2(200);

My function is

CREATE OR REPLACE FUNCTION test_varray(
  id number
  )
    RETURN array_squad_t
IS
    v_array array_squad_t;
BEGIN
  v_array(1) := '1 Val';
  v_array(2) := '2 Val';
    RETURN v_array;
END;

I want to call it like

SELECT column_value1, column_value2, e.Name FROM employees e, TABLE ( test_varray(1) );

Expected Result:

column_value1 | column_value2 | Name
1 Val         | 2 Val         | SomeName

Body:
Firstly, you must initialize your collection appropriately with a constructor array_squad_t().

CREATE OR REPLACE FUNCTION test_varray(
  id number
  )
    RETURN array_squad_t
IS
    v_array array_squad_t := array_squad_t() ;
BEGIN
  v_array.extend(2);
  v_array(1) := '1 Val';
  v_array(2) := '2 Val';
    RETURN v_array;
END;

You can then use the TABLE function and column_value to fetch from the varray in a select statement like this.

SELECT
    column_value,
    e.*
FROM
    employees e,
    TABLE ( test_varray(1) );


问:
What is difference btw Pandas/Numpy datetime64 and datetime64[ns]
What is the difference between Pandas/Numpy datetime64 and datetime64[ns]? Also, how do you select a Pandas DataFrame column with dtype datetime64[ns]?

I tried the following:

```<code>for col in df.columns:
   if (df[col].dtype == np.datetime64[ns]): #If column has dtype datetime64[ns]
       print(col)
       function(df[col]) ##apply a function to this column
## RESULT: NameError: name 'ns' is not defined
## If I try == np.datetime64, nothing gets printed.
</code>```

I also tried:

```<code>for col in df.columns:
   if (df[col].dtype == 'datetime64[ns]'):
       print(col)
       function(df[col])
## RESULT: This works but it also print Columns with dtype object.
</code>```

What can I do to select only columns that have dtype datetime64[ns]?

答:
Use select_dtypes.
Consider this df

```<code>df = pd.DataFrame({'date1': pd.date_range(end = dt.datetime.today(), periods = 2), \
'date2': pd.date_range(end = dt.datetime.today(), periods = 2),\
'val1': np.arange(2),'bool': [True, False]})
</code>```

df.dtypes

```<code>bool               bool
date1    datetime64[ns]
date2    datetime64[ns]
val1              int64
</code>```

You can use select_dtypes to select datetime,

```<code>df_new = df.select_dtypes(include = ['datetime'])
</code>```

You get

```<code>    date1                       date2
0   2017-12-05 11:02:05.580203  2017-12-05 11:02:05.580889
1   2017-12-06 11:02:05.580203  2017-12-06 11:02:05.580889
</code>```

Body:
What is the difference between Pandas/Numpy datetime64 and datetime64[ns]? Also, how do you select a Pandas DataFrame column with dtype datetime64[ns]?

I tried the following:

for col in df.columns:
   if (df[col].dtype == np.datetime64[ns]): #If column has dtype datetime64[ns]
       print(col)
       function(df[col]) ##apply a function to this column
## RESULT: NameError: name 'ns' is not defined
## If I try == np.datetime64, nothing gets printed.

I also tried:

for col in df.columns:
   if (df[col].dtype == 'datetime64[ns]'):
       print(col)
       function(df[col])
## RESULT: This works but it also print Columns with dtype object.

What can I do to select only columns that have dtype datetime64[ns]?

Body:
Use select_dtypes.
Consider this df

df = pd.DataFrame({'date1': pd.date_range(end = dt.datetime.today(), periods = 2), \
'date2': pd.date_range(end = dt.datetime.today(), periods = 2),\
'val1': np.arange(2),'bool': [True, False]})

df.dtypes

bool               bool
date1    datetime64[ns]
date2    datetime64[ns]
val1              int64

You can use select_dtypes to select datetime,

df_new = df.select_dtypes(include = ['datetime'])

You get

    date1                       date2
0   2017-12-05 11:02:05.580203  2017-12-05 11:02:05.580889
1   2017-12-06 11:02:05.580203  2017-12-06 11:02:05.580889


问:
List<Object> passed from view to controller becomes an empty List<object>
I'm building a IMDb like ASP.Net website, I want to pass the List of crew members to a different view where I can edit them. However when the List is passed from the Film view to the FilmCastEdit action in FilmController the List count is 0. Am I doing this wrong? another option is to run a new sql query when the FIlmCastEdit is called but seeing the list of people I need is already there I thought this way would be better.

Film view

```<code>@if (IngelogdeGebruiker != null && IngelogdeGebruiker.TypeOfUser == UserTypeEnum.Moderator)
{
    @Html.ActionLink("Edit", "FilmCastEdit", "Film", new { castList = Model.Crew }, null)
}
</code>```

Film controller

```<code>public ActionResult FilmCastEdit(List<Person> castList)
{

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

Debug view of Film view to Film controller
https://gyazo.com/eb5511ab4154256505aa87403f79f485

 In the Film view Model.Crew count is 5 as you can see

https://gyazo.com/d53df971450865f73c6662da08cfc8f0

 but castList here has a count of 0

If I didn't clarify something important please let me know, I have no clue why this isn't working.

答:
You need a submit/post in order for MVC to do a complex model bind like that, an ActionLink appends the data as a query string so it will only bind on the controller side with multiple individual named/typed fields. Your controller is set up as a post correctly but the actionlink is not a post.

Cheat and create a mini hidden form to submit with that data, set up an ajax post, or send it as a JSON string. There are a number of ways to do this. See:

https://stackoverflow.com/a/26528113/466245

Body:
I'm building a IMDb like ASP.Net website, I want to pass the List of crew members to a different view where I can edit them. However when the List is passed from the Film view to the FilmCastEdit action in FilmController the List count is 0. Am I doing this wrong? another option is to run a new sql query when the FIlmCastEdit is called but seeing the list of people I need is already there I thought this way would be better.

Film view

@if (IngelogdeGebruiker != null && IngelogdeGebruiker.TypeOfUser == UserTypeEnum.Moderator)
{
    @Html.ActionLink("Edit", "FilmCastEdit", "Film", new { castList = Model.Crew }, null)
}

Film controller

public ActionResult FilmCastEdit(List<Person> castList)
{

    return View(castList);
}

Debug view of Film view to Film controller
https://gyazo.com/eb5511ab4154256505aa87403f79f485

 In the Film view Model.Crew count is 5 as you can see

https://gyazo.com/d53df971450865f73c6662da08cfc8f0

 but castList here has a count of 0

If I didn't clarify something important please let me know, I have no clue why this isn't working.


问:
scala: Dynamically filtering with predicates
I have a Map[String, Int]

```<code>val labelMap: mutable.HashMap[String, Int] = sparse0.sparseOperationCountRowsByTarget()
</code>```

I want to filter that map in one statement. The filter may filter both by String or Int

In crudest form it looks like this:

```<code> val labelMapFiltered = labelMap.filter(label => label._1.startsWith("REL") || label._2 < 400)
</code>```

Now I already have general utility predicates for String and Int functions. String predicates are:

```<code>object StringPredicates
{
  def stringEquals(required:String)(input:String) = input == required
  def stringStartsWith(required:String)(input:String) = input.startsWith(required)
  def stringContains(required:String)(input:String) = input.contains(required)

  def and(predicates:Seq[String => Boolean])(input:String) = predicates.forall(predicate => predicate(input))
  def or(predicates:Seq[String => Boolean])(input:String) = predicates.exists(predicate => predicate(input))
}
</code>```

Int predicates are same pattern as above.

This allows for the following filter:

```<code>val sw1=stringContains("#")
val sw2=stringStartsWith("REL")
val sw3=intGT(400)

      val labelMapFiltered = labelMap.filter( label =>sw1(label._1) || sw2(label._1) || sw3(label._2) )
</code>```

I want to pass the predicates into the function (as a Seq, I assume) and then filter.
So I am looking for something like:

```<code>val labelMapFiltered = labelMap.filter( myFunction(myPredSeq))
</code>```

Can I do this using the predicates I already have? Writing predicates for Tuple2[String,Int] that match the specific Map in this function seems too specific. I would then have to write predicates for every type of Map I want to filter.

答:
You can transform your predicates into accepting the appropriate type using the compose method, e.g.:

```<code>val sw1: (String, Int) => Boolean = stringContains("#").compose(kv: (String, Int) => kv._1)
</code>```

Or even do the same but mapping over your predicates:

```<code>val predsOfTuples1 = predsOfStrings.map(_.compose(kv: (String, Int) => kv._1)))
val predsOfTuples2 = predsOfInts.map(_.compose(kv: (String, Int) => kv._2))
val preds = predsOfTuples1 ++ predsOfTuples2
</code>```

The last thing you would need to do is make your and and or methods generic so you can use them on predicates of tuples:

```<code>def and[A](predicates:Seq[A => Boolean])(input:A) = predicates.forall(predicate => predicate(input))
def or[A](predicates:Seq[A => Boolean])(input:A) = predicates.exists(predicate => predicate(input))
</code>```

Body:
I have a Map[String, Int]

val labelMap: mutable.HashMap[String, Int] = sparse0.sparseOperationCountRowsByTarget()

I want to filter that map in one statement. The filter may filter both by String or Int

In crudest form it looks like this:

 val labelMapFiltered = labelMap.filter(label => label._1.startsWith("REL") || label._2 < 400)

Now I already have general utility predicates for String and Int functions. String predicates are:

object StringPredicates
{
  def stringEquals(required:String)(input:String) = input == required
  def stringStartsWith(required:String)(input:String) = input.startsWith(required)
  def stringContains(required:String)(input:String) = input.contains(required)

  def and(predicates:Seq[String => Boolean])(input:String) = predicates.forall(predicate => predicate(input))
  def or(predicates:Seq[String => Boolean])(input:String) = predicates.exists(predicate => predicate(input))
}

Int predicates are same pattern as above.

This allows for the following filter:

val sw1=stringContains("#")
val sw2=stringStartsWith("REL")
val sw3=intGT(400)

      val labelMapFiltered = labelMap.filter( label =>sw1(label._1) || sw2(label._1) || sw3(label._2) )

I want to pass the predicates into the function (as a Seq, I assume) and then filter.
So I am looking for something like:

val labelMapFiltered = labelMap.filter( myFunction(myPredSeq))

Can I do this using the predicates I already have? Writing predicates for Tuple2[String,Int] that match the specific Map in this function seems too specific. I would then have to write predicates for every type of Map I want to filter.

Body:
You can transform your predicates into accepting the appropriate type using the compose method, e.g.:

val sw1: (String, Int) => Boolean = stringContains("#").compose(kv: (String, Int) => kv._1)

Or even do the same but mapping over your predicates:

val predsOfTuples1 = predsOfStrings.map(_.compose(kv: (String, Int) => kv._1)))
val predsOfTuples2 = predsOfInts.map(_.compose(kv: (String, Int) => kv._2))
val preds = predsOfTuples1 ++ predsOfTuples2

The last thing you would need to do is make your and and or methods generic so you can use them on predicates of tuples:

def and[A](predicates:Seq[A => Boolean])(input:A) = predicates.forall(predicate => predicate(input))
def or[A](predicates:Seq[A => Boolean])(input:A) = predicates.exists(predicate => predicate(input))


问:
How to query database for case sensitive values
I'm checking a few values in my database and it appears that the strings being compared are not being case sensitive enforced. I'm using C# and LINQ to SQL.</p>

答:
You do not need to change your database
you can modify your queries to work case sensitive:

```<code>SET NOCOUNT ON
declare @curdb sysname; select  @curdb =  db_name(0);
select  DATABASEPROPERTYEX(@curdb, 'Collation') Collation;

if object_id('test_CI', 'U') is not null
    drop table test_CI
go

create table test_CI (
    val varchar(10)
    );
go
insert into test_CI values ('TEST');
insert into test_CI values ('Test');
insert into test_CI values ('test');

--
select * from test_CI where val = 'Test';

select * from test_CI where val collate Latin1_General_CS_AS = 'Test';
</code>```

Just use your current sort order and replace the CI by CS.

Body:
You do not need to change your database
you can modify your queries to work case sensitive:

SET NOCOUNT ON
declare @curdb sysname; select  @curdb =  db_name(0);
select  DATABASEPROPERTYEX(@curdb, 'Collation') Collation;

if object_id('test_CI', 'U') is not null
    drop table test_CI
go

create table test_CI (
    val varchar(10)
    );
go
insert into test_CI values ('TEST');
insert into test_CI values ('Test');
insert into test_CI values ('test');

--
select * from test_CI where val = 'Test';

select * from test_CI where val collate Latin1_General_CS_AS = 'Test';

Just use your current sort order and replace the CI by CS.


问:
Angular 2: file not found on local .json file
I have seen a few different posts about not being able to find local files to open them up whether they be images or data files, but none of the solutions have worked for me. My guess would be there is some configuration I'm missing.

The file I'm looking for is in a folder named "data" on the same level as my app.html and app.ts files.

Here is what I have in app.html, PS I'm also using Ionic2:

```<code><ion-menu (click)='getDepartments()' side='right' type='overlay' [content]="content">
</code>```

and in the app.ts file I have:

```<code>getDepartments() {
    this.http.get('/data/data.json')
        .map(res => res.json())
        .subscribe(
            data => this.departments = data,
            err => console.log(err),
            () => console.log('Random Quote Complete')
        );
}
</code>```

I've tried:

```<code>./data/data.json

data/data.json

app/data/data.json
</code>```

and any other path. And they all return a 404 file not found error. This seems just like growing pains with getting familiar with Angular 2. Thanks in advance

答:
For any anyone who is interested in resolving the same problem. If you are using Angular CLI and you want to make any folder accessible through http as in this case "data" folder.

Go to Angular-CLI.JSON  then add "the folder name" which is "data" under apps -> assets

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "data"
      ],```

Body:
I have seen a few different posts about not being able to find local files to open them up whether they be images or data files, but none of the solutions have worked for me. My guess would be there is some configuration I'm missing.

The file I'm looking for is in a folder named "data" on the same level as my app.html and app.ts files.

Here is what I have in app.html, PS I'm also using Ionic2:

<ion-menu (click)='getDepartments()' side='right' type='overlay' [content]="content">

and in the app.ts file I have:

getDepartments() {
    this.http.get('/data/data.json')
        .map(res => res.json())
        .subscribe(
            data => this.departments = data,
            err => console.log(err),
            () => console.log('Random Quote Complete')
        );
}

I've tried:

./data/data.json

data/data.json

app/data/data.json

and any other path. And they all return a 404 file not found error. This seems just like growing pains with getting familiar with Angular 2. Thanks in advance


问:
em.getTransaction().commit(); causing an error in jpa
ive been getting the following errors when trying parser a xml file to mysql database.The database is created.
I dont under stand why it cannot create the user

error code
    Console errors

Driver.java

```<code>package DAO;

import parser.XMLParser;

import java.util.ArrayList;
import java.util.List;

import entities.*;

public class NewDriver {

public static void main(String args[]) throws Exception{
    UserDAO userDAO = new UserDAO();

    ProductDAO productDAO= new ProductDAO();
    ProductOnHandDAO productOnHandDAO= new ProductOnHandDAO();
    XMLParser x = new XMLParser();

    User user1 = new User("luke", "luke");
    userDAO.createUser(user1);

    Store store = new Store();
    StoreDAO storeDAO= new StoreDAO();
    storeDAO.createStore(store);

    List<Product> products = x.getProduct("test.xml");
    for(Product p : products){
        p.setStore(store);
        productDAO.createProduct(p);
    }

    List<Product> productList = ProductDAO.findByStore(store);
    List<ProductOnHand>productOnHands;

    productOnHands = x.getAllProductOnHand(productList,"test.xml");
    for (ProductOnHand p1 : productOnHands){
        p1.setStore(store);
        ProductOnHandDAO.createProductOnHand(p1);

    }

}
}
</code>```

UserDAO.java

```<code>public class UserDAO {

 public void createUser(User user){
        PersistenceUtil.persist(user);
    }

    public List<User> findAllUsers(){
        EntityManager em = PersistenceUtil.createEM();
        List<User> users = (List<User>)
                em.createNamedQuery("User.findAllUsers").getResultList();
        em.close();
        return users;
    }

     public User findUserByUsernameAndPassword(String username, String
      password){
        EntityManager em = PersistenceUtil.createEM();
        List<User> users = (List<User>)

   em.createNamedQuery("User.findUserByUsernameAndPassword").
   setParameter("username", username).setParameter("password",
   password).getResultList();
        em.close();
        return users.get(0);
    }
 }
</code>```

User.java

```<code>@Entity
public class User {

@Id
@Column
private int id;

private String username;
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public User() {
}
}
</code>```

Persistence.util

```<code>public class PersistenceUtil implements Serializable {

private static final long serialVersionUID = 1L;

protected static EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("dt354rel");

public static void persist(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(entity);
    em.getTransaction().commit();
    em.close();
}

public static void remove(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Object mergedEntity = em.merge(entity);
    em.remove(mergedEntity);
    em.getTransaction().commit();
    em.close();
}

public static Object merge(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    entity = em.merge(entity);
    em.getTransaction().commit();
    em.close();
    return entity;
}

public static EntityManager createEM() {
    return emf.createEntityManager();
}

}
</code>```

Any help would be appricated i looked at my persistence class and it all seems fine to me.

答:
Look at the error:

```<code>Table dt354rel.user doesn't exist
</code>```

Check if this table is missing or if you don't have access to that table.

Btw. you don't have to create a new EntityManager in all that methods. You could create it once an reuse it.

Body:
ive been getting the following errors when trying parser a xml file to mysql database.The database is created.
I dont under stand why it cannot create the user

error code
    Console errors

Driver.java

package DAO;

import parser.XMLParser;

import java.util.ArrayList;
import java.util.List;

import entities.*;

public class NewDriver {

public static void main(String args[]) throws Exception{
    UserDAO userDAO = new UserDAO();

    ProductDAO productDAO= new ProductDAO();
    ProductOnHandDAO productOnHandDAO= new ProductOnHandDAO();
    XMLParser x = new XMLParser();

    User user1 = new User("luke", "luke");
    userDAO.createUser(user1);

    Store store = new Store();
    StoreDAO storeDAO= new StoreDAO();
    storeDAO.createStore(store);

    List<Product> products = x.getProduct("test.xml");
    for(Product p : products){
        p.setStore(store);
        productDAO.createProduct(p);
    }

    List<Product> productList = ProductDAO.findByStore(store);
    List<ProductOnHand>productOnHands;

    productOnHands = x.getAllProductOnHand(productList,"test.xml");
    for (ProductOnHand p1 : productOnHands){
        p1.setStore(store);
        ProductOnHandDAO.createProductOnHand(p1);

    }

}
}

UserDAO.java

public class UserDAO {

 public void createUser(User user){
        PersistenceUtil.persist(user);
    }

    public List<User> findAllUsers(){
        EntityManager em = PersistenceUtil.createEM();
        List<User> users = (List<User>)
                em.createNamedQuery("User.findAllUsers").getResultList();
        em.close();
        return users;
    }

     public User findUserByUsernameAndPassword(String username, String
      password){
        EntityManager em = PersistenceUtil.createEM();
        List<User> users = (List<User>)

   em.createNamedQuery("User.findUserByUsernameAndPassword").
   setParameter("username", username).setParameter("password",
   password).getResultList();
        em.close();
        return users.get(0);
    }
 }

User.java

@Entity
public class User {

@Id
@Column
private int id;

private String username;
private String password;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

public User() {
}
}

Persistence.util

public class PersistenceUtil implements Serializable {

private static final long serialVersionUID = 1L;

protected static EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("dt354rel");

public static void persist(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(entity);
    em.getTransaction().commit();
    em.close();
}

public static void remove(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Object mergedEntity = em.merge(entity);
    em.remove(mergedEntity);
    em.getTransaction().commit();
    em.close();
}

public static Object merge(Object entity) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    entity = em.merge(entity);
    em.getTransaction().commit();
    em.close();
    return entity;
}

public static EntityManager createEM() {
    return emf.createEntityManager();
}

}

Any help would be appricated i looked at my persistence class and it all seems fine to me.

Body:
Look at the error:

Table dt354rel.user doesn't exist

Check if this table is missing or if you don't have access to that table.

Btw. you don't have to create a new EntityManager in all that methods. You could create it once an reuse it.


问:
I want to create a program that returns a list that contains only the elements that are common between the lists (without duplicates)
Below is the code:

```<code>a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)
</code>```

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

答:
Let's expand the ideas into English:

```<code>for each of the 11 positions in a:
     grab the element in that position ...
     if that element is also in b (so it's in both a and b),
         but is not yet in c (so we get no duplicates):

         add it to c
</code>```

Does that clear up the logic for you?

Body:
Below is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []

cal = len(a)

for d in range(cal):
     if a[d] in b and a[d] not in c:
         c.append(a[d])
print(c)

Below is the output:

[1, 2, 3, 5, 8, 13]

Process finished with exit code 0

I was not able to make the logic myself so I had looked at the solution but still didn't get the concept behind the code. The point where I am getting confused is that in cal I am storing the length of a which is 11, then I am doing a for loop 11 times(I am not sure why this is being done and what will we get from this part), then then finally conditional using "a[d]". It just doesnt makes sense to me.

Body:
Let's expand the ideas into English:

for each of the 11 positions in a:
     grab the element in that position ...
     if that element is also in b (so it's in both a and b),
         but is not yet in c (so we get no duplicates):

         add it to c

Does that clear up the logic for you?