问:
ChartControl - How to plot a line on X Axis (x - fixed coordinate, y - infinity)
I'm developing a C# winforms application in which I want to plot lines on X axis such that the X coordinate is a fixed value, but there is no Y coordinate specified.
Something like this:

Can this be done?

答:
Stripline did the trick!

Here's the code:

```<code>public Series series1 = new Series
    {
        Name = "Series1",
        Color = Color.Black,
        IsVisibleInLegend = false,
        ChartType = SeriesChartType.Line,
        BorderWidth = 0,
        XValueType = ChartValueType.Double,
        YValueType = ChartValueType.Double
    };

    public StripLine startPositionLine = new StripLine
    {
        BorderColor = Color.Red,
        BorderWidth = 2,
        IntervalOffset = 7
    };

    public StripLine endPositionLine = new StripLine
    {
        BorderColor = Color.Blue,
        BorderWidth = 2,
        IntervalOffset = 11
    };

    private void Form1_Load(object sender, EventArgs e)
    {
        chart1.Series.Clear();

        chart1.ChartAreas[0].AxisX.Minimum = 0;
        chart1.ChartAreas[0].AxisX.Interval = 1;

        //Apparently some series with some points have to be present on the chart before the striplines get displayed
        series1.Points.AddXY(0, 0);
        series1.Points.AddXY(10, 0);

        chart1.Series.Add(series1);

        chart1.ChartAreas[0].AxisX.StripLines.Add(startPositionLine);
        chart1.ChartAreas[0].AxisX.StripLines.Add(endPositionLine);

        chart1.Invalidate();
    }
</code>```

And here's how the striplines are plotted:

One thing I need to check is whether or not a series needs to be plotted first before a stripline can be plotted.

Body:
Stripline did the trick!

Here's the code:

public Series series1 = new Series
    {
        Name = "Series1",
        Color = Color.Black,
        IsVisibleInLegend = false,
        ChartType = SeriesChartType.Line,
        BorderWidth = 0,
        XValueType = ChartValueType.Double,
        YValueType = ChartValueType.Double
    };

    public StripLine startPositionLine = new StripLine
    {
        BorderColor = Color.Red,
        BorderWidth = 2,
        IntervalOffset = 7
    };

    public StripLine endPositionLine = new StripLine
    {
        BorderColor = Color.Blue,
        BorderWidth = 2,
        IntervalOffset = 11
    };

    private void Form1_Load(object sender, EventArgs e)
    {
        chart1.Series.Clear();

        chart1.ChartAreas[0].AxisX.Minimum = 0;
        chart1.ChartAreas[0].AxisX.Interval = 1;

        //Apparently some series with some points have to be present on the chart before the striplines get displayed
        series1.Points.AddXY(0, 0);
        series1.Points.AddXY(10, 0);

        chart1.Series.Add(series1);

        chart1.ChartAreas[0].AxisX.StripLines.Add(startPositionLine);
        chart1.ChartAreas[0].AxisX.StripLines.Add(endPositionLine);

        chart1.Invalidate();
    }

And here's how the striplines are plotted:

One thing I need to check is whether or not a series needs to be plotted first before a stripline can be plotted.


来源: stackexchange

问:
sudo composer install vs. composer install
I run sudo composer install I got this warning

Do not run Composer as root/super user! See https://getcomposer.org/root for details

I tried just composer install I got this error

[ErrorException]
    file_put_contents(/Applications/MAMP/htdocs/code/bheng/vendor/composer/installed.json): faile
    d to open stream: Permission denied

Here is the current permission set on my Laravel folder

```<code>total 1872
-rw-r--r--   1 bheng  staff     777 Feb 27 20:18 phpunit.xml
-rw-r--r--   1 bheng  staff      87 Feb 27 20:18 phpspec.yml
-rw-r--r--   1 bheng  staff     481 Feb 27 20:18 package.json
drwxr-xr-x   3 bheng  staff     102 Feb 27 20:18 note
-rw-r--r--   1 bheng  staff     967 Feb 27 20:18 md-bheng-readme.txt
-rw-r--r--   1 bheng  staff     503 Feb 27 20:18 gulpfile.js
-rw-r--r--   1 bheng  staff      26 Feb 27 20:18 contributors.txt
-rw-r--r--   1 bheng  staff    1635 Feb 27 20:18 artisan
-rw-r--r--   1 bheng  staff      43 Feb 27 20:18 Procfile
-rw-r--r--   1 bheng  staff    5634 Feb 27 20:18 Gruntfile.js
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 tests
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 storage
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 sql
-rw-r--r--   1 bheng  staff     560 Feb 27 20:18 server.php
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 resources
-rw-r--r--   1 bheng  staff     105 Feb 27 20:18 pull.sh
drwxr-xr-x   7 bheng  staff     238 Mar  1 14:46 bootstrap
-rw-r--r--@  1 bheng  staff       0 Mar  1 14:46 Icon?
drwxr-xr-x  22 bheng  staff     748 Mar  2 11:47 app
drwxrwxrwx@ 27 bheng  staff     918 Mar  3 14:55 public
drwxr-xr-x   8 bheng  staff     272 Mar  6 13:25 database
-rw-------@  1 bheng  staff     405 Mar 14 09:29 id_rsa.pub
-rw-------   1 bheng  staff    1766 Mar 14 09:29 id_rsa
-rw-r--r--   1 bheng  staff  126713 Mar 14 10:00 composer.lock
drwxr-xr-x  18 bheng  staff     612 Mar 28 21:24 config
-rw-r--r--   1 bheng  staff    1022 Mar 30 12:21 composer.json
drwxr-xr-x  32 bheng  staff    1088 Mar 30 12:21 vendor
</code>```

Here is what inside my composer.json

```<code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "laravel/framework": "5.1.0",
    "intervention/image": "^2.3",
    "laravelcollective/remote": "5.1.*",
    "doctrine/dbal": "^2.3",
    "league/flysystem-sftp": "^1.0"
    },
    "require-dev": {
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
        },
        "autoload": {
            "classmap": [ "database" ],

            "psr-4": {
                "App\\": "app/"
            }
            },
            "autoload-dev": {
                "classmap": [
                "tests/TestCase.php"
                ]
                },
                "scripts": {
                    "post-install-cmd": [
                    "php artisan clear-compiled",
                    "php artisan optimize"
                    ],
                    "post-update-cmd": [
                    "php artisan clear-compiled",
                    "php artisan optimize"
                    ],
                    "post-create-project-cmd": [
                    "php -r \"copy('.env.example', '.env');\"",
                    "php artisan key:generate"
                    ]
                    },
                    "config": {
                        "preferred-install": "dist"
                    }
                }
</code>```

How do I fix this ? Do I need to chmod any folders ?

答:
Delete your vendor directory and run composer install again.

You're getting the permission denied error because the vendor/composer/installed.json file was created by the root user when you ran sudo composer install, so now when you run composer install your user doesn't have permission to edit that file.

Update:

If you are working within a live document root (you shouldn't be - read up on atomic deployment) then you can try chown on the vendor directory and its contents to avoid any downtime between the deletion and re-running composer install:

```<code>$ sudo chown -R myuser: vendor/
</code>```

Replace myuser with your username.

ContentLicense: CC BY-SA 3.0

Body:
I run sudo composer install I got this warning

Do not run Composer as root/super user! See https://getcomposer.org/root for details

I tried just composer install I got this error

[ErrorException]
    file_put_contents(/Applications/MAMP/htdocs/code/bheng/vendor/composer/installed.json): faile
    d to open stream: Permission denied

Here is the current permission set on my Laravel folder

total 1872
-rw-r--r--   1 bheng  staff     777 Feb 27 20:18 phpunit.xml
-rw-r--r--   1 bheng  staff      87 Feb 27 20:18 phpspec.yml
-rw-r--r--   1 bheng  staff     481 Feb 27 20:18 package.json
drwxr-xr-x   3 bheng  staff     102 Feb 27 20:18 note
-rw-r--r--   1 bheng  staff     967 Feb 27 20:18 md-bheng-readme.txt
-rw-r--r--   1 bheng  staff     503 Feb 27 20:18 gulpfile.js
-rw-r--r--   1 bheng  staff      26 Feb 27 20:18 contributors.txt
-rw-r--r--   1 bheng  staff    1635 Feb 27 20:18 artisan
-rw-r--r--   1 bheng  staff      43 Feb 27 20:18 Procfile
-rw-r--r--   1 bheng  staff    5634 Feb 27 20:18 Gruntfile.js
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 tests
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 storage
drwxr-xr-x   4 bheng  staff     136 Feb 27 20:18 sql
-rw-r--r--   1 bheng  staff     560 Feb 27 20:18 server.php
drwxr-xr-x   5 bheng  staff     170 Feb 27 20:18 resources
-rw-r--r--   1 bheng  staff     105 Feb 27 20:18 pull.sh
drwxr-xr-x   7 bheng  staff     238 Mar  1 14:46 bootstrap
-rw-r--r--@  1 bheng  staff       0 Mar  1 14:46 Icon?
drwxr-xr-x  22 bheng  staff     748 Mar  2 11:47 app
drwxrwxrwx@ 27 bheng  staff     918 Mar  3 14:55 public
drwxr-xr-x   8 bheng  staff     272 Mar  6 13:25 database
-rw-------@  1 bheng  staff     405 Mar 14 09:29 id_rsa.pub
-rw-------   1 bheng  staff    1766 Mar 14 09:29 id_rsa
-rw-r--r--   1 bheng  staff  126713 Mar 14 10:00 composer.lock
drwxr-xr-x  18 bheng  staff     612 Mar 28 21:24 config
-rw-r--r--   1 bheng  staff    1022 Mar 30 12:21 composer.json
drwxr-xr-x  32 bheng  staff    1088 Mar 30 12:21 vendor

Here is what inside my composer.json

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "laravel/framework": "5.1.0",
    "intervention/image": "^2.3",
    "laravelcollective/remote": "5.1.*",
    "doctrine/dbal": "^2.3",
    "league/flysystem-sftp": "^1.0"
    },
    "require-dev": {
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
        },
        "autoload": {
            "classmap": [ "database" ],

            "psr-4": {
                "App\\": "app/"
            }
            },
            "autoload-dev": {
                "classmap": [
                "tests/TestCase.php"
                ]
                },
                "scripts": {
                    "post-install-cmd": [
                    "php artisan clear-compiled",
                    "php artisan optimize"
                    ],
                    "post-update-cmd": [
                    "php artisan clear-compiled",
                    "php artisan optimize"
                    ],
                    "post-create-project-cmd": [
                    "php -r \"copy('.env.example', '.env');\"",
                    "php artisan key:generate"
                    ]
                    },
                    "config": {
                        "preferred-install": "dist"
                    }
                }

How do I fix this ? Do I need to chmod any folders ?

Body:
Delete your vendor directory and run composer install again.

You're getting the permission denied error because the vendor/composer/installed.json file was created by the root user when you ran sudo composer install, so now when you run composer install your user doesn't have permission to edit that file.

Update:

If you are working within a live document root (you shouldn't be - read up on atomic deployment) then you can try chown on the vendor directory and its contents to avoid any downtime between the deletion and re-running composer install:

$ sudo chown -R myuser: vendor/

Replace myuser with your username.

ContentLicense: CC BY-SA 4.0


问:
SQL Server cyrillic error in php
First of all I want to apologize to my bad English.

And now for my problem. I have a SQL Server database and I want to get data from it with php. I can execute just select queries, because the database is not on localhost. I must get data from this database and the data is in cyrillic. This is my problem. When I execute mssql_query and get data, the Cyrillic symbols are returned as ????.

I try to convert characters with iconv and mb_convert_string, but without success.

Does anybody have a similar problem and how have you solved it?

答:
If the returned characters are actually question marks then you the problem may have been at the DB end with the data having been incorrectly imported.  In this case there may be little you can do.

If the returned characters are just being displayed as question marks, check the actual bytes (e.g. by using bin2hex on the string) and use that to determine the encoding that you have received.  You'll need to inform iconv of the correct encoding otherwise its "garbage in, garbage out".

Title: SQL Server cyrillic error in php

ContentLicense: CC BY-SA 2.5


问:
Google Speech API returns PERMISSION_DENIED the request cannot be identified with a client project
So i modified the Google Speech API Example code (didn't work before either) to be on par with their update notice (regarding the deprecation in ClientAuthenticator ) and get the same error as before with no resolution, with the host being speech.googleapis.com/v1beta1/speech:asyncrecognize?key=My_Key my code is as follows:

```<code>public static ManagedChannel createChannel(String host) throws IOException {
  FileInputStream filestream = new FileInputStream("/home/admin/creds.json");

  GoogleCredentials creds = GoogleCredentials.fromStream(filestream).createScoped(OAUTH2_SCOPES);

  ManagedChannel channel = ManagedChannelBuilder.forTarget(host).build();
  GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel);
  stub = stub.withCallCredentials(MoreCallCredentials.from(creds));
  System.out.println(channel.authority()+creds);

  filestream.close();

  return channel;
}
</code>```

but it simply returns a

```<code>WARNING: RPC failed: Status{code=PERMISSION_DENIED, description=The     request cannot be identified with a client project. Please pass a valid API key with the request., cause=null}
</code>```

any help or advice is welcome, Thanks!

答:
Hey instead of doing this,

GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel);
  stub = stub.withCallCredentials(MoreCallCredentials.from(creds));

please do following:

GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel).withCallCredentials(MoreCallCredentials.from(creds));

As your code reinitiate the stub object, you are getting PERMISSION_DENIED.

I hope it helps.

Body:
So i modified the Google Speech API Example code (didn't work before either) to be on par with their update notice (regarding the deprecation in ClientAuthenticator ) and get the same error as before with no resolution, with the host being speech.googleapis.com/v1beta1/speech:asyncrecognize?key=My_Key my code is as follows:

public static ManagedChannel createChannel(String host) throws IOException {
  FileInputStream filestream = new FileInputStream("/home/admin/creds.json");

  GoogleCredentials creds = GoogleCredentials.fromStream(filestream).createScoped(OAUTH2_SCOPES);

  ManagedChannel channel = ManagedChannelBuilder.forTarget(host).build();
  GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel);
  stub = stub.withCallCredentials(MoreCallCredentials.from(creds));
  System.out.println(channel.authority()+creds);

  filestream.close();

  return channel;
}

but it simply returns a

WARNING: RPC failed: Status{code=PERMISSION_DENIED, description=The     request cannot be identified with a client project. Please pass a valid API key with the request., cause=null}

any help or advice is welcome, Thanks!


问:
Avoiding twitter's rate limiting
When I do the following :

```<code>library(twitteR)
library("ROAuth")

consumer_key <- ''
consumer_secret <- ''
access_token <- ''
access_token_secret <- ''

setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_token_secret)

potus_user <- twitteR::getUser("potus")
followers_potus <- potus_user$getFollowerIDs()
</code>```

I get an array with 70000 entries, and the following message :

```<code>Warning message:
In twInterfaceObj$doAPICall(cmd, params, method, ...) :
  Rate limit encountered & retry limit reached - returning partial results
</code>```

I get what it's telling me, I'm asking for too much.

Is there, for instance, a way to loop on the getFollowerIDs() method and get the 70000 next followers once the rate limiting is erased ?

答:
Have you created multiple credentials for twitter's API? You might look into the smappR package: https://github.com/SMAPPNYU/smappR

The function smappR::getFollowers() can work with multiple credentials (by default, in the '~/Dropbox/credentials' directory) to speed up the acquisition of follower IDs.

The function smappR::getFollowers() has an argument sleep that allows you to tailor the frequency of API requests.

Title: Avoiding twitter's rate limiting

Body:
When I do the following :

library(twitteR)
library("ROAuth")

consumer_key <- ''
consumer_secret <- ''
access_token <- ''
access_token_secret <- ''

setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_token_secret)

potus_user <- twitteR::getUser("potus")
followers_potus <- potus_user$getFollowerIDs()

I get an array with 70000 entries, and the following message :

Warning message:
In twInterfaceObj$doAPICall(cmd, params, method, ...) :
  Rate limit encountered & retry limit reached - returning partial results

I get what it's telling me, I'm asking for too much.

Is there, for instance, a way to loop on the getFollowerIDs() method and get the 70000 next followers once the rate limiting is erased ?


问:
Why my automation in Selenium webdriver is working slow for Internet Explorer browser?
I had created a Test case for login in a website using internet Explorer server exe. When I Ran the script to enter the login name and password it takes 5 second to enter one character. Below are the details of the configuration done for this automation

IE Used: IE Server 64 bit.

Editor Used : Eclipse mars

OS Window : 64 bit.

If you need any details ready to provide.
Can you guys tell me why it takes so much of time to enter the characters in the Login name and password. I ran same script for Chrome it works fine for me.
Note: Application works well on IE 8 and above versions.
TIA

答:
Change the driver to 32-bit. Follow the link:

http://forumsqa.com/question/typing-too-slow-in-text-fields-while-replaying-tests/


问:
How to print the first n lines of file?
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

```<code>def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header
</code>```

Then later I want to write out in the format of the input file, using their header:

```<code>print(header)
for thing in usefulstuff:
   print(thing)
</code>```

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

```<code>for line in header:
     print(line)
</code>```

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

答:
There aren't two readlines() calls. Initially you call readline() which reads a single line from the file. Next you call readlines() and ignore the first 10 lines of the list it returns.

This would be a better way to do it:

```<code>def foo(lines):
    return ['foo: ' + line for line in lines]

def readInfile(infile):
    with open(infile, 'r') as ifh:
        lines = ifh.read().splitlines(False)  # read in the whole file, separate into lines
        header = lines[:10]
        usefulstuff = foo(lines[10:])

        return usefulstuff, header

usefulstuff, header = readInfile('name_of_file.txt')

for line in header:
    print(line)

for line in usefulstuff:
    print(line)
</code>```

Title: How to print the first n lines of file?

Body:
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header

Then later I want to write out in the format of the input file, using their header:

print(header)
for thing in usefulstuff:
   print(thing)

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

for line in header:
     print(line)

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

Body:
There aren't two readlines() calls. Initially you call readline() which reads a single line from the file. Next you call readlines() and ignore the first 10 lines of the list it returns.

This would be a better way to do it:

def foo(lines):
    return ['foo: ' + line for line in lines]

def readInfile(infile):
    with open(infile, 'r') as ifh:
        lines = ifh.read().splitlines(False)  # read in the whole file, separate into lines
        header = lines[:10]
        usefulstuff = foo(lines[10:])

        return usefulstuff, header

usefulstuff, header = readInfile('name_of_file.txt')

for line in header:
    print(line)

for line in usefulstuff:
    print(line)


问:
loop to fit model over all dataframe in floder python
I`m try to go through all files in folder and do some model like ARIMA for every file
my code

```<code>import os
import pandas as pd
from pandas import datetime
from sklearn.metrics import mean_squared_error
from math import sqrt
from statsmodels.tsa.arima_model import ARIMA
listing = os.listdir(path)
for infile in listing:
    pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)
#    print "current file is: " + infile

   X = df.values
   size = int(len(X) * 0.99)
   train, test = X[0:size], X[size:len(X)]
   history = [x for x in train]
   predictions = list()
   for t in range(len(test)):
      model = ARIMA(history, order=(3,1,0))
      model_fit = model.fit(disp=0)
      output = model_fit.forecast()
      yhat = output[0]
      predictions.append(yhat)
      obs = test[t]
      history.append(obs)
      print('predicted=%f, expected=%f' % (yhat, obs))
  rmse = sqrt(mean_squared_error(test, predictions))
  print('Test RMSE: %.3f' % rmse)
</code>```

the result supposed to be like this

```<code>file1 RMSE IS : 0.12
file2 RMSE IS : 0.32
file3 RMSE IS : 0.22
.
.
</code>```

but the output just showing the first file in the folder

答:
it does not appear that you are reading the csv into a dataframe.

I think

```<code>pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)
</code>```

should be

```<code>df = pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)
</code>```

Body:
I`m try to go through all files in folder and do some model like ARIMA for every file
my code

import os
import pandas as pd
from pandas import datetime
from sklearn.metrics import mean_squared_error
from math import sqrt
from statsmodels.tsa.arima_model import ARIMA
listing = os.listdir(path)
for infile in listing:
    pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)
#    print "current file is: " + infile

   X = df.values
   size = int(len(X) * 0.99)
   train, test = X[0:size], X[size:len(X)]
   history = [x for x in train]
   predictions = list()
   for t in range(len(test)):
      model = ARIMA(history, order=(3,1,0))
      model_fit = model.fit(disp=0)
      output = model_fit.forecast()
      yhat = output[0]
      predictions.append(yhat)
      obs = test[t]
      history.append(obs)
      print('predicted=%f, expected=%f' % (yhat, obs))
  rmse = sqrt(mean_squared_error(test, predictions))
  print('Test RMSE: %.3f' % rmse)

the result supposed to be like this

file1 RMSE IS : 0.12
file2 RMSE IS : 0.32
file3 RMSE IS : 0.22
.
.

but the output just showing the first file in the folder

Body:
it does not appear that you are reading the csv into a dataframe.

I think

pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)

should be

df = pd.read_csv(infile,header =0,nrows =2904 ,parse_dates=[0],
                index_col=0,squeeze=True, date_parser=parser)


问:
Find a "tabulator" space in a text field on SQL
I have several tex fields (varchar, nvarchar, ....) in a SQL Server 2012.

These fields are updated by the "users" pasting from different sources. And sometime, they paste a text that includes a "tabulator" space.

Obviously I can find spaces using:

```<code>SELECT * FROM table
WHERE field LIKE '%   %' /*3 spaces*/
OR field LIKE '%    %' /*4 spaces*/
OR field LIKE '%     %' /*5 spaces*/
OR field LIKE '%      %' /*6 spaces*/
</code>```

But is there any specific way to find out "tabulator" spaces inside a text field?

Regards!

答:
To find them you can use charindex() with char(9).

```<code>select *
from t
where charindex(char(9),col)>0;
</code>```

rextester demo: http://rextester.com/OOX36348

Body:
I have several tex fields (varchar, nvarchar, ....) in a SQL Server 2012.

These fields are updated by the "users" pasting from different sources. And sometime, they paste a text that includes a "tabulator" space.

Obviously I can find spaces using:

SELECT * FROM table
WHERE field LIKE '%   %' /*3 spaces*/
OR field LIKE '%    %' /*4 spaces*/
OR field LIKE '%     %' /*5 spaces*/
OR field LIKE '%      %' /*6 spaces*/

But is there any specific way to find out "tabulator" spaces inside a text field?

Regards!

Body:
To find them you can use charindex() with char(9).

select *
from t
where charindex(char(9),col)>0;

rextester demo: http://rextester.com/OOX36348


问:
Table View doesn't show Data, why? (Swift 3)
I've made an app using a table view to persist data. The table view shows the elements of an array which is saved through UserDefaults. Since TableViewControllers look kind of ugly, I did it a bit different: I put a TableView into a normal ViewController.
My problem is: even though I did everything I could to get the TableView to show the data, it doesn't, and I don't know why. Could anyone help me?
Here's the code of the ViewController:

```<code>class ErfolgreicheChallenges: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!

    var data = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.delegate = self

        data.append("test")
        data.append("lol")

    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        myTableView.dataSource = self

        let cell = myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel!.text = data[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

}
</code>```

Thanks to everyone for having a look! Have a great day

答:
You need to set the data source and data delegate in viewDidLoad, or somewhere similar.

You are setting the datasource inside cellForRowAt, but that will never be called!

Body:
I've made an app using a table view to persist data. The table view shows the elements of an array which is saved through UserDefaults. Since TableViewControllers look kind of ugly, I did it a bit different: I put a TableView into a normal ViewController.
My problem is: even though I did everything I could to get the TableView to show the data, it doesn't, and I don't know why. Could anyone help me?
Here's the code of the ViewController:

class ErfolgreicheChallenges: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!

    var data = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.delegate = self

        data.append("test")
        data.append("lol")

    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        myTableView.dataSource = self

        let cell = myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel!.text = data[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

}

Thanks to everyone for having a look! Have a great day


问:
How to take a "num/den" type input in Java?
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

```<code>Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();
</code>```

and divide symbol will be disregarded.

答:
Another way to do it is

```<code>String line = input.readLine();
int num = Integer.parseInt(line.substring( 0, line.indexOf("/") ));
int den = Integer.parseInt(line.substring( line.indexOf("/") + 1 ));
</code>```

It will find the "/" and take the left part as the "num" and the rigth part as "den"

Body:
I want to take in input like this:

Enter a fraction(num/den):

I thought this would work,

Scanner input = new Scanner(System.in);
System.out.print("Enter a fraction(num/den):");
numerator = input.nextInt();
input.next();
denominator = input.nextInt();

and divide symbol will be disregarded.

Body:
Another way to do it is

String line = input.readLine();
int num = Integer.parseInt(line.substring( 0, line.indexOf("/") ));
int den = Integer.parseInt(line.substring( line.indexOf("/") + 1 ));

It will find the "/" and take the left part as the "num" and the rigth part as "den"


问:
Logging setLevel is being ignored
The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.

Why is this happening? foo.py:

```<code>import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
</code>```

Output:

```<code>workingDirectory$ python foo.py
warn message
error message
critical message
</code>```

Where did the info and debug messages go??

答:
Replace the line

```<code>logger.setLevel(logging.DEBUG)
</code>```

with

```<code>logging.basicConfig(level=logging.DEBUG, format='%(message)s')
</code>```

and it should work as expected. If you don't configure logging with any handlers (as in your post - you only configure a level for your logger, but no handlers anywhere), you'll get an internal handler "of last resort" which is set to output just the message (with no other formatting) at the WARNING level.

Title: Logging setLevel is being ignored

Body:
The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.

Why is this happening? foo.py:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

Output:

workingDirectory$ python foo.py
warn message
error message
critical message

Where did the info and debug messages go??

Body:
Replace the line

logger.setLevel(logging.DEBUG)

with

logging.basicConfig(level=logging.DEBUG, format='%(message)s')

and it should work as expected. If you don't configure logging with any handlers (as in your post - you only configure a level for your logger, but no handlers anywhere), you'll get an internal handler "of last resort" which is set to output just the message (with no other formatting) at the WARNING level.


问:
Virtualbox doesn't open - error VERR_VD_IMAGE_READ_ONLY
I had tried to install an OS named Veos with virtual box ,but when I had finished the installation ,I can not open the wirtual machine Veos ,and I had this output:
 Failed to open image 'C:\Users\Takfarinas\VirtualBox VMs\AristaFiles\vEOS-lab-4.16.6M.vmdk' for writing due to wrong permissions (VERR_VD_IMAGE_READ_ONLY).
Failed to attach driver below us! Image is read-only. (VERR_VD_IMAGE_READ_ONLY).
PIIX3 cannot attach drive to the Primary Master (VERR_VD_IMAGE_READ_ONLY).

Code d'erreur :
E_FAIL (0x80004005)
Composant :
ConsoleWrap
Interface :
IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

答: This happens on our work airgap machine when someone forgets to shut down the virtual machine at the end of their session. Restarting the machine resolves the issue, for me.</p>


问:
Posting photos to Facebook fan page with iOS SDK
I'm trying to upload a photo to a Facebook page I own using the iOS SDK and graph API. I've been able to upload photos to my own wall. I've also been able to post a message to my fan page wall as an admin and create an album on my fan page, so I think I'm making the right calls, but not succeeding.

This is what I'm currently doing.

I'm logging in using

```<code>Facebook *fb = [[Facebook alloc] init];
self.facebook = fb;
[fb release];
NSArray *permissions =  [[NSArray arrayWithObjects:@"read_stream", @"offline_access", @"publish_stream", @"manage_pages", @"user_photos", @"friends_photos",nil] retain];
[facebook authorize:FB_APP_ID permissions:permissions delegate:self];
[permissions release];
</code>```

After I log in, I request the accounts

```<code>[facebook requestWithGraphPath:@"/me/accounts" andDelegate:self];
</code>```

The accounts are returned to me with access tokens for each page and app I own. I use a simple loop to parse through the accounts to extra the access_token supplied for the page I wish to upload a photo to.

I then set my access token of my facebook object to the new access_token.

```<code>facebook.accessToken = new_accessToken;
</code>```

and try and upload a photo my fan page using

```<code>UIImage *uploadImage = [UIImage imageNamed:@"t200.jpg"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
               uploadImage, @"source",
             @"test caption", @"message",
             nil];

[facebook requestWithGraphPath:@"/me/photos" andParams:params
        andHttpMethod:@"POST" andDelegate:self];
</code>```

The response I receive is

```
{"error":{"type":"OAuthException","message":"(#1) An unknown error occurred"}}
```

Is this a bug in the facebook graph API? I also tried making this call using standard HTTPS requests, and get the same result.

答: Not sure about this since I am quite new to FB iOS integration but I think you shouldn't use me/photos but the xyz/photos where xyz is the ID of the page you want to post to.</p>

Body:
I'm trying to upload a photo to a Facebook page I own using the iOS SDK and graph API. I've been able to upload photos to my own wall. I've also been able to post a message to my fan page wall as an admin and create an album on my fan page, so I think I'm making the right calls, but not succeeding.

This is what I'm currently doing.

I'm logging in using

Facebook *fb = [[Facebook alloc] init];
self.facebook = fb;
[fb release];
NSArray *permissions =  [[NSArray arrayWithObjects:@"read_stream", @"offline_access", @"publish_stream", @"manage_pages", @"user_photos", @"friends_photos",nil] retain];
[facebook authorize:FB_APP_ID permissions:permissions delegate:self];
[permissions release];

After I log in, I request the accounts

[facebook requestWithGraphPath:@"/me/accounts" andDelegate:self];

The accounts are returned to me with access tokens for each page and app I own. I use a simple loop to parse through the accounts to extra the access_token supplied for the page I wish to upload a photo to.

I then set my access token of my facebook object to the new access_token.

facebook.accessToken = new_accessToken;

and try and upload a photo my fan page using

UIImage *uploadImage = [UIImage imageNamed:@"t200.jpg"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
               uploadImage, @"source",
             @"test caption", @"message",
             nil];

[facebook requestWithGraphPath:@"/me/photos" andParams:params
        andHttpMethod:@"POST" andDelegate:self];

The response I receive is

{"error":{"type":"OAuthException","message":"(#1) An unknown error occurred"}}

Is this a bug in the facebook graph API? I also tried making this call using standard HTTPS requests, and get the same result.


问:
A prolog predicate checks if an element occurs at least twice in a list
```<code>twice(X,[X|Y]):-
   member(X,[Y]).
twice(X,[Y|Z]):-
   twice(X,[Z]),
   X\=Y.
</code>```

I can't find any syntax error,but the execution fails every time.

答:
You've got a misconception about the list structure. The list [H|T] has head element H and tail list T. So T is itself a list. If you put [T] then that's a list of only one element, that element being the list T.

Also, in your second predicate clause, you don't need the X argument or to check for X \= Y since it's not really relevant if you're checking for at least twice.

Thus, your solution changes a little to:

```<code>twice(X, [X|T]) :-
    member(X, T).
twice(X, [_|T]) :-
    twice(X, T).
</code>```

Which says that X occurs twice in [X|T] if X is a member of T or X occurs twice in [_|T] if X occurs twice in T.

Body:
twice(X,[X|Y]):-
   member(X,[Y]).
twice(X,[Y|Z]):-
   twice(X,[Z]),
   X\=Y.

I can't find any syntax error,but the execution fails every time.

Body:
You've got a misconception about the list structure. The list [H|T] has head element H and tail list T. So T is itself a list. If you put [T] then that's a list of only one element, that element being the list T.

Also, in your second predicate clause, you don't need the X argument or to check for X \= Y since it's not really relevant if you're checking for at least twice.

Thus, your solution changes a little to:

twice(X, [X|T]) :-
    member(X, T).
twice(X, [_|T]) :-
    twice(X, T).

Which says that X occurs twice in [X|T] if X is a member of T or X occurs twice in [_|T] if X occurs twice in T.


问:
Removing from local storage
I have added to my local storage to create a favorites section on an app i am not trying to remove using a different button. The remove wont work any ideas why?</p>

```<code>//Add Favorites
$('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

});

//Removing favorites
$('.removebtn').click(function () {
                localStorage.removeItem('favorties', JSON.stringify(favArray));
            });
</code>```

答:
You just have to pass the key of the item to remove:</p>

```<code>localStorage.removeItem('favorties');
</code>```

Title: Removing from local storage

Body:
I have added to my local storage to create a favorites section on an app i am not trying to remove using a different button. The remove wont work any ideas why?

//Add Favorites
$('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

});

//Removing favorites
$('.removebtn').click(function () {
                localStorage.removeItem('favorties', JSON.stringify(favArray));
            });

Body:
You just have to pass the key of the item to remove:

localStorage.removeItem('favorties');


问:
(OpenGL) Rotate object
I'm making a program that rotates six-point stars with two triangles overlapping when I click the mouse button.

Click right mouse button: star spins

Click middle mouse button: star's color changes(white → blue)

I've applied the codes to rotate a rectangle, but when I click right mouse button, it doesn't rotate and makes a jump around.

And when the middle mouse button is clicked, the color changing is successful but it is initialized by rotating the star. I would like to rotate the star with the color changed by clicking the middle button while rotating.

Please let me know what is the problem.

```<code>/////////////////////////// Header /////////////////////////////
#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { 365.0, 465.0, 0.0 };
float v2[3] = { 365.0, 420.0, 0.0 };
float v3[3] = { 400.0, 485.0, 0.0 };
float v4[3] = { 400.0, 400.0, 0.0 };
float v5[3] = { 435.0, 465.0, 0.0 };
float v6[3] = { 435.0, 420.0, 0.0 };

static GLfloat spin = 0.0;

//////////////////////// Functions ////////////////////////////
void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void spinDisplay(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void triangle_1(void) {         /////////// first triangle ///////////
    glColor3f(1.0, 1.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {         ///////// second triangle /////////
    glColor3f(1.0, 1.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void triangle_1p(void) {       ///// first triangle (color changed) /////
    glColor3f(0.0, 0.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2p(void) {       ///// second triangle (color changed) /////
    glColor3f(0.0, 1.0, 0.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void display(void) {            ///////// star display /////////
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void display_p(void) {         ///// star display (color changed) /////
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1p();
    triangle_2p();

    glPopMatrix();

    glutSwapBuffers();
}

/////////////////////// Mouse Click ///////////////////////
void mouse(int button, int state, int x, int y) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(NULL);
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(display_p);
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(spinDisplay);
        break;
    default:
        break;
    }
}

//////////////////////////// Main /////////////////////////////
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}
</code>```

答:
when I click right mouse button, it doesn't rotate and makes a jump around

It actually isn't jumping around, it's rotating around the origin (bottom left corner of the display).

The reason this happens if because you're rotating then translating. Since you have hardcoded the star's position of x = 400 and y = 442.5 into your vertices. If you make so that the the center of the star is at 0x0 (subtracting 400x442.5) then you'll see the star is rotating around itself in the bottom left corner of the display.

```<code>float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = {   0.0f,  42.5f, 0.0f };
float v4[3] = {   0.0f, -42.5f, 0.0f };
float v5[3] = {  35.0f,  22.5f, 0.0f };
float v6[3] = {  35.0f, -22.5f, 0.0f };
</code>```

Now in display() you then translate before rotating:

```<code>glTranslatef(x, y, 0.0f);
glRotatef(spin, 0.0, 0.0, 1.0);
</code>```

Considering float x = 400.0f, y = 442.5f; to be defined elsewhere.

Now you'll see the star back at the same place, but rotating around itself.

I would like to rotate the star with the color changed by clicking the middle button while rotating.

Instead of duplicating all your code for each mode, you could keep the colors as variables.

```<code>float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;
</code>```

Now in mouse() on GLUT_MIDDLE_BUTTON then you switch around the colors.

```<code>case GLUT_MIDDLE_BUTTON:
    if (state == GLUT_DOWN) {
        if (mode == 1) {
            color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
            color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
            mode = 2;
        }
        else if (mode == 2) {
            color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
            color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
            mode = 1;
        }
    }
</code>```

Then in triangle_1 and triangle_2 remember to replace glColor3f() with glColor3fv(color1) and glColor3fv(color2).

Instead of all that, you could also just set mode in mouse and do something like this in triangle_1 (also doing likewise in triangle_2):

```<code>if (mode == 2)
    glColor3f(0.0, 0.0, 1.0);
else
    glColor3f(1.0, 1.0, 1.0);
</code>```

The choice is of course up to you.

All in all, now you should be able to see the star rotating around itself, and toggle the colors when middle mouse button is clicked.

This now also means that you can delete display_p, triangle_1p and triangle_2p.

Title: (OpenGL) Rotate object

Body:
I'm making a program that rotates six-point stars with two triangles overlapping when I click the mouse button.

Click right mouse button: star spins

Click middle mouse button: star's color changes(white → blue)

I've applied the codes to rotate a rectangle, but when I click right mouse button, it doesn't rotate and makes a jump around.

And when the middle mouse button is clicked, the color changing is successful but it is initialized by rotating the star. I would like to rotate the star with the color changed by clicking the middle button while rotating.

Please let me know what is the problem.

/////////////////////////// Header /////////////////////////////
#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { 365.0, 465.0, 0.0 };
float v2[3] = { 365.0, 420.0, 0.0 };
float v3[3] = { 400.0, 485.0, 0.0 };
float v4[3] = { 400.0, 400.0, 0.0 };
float v5[3] = { 435.0, 465.0, 0.0 };
float v6[3] = { 435.0, 420.0, 0.0 };

static GLfloat spin = 0.0;

//////////////////////// Functions ////////////////////////////
void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void spinDisplay(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void triangle_1(void) {         /////////// first triangle ///////////
    glColor3f(1.0, 1.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {         ///////// second triangle /////////
    glColor3f(1.0, 1.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void triangle_1p(void) {       ///// first triangle (color changed) /////
    glColor3f(0.0, 0.0, 1.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2p(void) {       ///// second triangle (color changed) /////
    glColor3f(0.0, 1.0, 0.0);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void display(void) {            ///////// star display /////////
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void display_p(void) {         ///// star display (color changed) /////
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1p();
    triangle_2p();

    glPopMatrix();

    glutSwapBuffers();
}

/////////////////////// Mouse Click ///////////////////////
void mouse(int button, int state, int x, int y) {
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(NULL);
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(display_p);
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            glutIdleFunc(spinDisplay);
        break;
    default:
        break;
    }
}

//////////////////////////// Main /////////////////////////////
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}

Body:
when I click right mouse button, it doesn't rotate and makes a jump around

It actually isn't jumping around, it's rotating around the origin (bottom left corner of the display).

The reason this happens if because you're rotating then translating. Since you have hardcoded the star's position of x = 400 and y = 442.5 into your vertices. If you make so that the the center of the star is at 0x0 (subtracting 400x442.5) then you'll see the star is rotating around itself in the bottom left corner of the display.

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = {   0.0f,  42.5f, 0.0f };
float v4[3] = {   0.0f, -42.5f, 0.0f };
float v5[3] = {  35.0f,  22.5f, 0.0f };
float v6[3] = {  35.0f, -22.5f, 0.0f };

Now in display() you then translate before rotating:

glTranslatef(x, y, 0.0f);
glRotatef(spin, 0.0, 0.0, 1.0);

Considering float x = 400.0f, y = 442.5f; to be defined elsewhere.

Now you'll see the star back at the same place, but rotating around itself.

I would like to rotate the star with the color changed by clicking the middle button while rotating.

Instead of duplicating all your code for each mode, you could keep the colors as variables.

float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;

Now in mouse() on GLUT_MIDDLE_BUTTON then you switch around the colors.

case GLUT_MIDDLE_BUTTON:
    if (state == GLUT_DOWN) {
        if (mode == 1) {
            color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
            color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
            mode = 2;
        }
        else if (mode == 2) {
            color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
            color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
            mode = 1;
        }
    }

Then in triangle_1 and triangle_2 remember to replace glColor3f() with glColor3fv(color1) and glColor3fv(color2).

Instead of all that, you could also just set mode in mouse and do something like this in triangle_1 (also doing likewise in triangle_2):

if (mode == 2)
    glColor3f(0.0, 0.0, 1.0);
else
    glColor3f(1.0, 1.0, 1.0);

The choice is of course up to you.

All in all, now you should be able to see the star rotating around itself, and toggle the colors when middle mouse button is clicked.

This now also means that you can delete display_p, triangle_1p and triangle_2p.


问:
SystemEvents.SessionSwitch Crashes in Windows 8 but works in Windows 10
I am developing a WPF App and getting a very weird problem:

I use SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; to detect the screen lock event of the computer. The code works well in Windows 10. But crashes in Windows 8. The error window I got was "You App has stopped working" without any exception code. I tried it on other Windows 10 and other Windows 8 and got the same results. Any ideas?

答: I'm not sure why someone downvoted this question. Anyway, I've fixed the problem by installing  341.61-quadro-grid-desktop-notebook-win8-win7-64bit-international-whql.exe  on windows 8. </p>


问:
null object after valueEventListener
I am using Firebase valueEventListener and adding objects in OnDataChange. But my list stays null. Please help.

答: Firebase listeners fetch data asynchronously. Add your objects in the list in the OnDataChange method itself. And notify the adapter by adapter.notifyDataSetChanged()

Title: null object after valueEventListener


问:
How to launch XCUITests on more than one simulator from command line
Does any one know how to launch XCUItest bundles from command line on more than one simulator?

I do not wish to use a third party frame work. I just want to know how to do it from command line.
Currently, I only know how to launch them on one simulator.
Any help is appreciated.

答:
```<code>xcodebuild test -workspace your_app.xcworkspace -scheme your_app_scheme -destination 'platform=iphonesimulator,name=iPad Air'
</code>```

Also I recommend to read this article for using Ruby Rake library with Command line  http://cuckooforcocoadev.com/blog/2014/05/02/using-rake-for-command-line-builds/

If you use rake you will be able customize log of UI tests results.
According to this article:

```<code>xcodebuild -workspace your_app.xcworkspace -scheme '#{target_name}' -sdk iphonesimulator -configuration Release #{build_action} | xcpretty -tc ; exit ${PIPESTATUS[0]}
</code>```

Body:
xcodebuild test -workspace your_app.xcworkspace -scheme your_app_scheme -destination 'platform=iphonesimulator,name=iPad Air'

Also I recommend to read this article for using Ruby Rake library with Command line  http://cuckooforcocoadev.com/blog/2014/05/02/using-rake-for-command-line-builds/

If you use rake you will be able customize log of UI tests results.
According to this article:

xcodebuild -workspace your_app.xcworkspace -scheme '#{target_name}' -sdk iphonesimulator -configuration Release #{build_action} | xcpretty -tc ; exit ${PIPESTATUS[0]}


问:
Oracle datapump export/import
I tried to do a full Datapump exp on our Dbase.
But resorted to just backing up the table spaces we were working on.

Then I imported using table_exists_action=replace;

Afterwards unfortunately all the Grants on objects are lost... grants
For procedures and functions and I imagine others as well...

Why would the grants to the procedures be lost after importing using table_exists_action=replace; ?
Is there some other way of running the import to get the grants on the prcedures.. in fact everything on the tablespaces
I'm importing ?

I suppose I can fix that by doing the Grant on the Objects ( procedures, functions, etc ) one by one provided the procedures
apply to the schema they're in. When I do so however a few of them wouldn't get granted/wouldn't work.

Looks like we would really need to be able to accomplish a full dbase exp and imp...

What would we need to have in place for this to work ?

If I tried a full Datapump export I get a fatal error I imagine it's due to the excessive size of the dump file ( 30.25 GB ) to our
Linux server backup folder ?? see below

1.Total estimation using BLOCKS method: 30.25 GB

Then..

Total estimation using BLOCKS method: 30.25 GB
Processing object type DATABASE_EXPORT/PRE_SYSTEM_IMPCALLOUT/MARKER
Processing object type DATABASE_EXPORT/PRE_INSTANCE_IMPCALLOUT/MARKER
Processing object type DATABASE_EXPORT/TABLESPACE
Processing object type DATABASE_EXPORT/PROFILE
Processing object type DATABASE_EXPORT/SYS_USER/USER
Processing object type DATABASE_EXPORT/SCHEMA/USER
Processing object type DATABASE_EXPORT/ROLE
Processing object type DATABASE_EXPORT/RADM_FPTM
Processing object type DATABASE_EXPORT/GRANT/SYSTEM_GRANT/PROC_SYSTEM_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/GRANT/SYSTEM_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/ROLE_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/DEFAULT_ROLE
Processing object type DATABASE_EXPORT/SCHEMA/ON_USER_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/TABLESPACE_QUOTA
Processing object type DATABASE_EXPORT/RESOURCE_COST
Processing object type DATABASE_EXPORT/SCHEMA/DB_LINK
Processing object type DATABASE_EXPORT/TRUSTED_DB_LINK
Processing object type DATABASE_EXPORT/SCHEMA/SEQUENCE/SEQUENCE
Processing object type DATABASE_EXPORT/SCHEMA/SEQUENCE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/DIRECTORY/DIRECTORY
Processing object type DATABASE_EXPORT/DIRECTORY/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/DIRECTORY/GRANT/WITH_GRANT_OPTION/OBJECT_GRANT
Processing object type DATABASE_EXPORT/DIRECTORY/GRANT/CROSS_SCHEMA/OBJECT_GRANT
Processing object type DATABASE_EXPORT/CONTEXT
Processing object type DATABASE_EXPORT/SCHEMA/PUBLIC_SYNONYM/SYNONYM
Processing object type DATABASE_EXPORT/SCHEMA/SYNONYM
Processing object type DATABASE_EXPORT/SCHEMA/TYPE/TYPE_SPEC
Processing object type DATABASE_EXPORT/SCHEMA/TYPE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SYSTEM_PROCOBJACT/PRE_SYSTEM_ACTIONS/PROCACT_SYSTEM
Processing object type DATABASE_EXPORT/SYSTEM_PROCOBJACT/PROCOBJ
Processing object type DATABASE_EXPORT/SYSTEM_PROCOBJACT/POST_SYSTEM_ACTIONS/PROCACT_SYSTEM
Processing object type DATABASE_EXPORT/SCHEMA/PROCACT_SCHEMA
Processing object type DATABASE_EXPORT/EARLY_OPTIONS/VIEWS_AS_TABLES/TABLE
Processing object type DATABASE_EXPORT/EARLY_POST_INSTANCE_IMPCALLOUT/MARKER
Processing object type DATABASE_EXPORT/NORMAL_OPTIONS/TABLE
Processing object type DATABASE_EXPORT/NORMAL_OPTIONS/VIEWS_AS_TABLES/TABLE
Processing object type DATABASE_EXPORT/NORMAL_POST_INSTANCE_IMPCALLOU/MARKER
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/COMMENT
Processing object type DATABASE_EXPORT/SCHEMA/PACKAGE/PACKAGE_SPEC
Processing object type DATABASE_EXPORT/SCHEMA/PACKAGE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/FUNCTION/FUNCTION
Processing object type DATABASE_EXPORT/SCHEMA/FUNCTION/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/PROCEDURE/PROCEDURE
Processing object type DATABASE_EXPORT/SCHEMA/PROCEDURE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/PACKAGE/COMPILE_PACKAGE/PACKAGE_SPEC/ALTER_PACKAGE_SPEC
Processing object type DATABASE_EXPORT/SCHEMA/FUNCTION/ALTER_FUNCTION
Processing object type DATABASE_EXPORT/SCHEMA/PROCEDURE/ALTER_PROCEDURE
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/INDEX/INDEX
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/CONSTRAINT/CONSTRAINT
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
Processing object type DATABASE_EXPORT/SCHEMA/VIEW/VIEW
Processing object type DATABASE_EXPORT/SCHEMA/VIEW/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type DATABASE_EXPORT/SCHEMA/VIEW/COMMENT
Processing object type DATABASE_EXPORT/SCHEMA/PACKAGE_BODIES/PACKAGE/PACKAGE_BODY
Processing object type DATABASE_EXPORT/SCHEMA/TYPE/TYPE_BODY
Job "GAPLITE"."EXPORT_JOB_SQLDEV_3526" stopped due to fatal error at Fri Mar 24 12:05:34 2017 elapsed 0 00:16:47

The cmd:

impdp gaplite/gaplite@mbqas DIRECTORY=exp_gaplite DUMPFILE=gaplite_SLAC.dmp LOGFILE=gaplite_SLAC_march282017.log TABLESPACES=GAPLITE,I_IDB,I_PCAP,REIMB,TANDEM_REFRESH,R_PAYMENT,CAPS,PAYMENT,PCAP,TANDEM,HCOM,IREPORTS,R_IDB,I_PAYMENT,DEFER_V2,CLIEN T_MAPPING,IDB,R_CAPS,R_GAPLITE,I_GAPLITE,DB_MOD,PARTNER_CLAIMS,PCAP_WORK,SDP,R_PCAP,UCS,PCAPEOD,I_CAPS,PREPAYMENT,CDC,I_PREPAYMENT,ER EIMBURSEMENT,AUDITCOLLECTIONS,SLDRYRUN,R_DRUGOPS,R_REIMB,R_TANDEM_REFRESH,IMPORT_CAPS,EVENTS,DRUGOPS table_exists_action=replace;

but it looks like I should include the SYSTEM tablespace to maintain grant objects, etc.
or add something like EXCLUDE=CONSTRAINT,REF_CONSTRAINT,INDEX..

答:
Well, from what i rebember, that's a common problem. It may be due to the fact that the grants are being implemented before the user/object creation.
So, basically, store the scripts from those grants to implement them later. </p>

Title: Oracle datapump export/import


答:
Just in case you want to get rid of those extra spaces, here is a little technique Gordon demonstrated several weeks ago.  It will handle ANY NUMBER of repeating spaces.

```<code>Declare @YourTable table (col varchar(100))
Insert Into @YourTable values
('Some    text    with extra spaces')

Select *
      ,Trimmed = replace(replace(replace(col,' ','><'),'<>',''),'><',' ')
 From  @YourTable
</code>```

Returns

```<code>col                                 Trimmed
Some    text    with extra spaces   Some text with extra spaces
</code>```

EDIT - To Update

```<code>Update YourTable
   set col = replace(replace(replace(col,' ','><'),'<>',''),'><',' ')
 Where col like '%  %'
</code>```

No need to search for 3+ spaces, searching for double spaces will do the trick

Title: Find a "tabulator" space in a text field on SQL

Body:
Just in case you want to get rid of those extra spaces, here is a little technique Gordon demonstrated several weeks ago.  It will handle ANY NUMBER of repeating spaces.

Declare @YourTable table (col varchar(100))
Insert Into @YourTable values
('Some    text    with extra spaces')

Select *
      ,Trimmed = replace(replace(replace(col,' ','><'),'<>',''),'><',' ')
 From  @YourTable

Returns

col                                 Trimmed
Some    text    with extra spaces   Some text with extra spaces

EDIT - To Update

Update YourTable
   set col = replace(replace(replace(col,' ','><'),'<>',''),'><',' ')
 Where col like '%  %'

No need to search for 3+ spaces, searching for double spaces will do the trick


问:
Find user id from Telegram username
getFullUser a method in Telegram API that returns extended user info by ID.

https://core.telegram.org/method/users.getFullUser

My question is how I can get the user id from telegram username to use with this method.
For example this is my username : telegram.me/androidsoftware .
Is a method exist that return userId from username ?

答:
You should use undocumented method ContactsResolveUsername, check for existence of this in your client SDK

example in Java: https://github.com/rubenlagus/TelegramApi/blob/master/src/main/java/org/telegram/api/functions/contacts/TLRequestContactsResolveUsername.java

description: http://aseman.co/documents/libqtelegram-ae/functions/methods/resolveusername.html

Title: Find user id from Telegram username


问:
WordPress is declaring JQuery in the Footer
I've been handed a WordPress (WP) site from a 3rd party. I work with Drupal, so I'm not well-rounded in WP.

That said, I'm attempting to install Google Tag Manager (GTM). However, I'm getting console errors, stating that JQuery is not defined. I've discovered that JQuery is defined in the , not the . I've had this issue in the past with Drupal, but I'm not sure where to begin with WP.

After looking at the template, I've discovered that there is a <?php wp_head(); ?> tag in the head and there is a <?php wp_footer(); ?> tag in the footer. Both tags inject scripts, but obviously, JQuery is injected through the footer tag. From what I can tell, the scripts are compiled in the script-loader.php document, but the document is a little overwhelming. I'm not exactly sure what to move around in order to get JQuery injected through the <?php wp_head(); ?> tag.

I've uploaded the script-loader.php document to Google Drive. I'll put it into a .txt file so that it's readable within GDrive.

Please let me know if there's anything else I can provide. Any helpful feedback is appreciated!

答:
After posting on the Stack Exchange site for WordPress, I found a solution. Basically, I had to enqueue the GTM script, declaring JQuery as a dependency to it. The script I was provided is as follows:</p>

```<code>function my_theme_add_gtm_script() {
    wp_enqueue_script('google-track-manager', get_template_directory_uri() . '/assets/js/gtm.js', array('jquery'), false, false);
}
add_action('wp_enqueue_scripts', 'my_theme_add_gtm_script');
</code>```

Body:
After posting on the Stack Exchange site for WordPress, I found a solution. Basically, I had to enqueue the GTM script, declaring JQuery as a dependency to it. The script I was provided is as follows:

function my_theme_add_gtm_script() {
    wp_enqueue_script('google-track-manager', get_template_directory_uri() . '/assets/js/gtm.js', array('jquery'), false, false);
}
add_action('wp_enqueue_scripts', 'my_theme_add_gtm_script');


问:
Java: not printing lines which start with certain character
So basicly what I'm intending to do is read information from the agree1out file, which contains following information:

1|1

2|0

The following piece of code hooks into my mySQL database, using the first 2 numbers (before "|") to get xf.user.user_id.

Currently String print is:

equalsdavid 1 6af87ef8-e620-4d08-8320-183fc469eb0d

user 0 ac899bce-4a87-4977-957c-05013534b25b

I need a way to remove lines where the second part of the string is less than 1.
Now I tried doing something like, but since I'm here you can probably tell it didn't work:

```<code>  temp = temp.replaceAll("(?m)^0.*", "");
</code>```

Here is the code:

```<code>  package io.chuchoter.stats2;

    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.UUID;

    import io.chuchoter.core.Main;

    public class RATE2_agree {
    public static void main(String [] args) {

        String line = null;

        try {

            PrintStream p = new PrintStream(new File(Main.agree2out));
            System.setOut(p);

            FileReader fileReader =
                new FileReader(Main.agree1out);

            BufferedReader bufferedReader =
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {

                String[] parts = line.split("|");
                String part1 = parts[0];
                String part3 = parts[2];

                Connection con = DriverManager.getConnection(Main.host, Main.uName, Main.uPass);

                Statement rstmt = con.createStatement();
                String r = "SELECT * FROM `xf_user` WHERE `user_id` = " + part1 + ";";
                ResultSet rs = rstmt.executeQuery(r);

                while (rs.next()) {
                    String uuid = UUID.randomUUID().toString();
                    String username = rs.getString("username");

                    String print = username + " " + part3 + " " + uuid;
                    System.out.println(print);
                }
            }

            bufferedReader.close();

        }

        catch(FileNotFoundException ex) {
            System.out.println("Unable to open file");
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file");
        }

        catch (SQLException err) {
            System.out.println(err.getMessage());
        }
    }

}
</code>```

Thanks for the help!

答:
For string "1|1", when you apply a split

```<code>String[] parts = line.split("|");
</code>```

you get an array of size 2. Thus your code will go like this

```<code>String[] parts = line.split("|");
String part1 = parts[0];
String part3 = parts[1];
Connection con = DriverManager.getConnection(Main.host, Main.uName, Main.uPass);

Statement rstmt = con.createStatement();
String r = "SELECT * FROM `xf_user` WHERE `user_id` = " + part1 + ";";
ResultSet rs = rstmt.executeQuery(r);

StringBuilder sb = new StringBuilder();
while (rs.next()) {
     String uuid = UUID.randomUUID().toString();
     String username = rs.getString("username");
     String print = username + " " + part3 + " " + uuid;
     if(Integer.parseInt(part3) >= 0)
         sb.append(print + "\n");
}
System.out.println(sb.toString());
</code>```

Hope this helps!

Body:
So basicly what I'm intending to do is read information from the agree1out file, which contains following information:

1|1

2|0

The following piece of code hooks into my mySQL database, using the first 2 numbers (before "|") to get xf.user.user_id.

Currently String print is:

equalsdavid 1 6af87ef8-e620-4d08-8320-183fc469eb0d

user 0 ac899bce-4a87-4977-957c-05013534b25b

I need a way to remove lines where the second part of the string is less than 1.
Now I tried doing something like, but since I'm here you can probably tell it didn't work:

  temp = temp.replaceAll("(?m)^0.*", "");

Here is the code:

  package io.chuchoter.stats2;

    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.UUID;

    import io.chuchoter.core.Main;

    public class RATE2_agree {
    public static void main(String [] args) {

        String line = null;

        try {

            PrintStream p = new PrintStream(new File(Main.agree2out));
            System.setOut(p);

            FileReader fileReader =
                new FileReader(Main.agree1out);

            BufferedReader bufferedReader =
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {

                String[] parts = line.split("|");
                String part1 = parts[0];
                String part3 = parts[2];

                Connection con = DriverManager.getConnection(Main.host, Main.uName, Main.uPass);

                Statement rstmt = con.createStatement();
                String r = "SELECT * FROM `xf_user` WHERE `user_id` = " + part1 + ";";
                ResultSet rs = rstmt.executeQuery(r);

                while (rs.next()) {
                    String uuid = UUID.randomUUID().toString();
                    String username = rs.getString("username");

                    String print = username + " " + part3 + " " + uuid;
                    System.out.println(print);
                }
            }

            bufferedReader.close();

        }

        catch(FileNotFoundException ex) {
            System.out.println("Unable to open file");
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file");
        }

        catch (SQLException err) {
            System.out.println(err.getMessage());
        }
    }

}

Thanks for the help!

Body:
For string "1|1", when you apply a split

String[] parts = line.split("|");

you get an array of size 2. Thus your code will go like this

String[] parts = line.split("|");
String part1 = parts[0];
String part3 = parts[1];
Connection con = DriverManager.getConnection(Main.host, Main.uName, Main.uPass);

Statement rstmt = con.createStatement();
String r = "SELECT * FROM `xf_user` WHERE `user_id` = " + part1 + ";";
ResultSet rs = rstmt.executeQuery(r);

StringBuilder sb = new StringBuilder();
while (rs.next()) {
     String uuid = UUID.randomUUID().toString();
     String username = rs.getString("username");
     String print = username + " " + part3 + " " + uuid;
     if(Integer.parseInt(part3) >= 0)
         sb.append(print + "\n");
}
System.out.println(sb.toString());

Hope this helps!


问:
how to register a subscriber the right way in ionic 2?
I have this ionic 2 provider:

```<code>@Injectable()
export class SettingsProvider {

    settingsData: SettingsDataModel = new SettingsDataModel(2, 2);
    subscriber = null;

    constructor(public http: Http, public storage: Storage) {
        console.log('Hello SettingsProvider Provider');
    }

    load(): void {
        this.storage.ready().then(() => {

            // Or to get a key/value pair
            this.storage.get('settingsData').then((val) => {
                this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
            });

        })
    }

    save() {
        this.storage.set('settingsData', this.settingsData);
        this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
    }

    subscribe(callback) { // how to register a subscriber the right way in ionic 2?
        this.subscriber = callback;
    }

}
</code>```

I have implemented the ability that another class wanting to subscribe and get notifications by custom code (fragile one) what would be the implementation that another class could subscribe to it the right way?

答:
In order to notify another chunk of code, such as another service, you can expose an observable property that represents an ongoing series of events. We can do this using a Subject.

Here is what this would look like

```<code>import { Subject } from 'rxjs/subject';

// singleton can use true privacy.
const settingsEventSource = new Subject<SettingsDataModel>();

@Injectable() export default class SettingsProvider {

  constructor(readonly http: Http, readonly storage: Storage) { }

  get settings$() {
    return settingsEventSource.asObservable(); // prevent others from sourcing events
  }

  settingsData = new SettingsDataModel(2, 2);

  async load() {
    await this.storage.ready();
    try {
      this.settingsData = await this.storage.get('settingsData');
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error loading settings.');
    }
  }

  async save() {
    try {
      await this.storage.set('settingsData', this.settingsData);
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error saving settings.');
    }
  }
}
</code>```

A subscriber would look like this

```<code>import SettingsProvider from './settings-provider';
import SetttingsDataModel from './settings-data-model';

@Injectable() export default class SomeService {
  constructor(settingsProvider: SettingsProvider) {
    settingsProvider.subscribe(settings => {
      this.settings = setttings;
    });
  }
}
</code>```

Body:
I have this ionic 2 provider:

@Injectable()
export class SettingsProvider {

    settingsData: SettingsDataModel = new SettingsDataModel(2, 2);
    subscriber = null;

    constructor(public http: Http, public storage: Storage) {
        console.log('Hello SettingsProvider Provider');
    }

    load(): void {
        this.storage.ready().then(() => {

            // Or to get a key/value pair
            this.storage.get('settingsData').then((val) => {
                this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
            });

        })
    }

    save() {
        this.storage.set('settingsData', this.settingsData);
        this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
    }

    subscribe(callback) { // how to register a subscriber the right way in ionic 2?
        this.subscriber = callback;
    }

}

I have implemented the ability that another class wanting to subscribe and get notifications by custom code (fragile one) what would be the implementation that another class could subscribe to it the right way?

Body:
In order to notify another chunk of code, such as another service, you can expose an observable property that represents an ongoing series of events. We can do this using a Subject.

Here is what this would look like

import { Subject } from 'rxjs/subject';

// singleton can use true privacy.
const settingsEventSource = new Subject<SettingsDataModel>();

@Injectable() export default class SettingsProvider {

  constructor(readonly http: Http, readonly storage: Storage) { }

  get settings$() {
    return settingsEventSource.asObservable(); // prevent others from sourcing events
  }

  settingsData = new SettingsDataModel(2, 2);

  async load() {
    await this.storage.ready();
    try {
      this.settingsData = await this.storage.get('settingsData');
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error loading settings.');
    }
  }

  async save() {
    try {
      await this.storage.set('settingsData', this.settingsData);
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error saving settings.');
    }
  }
}

A subscriber would look like this

import SettingsProvider from './settings-provider';
import SetttingsDataModel from './settings-data-model';

@Injectable() export default class SomeService {
  constructor(settingsProvider: SettingsProvider) {
    settingsProvider.subscribe(settings => {
      this.settings = setttings;
    });
  }
}


问:
How do I tell TYPO3 what it's URL is when using a reverse proxy?
I have:

A url www.my-website.com

A machine running TYPO3 with some hostname like typo3-website.my.internal.domain.com

A machine running Nginx which uses proxy_pass to send requests from www.my-website.com to typo3-website.my.internal.domain.com

A DNS A record for www.my-website.com pointing to the reverse-proxy machine.

When a backend user is working in the Page module, and they do right-click 'Show' on a page, it tries to open the page at the hostname of the machine TYPO3 is running on.

I want it to open the page under the actual website URL instead.

What setting do I need to change to make this work?

Things I have already tried which did not help:

Setting the trusted hosts pattern

'reverseProxyIP' => '*'

'reverseProxyHeaderMultiValue' => 'last'

答:
If you're trying to get TYPO to see the request as a request for a specific domain, you may want to use the following on your proxy block:</p>

```<code>proxy_set_header Host $proxy_host;
</code>```

Body:
If you're trying to get TYPO to see the request as a request for a specific domain, you may want to use the following on your proxy block:

proxy_set_header Host $proxy_host;


问:
Image Blob - Pop up window not showing content
I am working on displaying an image in blob

```<code>const file = new Blob([response.data], { type: 'image/png' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
        console.log('fileURL', fileURL);
        const image = document.createElement('img');
</code>```

I am getting this response

```<code>PNG

IHDR2²OósRGB®ÎégAMA±üa  pHYsÃÃÇo¨dã¼IDATx^ìý=ô<Ó¶Þ;ÐØ²g
cõ-EVÙÚÜòfã·#cV0¡\¡5È·Eüü$
]EGâ¹AD"    èî÷½þûeü÷_ý×ð\¸³µ°ñ F\¸³µ°ñ    F\¸³µ°ñ    F\¸³µ°ñ    FáË¥ßçòüù«&Þv~ÑTU?ÿ^Ý}öòóÜï×'sµùÔ¤|¼þåúE8ñp
ÎÛ3Î0
¹Þuv]áÌäZ×G#¬Ïv\f.ý{ý>ã¦ñï÷õÈõÁÛÅØã·n6«ÿÞpÙ.2ßÆ¹od
ÕEk+bv|_Hß5yÏçnØ1C´ìOÑÞøVÛ|¯
¤=ûsÔ_}BKíWÊó÷¿ç¯×ò_Þòu¸ÈÜ\dF¾a
¯FXí¸.Í\"øãñXÈ|8°àmÇýØa)@
F;L æ Øñæá_ðÉ¾´o»ìÔq#ºMxVÍ_±S.|íËs¿4×â7÷="/2GýÝù¹uyZ{c6Â×·°ãÛÆyqÎ_\ÁFøÎ)¼>a}¶àº¸r)Ý
ÄÛ® ÖáÌÁÁ\à"ó'â7|ú®HNë'/Õû
D ¶³c.!lÿÈ¶Ëhê¾ü"sÆß4ò@^¦¬XxcvÒ×·Ì½ÀEf$.í7a}¶àº4s)úáñtøÖEÛ´´ve¬í`Ê"UWäÃÛèÁ¿X}½2få¯âH²×n£Îy)U|Íg]O½{þ«}Ï®¹JÈ-ýðkÙÊ¯óR¸/ZLBd[NN±¨ùÖÌ¥x}³è:#"9¯yoLÃ·ÿBÎj¸Õvöú_æ´v8çï.òú©Cµ-/óÊõÑ   _{¹³æb[.êòRÙÖ£'lµo¦¬aò/ÌÕ1>ÿ¶ª<hPù½nüä7Ûzéú]Ïúgó=ó´ÞÛúºÓ¾KéåSÀÅ [¥8ìµÛ¸üí®õFxOáõÑë³×¥KËG1ýÿF&Êw\c´Û6¶Éðqò&¹mYÐÜ@ÝÄØtÓYÇÈ>Ó'´«6"áW±5k>\¥ñ[ëñîùkö[1X}Íãq{1K_1oÓç÷1ãÕ8t*Þå+V±]/G´v5ZI¨ÚÉ¹¼Æ5
µç°½Ö¿cþîÄÊLò#¬1CÆ³¾zrgô·mbÄjïøÛX9N½oû½â²ÖhÏZßlë]ßo=Ku³MâáôÙ;V¼W·õN}¹¾ýíÛH¨>4ðÆ`>çyÐ9x¾¿¢_;GC[
¯FXí¸.¾\J;Ýu¼í2ñÃccçp^iL|CJ~\vvobú<ª
Ê··á¾Þ9k¸ðÞùöwÆ ö£ôUcgû"þÏZ5Ú7xoìq*ò¡Zå@UÛySÞkc+{gsÛw¥Me;û²ÆS×_Ò&wzßwÉýçSoçÙÂ_#2Vïÿ¶3F¬FÏoýVì÷{¾YûÇï4WÍnÀ²]û·wãÖ;ÙëÅÂ>¯´g6®qÕüìåD·ñøëYë°®^°>Ûp]þ4´õáUíøH}{cø63}ccªXòâÙØ%yCZÛx6±óÉã/ýºkyïü
ûyncÖTYü¯b`Ì)|ÜrY÷9ÁÛªßA7úÖGSÃÂ¿]sßrSôÉöëÒË
¥Ms.Ù'ÕfÏ_ï¼
´<`Äï-¯+f#|ÈÜÑsqä·1bõÖñßddÐ7k¿óø½å¨Gíêùéy7·wÜ¾5¦k\#.¢ÂSx}4ÂúlÀuùÓ\ÒHãÀí\Yîæªí£§ÞÄV±AiÞóñHÜÏgyBØR:ñîù«ö¶¦r®úFÞ³Ø«¦®=+°\Ö}Î0_µ4y§o
ÝXi(ßv}ïGDrkåËË%_íò}æÿnÙ<ìoÖväÉ    _ÿâÛV1â°g|1\Ìñ{ë³cmZß¬ùÎí·½ß[¶Óóìßéy_onÏe!å%ïçÏq×¸Æ<´ý¾÷týu¯õFxNáõÑë³×åOsI; ["ÅhçÛÈä¸qDüL´¡o¸cçCIïÚ¶ß;Ã~sMùsßÅÿ*¿9½»@Ç;°voõâFãÛ®|<(ùÁî³ãð=Úa±mÎå'Ù¬:HùÛAËN«×C¾úrgì·ÝÀÃ¹ñ;hùNi¼ßóÍÚïöûlm},ÛÕóÓóðÆ[>çö|öKnÒ²/¿]ãqù
ìPx}4ÂúlÀuùÓ\j~àv»6²î :Ã61µ
ÛÄbÞ&;v>5}ÛoxrfMc1cvµ9;õáº·bZÞ/ëú: ßìÛ7VªøUúÉyNtN;iîÖþbÌÍ°|ÿÿÕ
®õ·V¯G|uæÎÐo»Sãwáv8¶Ý=ß¬ýîßud¯}n³úwvÇ×ÛsÙ¹pîÛs«~,&ïÄå¯½\ëñúhõÙëò§¹¤Æ#Ñ  ßF¹7Åº{h×ßàmb_IðÐ6ä+ï£æì±yPÞ=ï¦v$ÙðlóÃ7¦Ö. ÆX°q)Ù¾×ñóàöm/v+ñ=ó5çz[=;+ùÀg1Ù+6,Û$¿Ö
÷·6^ùêË=e_7ê·Ý¢õ=÷Ç/kXwíÚq~/8µ÷ö3ým½ëúÞÓo9ÇûW¿bóÜ<¯7·çµ¿æ"+Ô×®qY,qì5æ
ßÈº¸üÝ£¡-×G#¬Ïv\?Í¥øá±¬uðròKþè½Yl©´¥Â¸Mlû°ø¨mtÜNSÝùlvøØ÷Îß°ãÂ×´ö=ôIµòÃ1fDÉ¯}³îsMséÏÓ²Kö_í7È·o¬8Ú·(öóÂß&õÖïV¬ñ,´q95l¯¾üþÖmJm-ZyPèæ#fG}uä'¾ítÙ=ãù8óMä·+â+íê~&Zï"¿¹4«mfC]÷Ãó8¾ÞÜÏ~ªó¼I}÷¬igÜ3>Ø?»ßÉwähxOáõÑë³×¹ôÙèóBÞ°Ô|é"£¬-|æùóÅ|Ûú.gk?aâ¹ôáärÕUù3àïÅø©/|W¼È|Ýú&gk?a}¶àº ¾ñ+û¥X¾$|ÆÁ%/2o;Sßào°AáõÑë³×¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¢K?Ïð/á_ÿff¬á=þÑ´4?Ïsÿøz}Ä2ßç?þU{ß7?¾!×¿ÏÈð´´ß;Ög;®K+ :¾¯¿Èhÿ¢ñZÈ¿Û±)ßèût9ýÿXc\dt¼>bO
.2À.2`#^°>Ûp]¾*þ½~>!zAþzþÆøóÅÇ¿ß×   bó"S?K¾:sg¬ÎýcâÛà|¼)Ny>xóããóè¯÷àSà"6fk?aý«Ä'øh¾*¾úÀ_ÏÿSDlþMKåó"³x.A×ò_
±:÷OooðñVà"3¿ÞOØýõ¯à£iå<TÒFÚÄÒÙÍcÿ(ë~j·|@¬¶Y»ô§¬tÄ¨5>ßÈ×vÄÊGî·NOÌ?À×p×ZãocXgÇjò¼û"Sæb%m®%gÔxr[æ8+¾G×?0ÂG¯º}oOYñÎ´+¦[ï"Ü6¿ÐµÁÉïµHÝ1#Û)~Br{,>imø÷×9Ã×qoÝbkWç*¾ÎqÏÚü×÷¹6ñ×wlîjxæîÍpKB^Px}4ÂúlÀuiåR}øäd]5lÞê&IýÃ&Ê4Mp²
V{7ïÖm|2bWósE´çÖÔK·¿>¾§ó$;ÆÒ0ÆwÛtÄ¢G¯Ñ¶6oÇÔ~Js®|Äÿ3s_·->¦g¥Möëí)ó,´ÞIÛÊ³¦
</code>```

When I reffer some stackoverflow answers I understood my response is wrong. my questions is how to get correct binary response ..

答:
You can use XMLHttpRequest() or fetch() to get response as Blob

```<code>let url, w;
let request = fetch("/path/to/image");

request.then(function(response) {
  return response.blob() // return `Promise` which resolves to `Blob` of response
})
.then(function(blob) {
  url = URL.createObjectURL(blob);
  w = window.open(url);
})
.catch(function(err) {
  console.log(err)
});
</code>```

```<code>let url, w;

let request = new XMLHttpRequest();
request.open("GET", "/path/to/image");
request.responseType = "blob"; // set `responseType` to `"blob"`
request.onload = function() {
  url = URL.createObjectURL(blob);
  w = window.open(url);
}
request.onerror = function(e) {
  console.log(e);
}
request.send(null);
</code>```

Body:
I am working on displaying an image in blob

const file = new Blob([response.data], { type: 'image/png' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
        console.log('fileURL', fileURL);
        const image = document.createElement('img');

I am getting this response

PNG

IHDR2²OósRGB®ÎégAMA±üa  pHYsÃÃÇo¨dã¼IDATx^ìý=ô<Ó¶Þ;ÐØ²g
cõ-EVÙÚÜòfã·#cV0¡\¡5È·Eüü$
]EGâ¹AD"    èî÷½þûeü÷_ý×ð\¸³µ°ñ F\¸³µ°ñ    F\¸³µ°ñ    F\¸³µ°ñ    FáË¥ßçòüù«&Þv~ÑTU?ÿ^Ý}öòóÜï×'sµùÔ¤|¼þåúE8ñp
ÎÛ3Î0
¹Þuv]áÌäZ×G#¬Ïv\f.ý{ý>ã¦ñï÷õÈõÁÛÅØã·n6«ÿÞpÙ.2ßÆ¹od
ÕEk+bv|_Hß5yÏçnØ1C´ìOÑÞøVÛ|¯
¤=ûsÔ_}BKíWÊó÷¿ç¯×ò_Þòu¸ÈÜ\dF¾a
¯FXí¸.Í\"øãñXÈ|8°àmÇýØa)@
F;L æ Øñæá_ðÉ¾´o»ìÔq#ºMxVÍ_±S.|íËs¿4×â7÷="/2GýÝù¹uyZ{c6Â×·°ãÛÆyqÎ_\ÁFøÎ)¼>a}¶àº¸r)Ý
ÄÛ® ÖáÌÁÁ\à"ó'â7|ú®HNë'/Õû
D ¶³c.!lÿÈ¶Ëhê¾ü"sÆß4ò@^¦¬XxcvÒ×·Ì½ÀEf$.í7a}¶àº4s)úáñtøÖEÛ´´ve¬í`Ê"UWäÃÛèÁ¿X}½2få¯âH²×n£Îy)U|Íg]O½{þ«}Ï®¹JÈ-ýðkÙÊ¯óR¸/ZLBd[NN±¨ùÖÌ¥x}³è:#"9¯yoLÃ·ÿBÎj¸Õvöú_æ´v8çï.òú©Cµ-/óÊõÑ   _{¹³æb[.êòRÙÖ£'lµo¦¬aò/ÌÕ1>ÿ¶ª<hPù½nüä7Ûzéú]Ïúgó=ó´ÞÛúºÓ¾KéåSÀÅ [¥8ìµÛ¸üí®õFxOáõÑë³×¥KËG1ýÿF&Êw\c´Û6¶Éðqò&¹mYÐÜ@ÝÄØtÓYÇÈ>Ó'´«6"áW±5k>\¥ñ[ëñîùkö[1X}Íãq{1K_1oÓç÷1ãÕ8t*Þå+V±]/G´v5ZI¨ÚÉ¹¼Æ5
µç°½Ö¿cþîÄÊLò#¬1CÆ³¾zrgô·mbÄjïøÛX9N½oû½â²ÖhÏZßlë]ßo=Ku³MâáôÙ;V¼W·õN}¹¾ýíÛH¨>4ðÆ`>çyÐ9x¾¿¢_;GC[
¯FXí¸.¾\J;Ýu¼í2ñÃccçp^iL|CJ~\vvobú<ª
Ê··á¾Þ9k¸ðÞùöwÆ ö£ôUcgû"þÏZ5Ú7xoìq*ò¡Zå@UÛySÞkc+{gsÛw¥Me;û²ÆS×_Ò&wzßwÉýçSoçÙÂ_#2Vïÿ¶3F¬FÏoýVì÷{¾YûÇï4WÍnÀ²]û·wãÖ;ÙëÅÂ>¯´g6®qÕüìåD·ñøëYë°®^°>Ûp]þ4´õáUíøH}{cø63}ccªXòâÙØ%yCZÛx6±óÉã/ýºkyïü
ûyncÖTYü¯b`Ì)|ÜrY÷9ÁÛªßA7úÖGSÃÂ¿]sßrSôÉöëÒË
¥Ms.Ù'ÕfÏ_ï¼
´<`Äï-¯+f#|ÈÜÑsqä·1bõÖñßddÐ7k¿óø½å¨Gíêùéy7·wÜ¾5¦k\#.¢ÂSx}4ÂúlÀuùÓ\ÒHãÀí\Yîæªí£§ÞÄV±AiÞóñHÜÏgyBØR:ñîù«ö¶¦r®úFÞ³Ø«¦®=+°\Ö}Î0_µ4y§o
ÝXi(ßv}ïGDrkåËË%_íò}æÿnÙ<ìoÖväÉ    _ÿâÛV1â°g|1\Ìñ{ë³cmZß¬ùÎí·½ß[¶Óóìßéy_onÏe!å%ïçÏq×¸Æ<´ý¾÷týu¯õFxNáõÑë³×åOsI; ["ÅhçÛÈä¸qDüL´¡o¸cçCIïÚ¶ß;Ã~sMùsßÅÿ*¿9½»@Ç;°voõâFãÛ®|<(ùÁî³ãð=Úa±mÎå'Ù¬:HùÛAËN«×C¾úrgì·ÝÀÃ¹ñ;hùNi¼ßóÍÚïöûlm},ÛÕóÓóðÆ[>çö|öKnÒ²/¿]ãqù
ìPx}4ÂúlÀuùÓ\j~àv»6²î :Ã61µ
ÛÄbÞ&;v>5}ÛoxrfMc1cvµ9;õáº·bZÞ/ëú: ßìÛ7VªøUúÉyNtN;iîÖþbÌÍ°|ÿÿÕ
®õ·V¯G|uæÎÐo»Sãwáv8¶Ý=ß¬ýîßud¯}n³úwvÇ×ÛsÙ¹pîÛs«~,&ïÄå¯½\ëñúhõÙëò§¹¤Æ#Ñ  ßF¹7Åº{h×ßàmb_IðÐ6ä+ï£æì±yPÞ=ï¦v$ÙðlóÃ7¦Ö. ÆX°q)Ù¾×ñóàöm/v+ñ=ó5çz[=;+ùÀg1Ù+6,Û$¿Ö
÷·6^ùêË=e_7ê·Ý¢õ=÷Ç/kXwíÚq~/8µ÷ö3ým½ëúÞÓo9ÇûW¿bóÜ<¯7·çµ¿æ"+Ô×®qY,qì5æ
ßÈº¸üÝ£¡-×G#¬Ïv\?Í¥øá±¬uðròKþè½Yl©´¥Â¸Mlû°ø¨mtÜNSÝùlvøØ÷Îß°ãÂ×´ö=ôIµòÃ1fDÉ¯}³îsMséÏÓ²Kö_í7È·o¬8Ú·(öóÂß&õÖïV¬ñ,´q95l¯¾üþÖmJm-ZyPèæ#fG}uä'¾ítÙ=ãù8óMä·+â+íê~&Zï"¿¹4«mfC]÷Ãó8¾ÞÜÏ~ªó¼I}÷¬igÜ3>Ø?»ßÉwähxOáõÑë³×¹ôÙèóBÞ°Ô|é"£¬-|æùóÅ|Ûú.gk?aâ¹ôáärÕUù3àïÅø©/|W¼È|Ýú&gk?a}¶àº ¾ñ+û¥X¾$|ÆÁ%/2o;Sßào°AáõÑë³×¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¢K?Ïð/á_ÿff¬á=þÑ´4?Ïsÿøz}Ä2ßç?þU{ß7?¾!×¿ÏÈð´´ß;Ög;®K+ :¾¯¿Èhÿ¢ñZÈ¿Û±)ßèût9ýÿXc\dt¼>bO
.2À.2`#^°>Ûp]¾*þ½~>!zAþzþÆøóÅÇ¿ß×   bó"S?K¾:sg¬ÎýcâÛà|¼)Ny>xóããóè¯÷àSà"6fk?aý«Ä'øh¾*¾úÀ_ÏÿSDlþMKåó"³x.A×ò_
±:÷OooðñVà"3¿ÞOØýõ¯à£iå<TÒFÚÄÒÙÍcÿ(ë~j·|@¬¶Y»ô§¬tÄ¨5>ßÈ×vÄÊGî·NOÌ?À×p×ZãocXgÇjò¼û"Sæb%m®%gÔxr[æ8+¾G×?0ÂG¯º}oOYñÎ´+¦[ï"Ü6¿ÐµÁÉïµHÝ1#Û)~Br{,>imø÷×9Ã×qoÝbkWç*¾ÎqÏÚü×÷¹6ñ×wlîjxæîÍpKB^Px}4ÂúlÀuiåR}øäd]5lÞê&IýÃ&Ê4Mp²
V{7ïÖm|2bWósE´çÖÔK·¿>¾§ó$;ÆÒ0ÆwÛtÄ¢G¯Ñ¶6oÇÔ~Js®|Äÿ3s_·->¦g¥Möëí)ó,´ÞIÛÊ³¦

When I reffer some stackoverflow answers I understood my response is wrong. my questions is how to get correct binary response ..

Body:
You can use XMLHttpRequest() or fetch() to get response as Blob

let url, w;
let request = fetch("/path/to/image");

request.then(function(response) {
  return response.blob() // return `Promise` which resolves to `Blob` of response
})
.then(function(blob) {
  url = URL.createObjectURL(blob);
  w = window.open(url);
})
.catch(function(err) {
  console.log(err)
});

let url, w;

let request = new XMLHttpRequest();
request.open("GET", "/path/to/image");
request.responseType = "blob"; // set `responseType` to `"blob"`
request.onload = function() {
  url = URL.createObjectURL(blob);
  w = window.open(url);
}
request.onerror = function(e) {
  console.log(e);
}
request.send(null);


问:
SVG Animation, Layers, and Rendering Order
So I have an SVG that goes something like this:

```<code><svg>

<g id='leftArm'>
  <shapes for upper arm>
  <circle id='leftShoulderPivot' />
  <g id="leftForearm'>
    <shapes for lower arm>
    <circle id='leftElbowPivot' />
    <circle id='leftWristPivot' />
    <g id='leftHand'>
        <shapes for left hand>
    </g>
  </g>
</g>

<g id='torso'>
  <shapes>
</g>

</svg>
</code>```

This allows me to rotate the arm, forearm, and hand groups using the cx and cy vales of the appropriate pivots as the rotation origin.  Hooray!

However, I would like the forearm shapes to render beneath the torso shapes and the hand shapes to render on top of the torso shapes.  As is, when you rotate the arms down, the hands go behind the torso.

So I'm looking for one of two solutions:

a) a way to shift the rendering order of the existing SVG so forearms render first and hands render last

b) a way to move the hands groups out of the arm groups while still keeping the hands group's x,y, and rotation equal to the wrist pivot

Ideally I'd like to do this within the SVG and not rely on outside javascript.  I could write javascript that fixes the hand's position whenever other javascript moves the arms, but then I would not be able to use SVG animation for "idle animation" loops and the like.

Thank you!

答:
Your idea should work ... as seen below. Will not work in IE.

<svg viewBox="0 0 10 10" width="200" height="200">
<defs>

</defs>

  <g id="human">

    <g id="arm-left">
      <g id="arm-left-upper">
        <path d="M4 2l1 1"/>

        <g id="arm-left-lower">
          <path d="M5 3v1"/>

          <g id="arm-left-hand">
            <path d="M5 4h-.3"/>
          </g>
        </g>

      </g>
    </g>

    <g id="torso">
      <rect x="2" y="1.8" width="2" height="3"/>
    </g>

  </g>

</svg>```

Body:
So I have an SVG that goes something like this:

<svg>

<g id='leftArm'>
  <shapes for upper arm>
  <circle id='leftShoulderPivot' />
  <g id="leftForearm'>
    <shapes for lower arm>
    <circle id='leftElbowPivot' />
    <circle id='leftWristPivot' />
    <g id='leftHand'>
        <shapes for left hand>
    </g>
  </g>
</g>

<g id='torso'>
  <shapes>
</g>

</svg>

This allows me to rotate the arm, forearm, and hand groups using the cx and cy vales of the appropriate pivots as the rotation origin.  Hooray!

However, I would like the forearm shapes to render beneath the torso shapes and the hand shapes to render on top of the torso shapes.  As is, when you rotate the arms down, the hands go behind the torso.

So I'm looking for one of two solutions:

a) a way to shift the rendering order of the existing SVG so forearms render first and hands render last

b) a way to move the hands groups out of the arm groups while still keeping the hands group's x,y, and rotation equal to the wrist pivot

Ideally I'd like to do this within the SVG and not rely on outside javascript.  I could write javascript that fixes the hand's position whenever other javascript moves the arms, but then I would not be able to use SVG animation for "idle animation" loops and the like.

Thank you!

Body:
Your idea should work ... as seen below. Will not work in IE.

<svg viewBox="0 0 10 10" width="200" height="200">
<defs>
<style type="text/css">
path {fill: none; stroke: #000; stroke-width:.2;}
rect {fill: #999;}

#human {
  animation: sway 2s ease alternate infinite;
}

#arm-left-upper {
  animation: upanddown 4s ease alternate infinite;
  transform-origin: 0% 0%;
}

#arm-left-lower {
  animation: upanddown 3s ease alternate infinite;
  transform-origin: 0% 0%;
}

#arm-left-hand {
  animation: wave 1s ease alternate infinite;
  transform-origin: 100% 0%;
}

@keyframes sway {
  0% { transform: translateX(0); }
  100% { transform: translateX(2px); }
}

@keyframes upanddown {
  0% { transform: rotate(-30deg) }
  100% { transform: rotate(30deg); }
}

@keyframes wave {
  0% { transform: rotate(-80deg) }
  100% { transform: rotate(20deg); }
}
</style>
</defs>

  <g id="human">

    <g id="arm-left">
      <g id="arm-left-upper">
        <path d="M4 2l1 1"/>

        <g id="arm-left-lower">
          <path d="M5 3v1"/>

          <g id="arm-left-hand">
            <path d="M5 4h-.3"/>
          </g>
        </g>

      </g>
    </g>

    <g id="torso">
      <rect x="2" y="1.8" width="2" height="3"/>
    </g>

  </g>

</svg>


问:
SetInterval is not working for async tasks in Nodejs
I am new to nodejs. I have implemented simple async task and it should run every 10 min. Here set Interval function should run every x minutes as given and value for the variable api key should be updated. I don't know what is missing in it.

Could anyone let me know where I am going wrong.

```<code>var  csgTokenFile= rfr('models/csg-token-gen');
var apiKey;

setInterval(function(req, res) {
    csgTokenFile.key(function(messages) {
          console.log("key: ",messages);
          apiKey = messages;
    })
}, 20000);
</code>```

答:
There are a few problems with your code that when fixed can help you find the real problem - which is either in the csgTokenFile.key() function, its invocation or the expected behavior.

First of all, parameters in a function that is passed to setInterval() make no sense because it will be invoked with no arguments anyway. You're not using them here anyway but their presence is not a good sign because it seems that you may be confused about how it works.

Instead of this:

```<code>setInterval(function (req, res) {
    // ...
}, 20000);
</code>```

use this:

```<code>setInterval(function () {
    // ...
}, 20000);
</code>```

or this, because you're not using this anyway:

```<code>setInterval(() => {
    // ...
}, 20000);
</code>```

Now, the interface and the implementation of the function csgTokenFile.key() remains a mystery (and this is the most important source of the problem here, as it's either the function that doesn't work properly or it's the other code that doesn't use that function properly  - it's impossible to tell without looking at the source code of csgTokenFile.key() - also the rfr() function is a mystery and may be relevant here) but it looks like it may be following the Node convention of error-first callbacks, in which case it will pass error as the first argument to the callback and the actual data as the second.

If the csgTokenFile.key() takes traditional Node-style callbacks then it should be used like this:

```<code>setInterval(() => {
    csgTokenFile.key((error, messages) => {
        if (error) {
            return console.log('Error:', error);
        }
        console.log("key: ", messages);
        apiKey = messages;
    })
}, 20000);
</code>```

But as mentioned above it's impossible to tell from your question. It's just a hint.

Body:
I am new to nodejs. I have implemented simple async task and it should run every 10 min. Here set Interval function should run every x minutes as given and value for the variable api key should be updated. I don't know what is missing in it.

Could anyone let me know where I am going wrong.

var  csgTokenFile= rfr('models/csg-token-gen');
var apiKey;

setInterval(function(req, res) {
    csgTokenFile.key(function(messages) {
          console.log("key: ",messages);
          apiKey = messages;
    })
}, 20000);

Body:
There are a few problems with your code that when fixed can help you find the real problem - which is either in the csgTokenFile.key() function, its invocation or the expected behavior.

First of all, parameters in a function that is passed to setInterval() make no sense because it will be invoked with no arguments anyway. You're not using them here anyway but their presence is not a good sign because it seems that you may be confused about how it works.

Instead of this:

setInterval(function (req, res) {
    // ...
}, 20000);

use this:

setInterval(function () {
    // ...
}, 20000);

or this, because you're not using this anyway:

setInterval(() => {
    // ...
}, 20000);

Now, the interface and the implementation of the function csgTokenFile.key() remains a mystery (and this is the most important source of the problem here, as it's either the function that doesn't work properly or it's the other code that doesn't use that function properly  - it's impossible to tell without looking at the source code of csgTokenFile.key() - also the rfr() function is a mystery and may be relevant here) but it looks like it may be following the Node convention of error-first callbacks, in which case it will pass error as the first argument to the callback and the actual data as the second.

If the csgTokenFile.key() takes traditional Node-style callbacks then it should be used like this:

setInterval(() => {
    csgTokenFile.key((error, messages) => {
        if (error) {
            return console.log('Error:', error);
        }
        console.log("key: ", messages);
        apiKey = messages;
    })
}, 20000);

But as mentioned above it's impossible to tell from your question. It's just a hint.