问:
Using Unittest to test my python number guessing game
This is my first Stack overflow post and I hope to make a good impression.

I am working on a number guessing game in python to get my feet wet with unittest, but I am running into a silly conundrum.

The issue is that I want to create a unittest class that tests the following things

Does the pregenerated number match the guessed number

What does the program do if you enter in a letter

Do you see custom errors created when an error is occurring (in the try/except block)

My github project link is here -> https://github.com/robpedersendev/python-number-guessing-game

My main.py file is below

import random
import sys

def guessingGame(number, guess):  # Answer and guess was placed here so as to allow the test to insert
                                  # its own values into the game, but that is not working
    while true:

        try:
            guess = input(
                f"Number guesser.\t\t\n {name} choose a number between "
                f"{start} and {end}. Enter guess? : ")
            guess = int(guess)
            if guess < number:
                print("\n\nThat number is a tad low\n\n")
            elif guess > number:
                print("\n\nThat number is a tad high\n\n")
            else:
                print("\n\nCongrats, you chose the right number!\n\n")
                break

        except (TypeError, ValueError):
            print("Sorry, numbers only please")
            guess = str(f"\'{guess}\' Which is an invalid character")
            continue
        except (UnboundLocalError):
            print("Sorry, numbers only please")
            continue
        finally:
            print(f"{name}, your last successful guess was {guess}")

if __name__ == "__main__":
    true = True
    start = int(sys.argv[1])
    end = int(sys.argv[2])
    number = random.randrange(start, end)  # Selects the winning number
    name = input("\t\t\t\t\nHello stranger, whats your name? ")
    guessingGame()

```

<p>My test.py file looks like </p>

<pre class="lang-py prettyprint-override"><code>import unittest
import main

class TestMain(unittest.TestCase):
    def test_input(self):
        true = True
        number = 5
        guess = 5
        result = main.guessingGame(number, guess)
        self.assertEqual(result)

if __name__ == "__main__":
    unittest.main()
</code>```

I keep getting the error

Traceback (most recent call last):
  File "c:\Users\Robert\desktop\Side Projects\Udemy\Master python zero to Mastery\projects\python-number-guessing-game\test.py", line 10, in test_input
    result = main.guessingGame(number, guess)
  File "c:\Users\Robert\desktop\Side Projects\Udemy\Master python zero to Mastery\projects\python-number-guessing-game\main.py", line 6, in guessingGame
    while true:
NameError: name 'true' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

[Done] exited with code=1 in 0.375 seconds
```

<p>Error message</p>

<p>I know I have much to do and much to learn, but I am hoping for some helpful guidance!</p>

<p>UPDATE:</p>

<p>Ok, I figured out the problem (kinda). </p>

<p>The issue is within my main.py file I need to have this</p>

<pre class="lang-py prettyprint-override"><code>true = True

def guessingGame(number, guess, name='bob', start=1, end=20):
    while true:

        try:
            # guess = input(
            #     f"Number guesser.\t\t\n {name} choose a number between "
            #     f"{start} and {end}. Enter guess? : ")
            guess = int(guess)
            if guess < number:
                print("\n\nThat number is a tad low\n\n")
            elif guess > number:
                print("\n\nThat number is a tad high\n\n")
</code>```

My test.py file

import unittest
import main

class TestMain(unittest.TestCase):
    def test_input(self):
        number = 5
        guess = 5
        start = 1
        end = 20
        name = "bob"
        result = main.guessingGame(number, guess)
        self.assertEqual(guess, number)

if __name__ == "__main__":
    unittest.main()

```

I needed to predefine the values and comment out the first little block of code. Once I did that, my test passed!!
Any ideas, on how to get around this piece, or was this bad design on my part?

答:
https://book.crawfordc.com/anatomy-of-a-modern-test-file

Here’s something I wrote a while back about writing unit tests with hypothesis and pytest.
For testing what goes wrong when you enter a letter you use the with pytest.raises pattern.
Using hypothesis to generate the random numbers will also work much better than your random number generation.

(You should just make the code while True: and not a variable. But you would need to return false if it failed. It would probably be better as a loop. )

Body:
This is my first Stack overflow post and I hope to make a good impression.

I am working on a number guessing game in python to get my feet wet with unittest, but I am running into a silly conundrum.

The issue is that I want to create a unittest class that tests the following things

Does the pregenerated number match the guessed number

What does the program do if you enter in a letter

Do you see custom errors created when an error is occurring (in the try/except block)

My github project link is here -> https://github.com/robpedersendev/python-number-guessing-game

My main.py file is below

import random
import sys

def guessingGame(number, guess):  # Answer and guess was placed here so as to allow the test to insert
                                  # its own values into the game, but that is not working
    while true:

        try:
            guess = input(
                f"Number guesser.\t\t\n {name} choose a number between "
                f"{start} and {end}. Enter guess? : ")
            guess = int(guess)
            if guess < number:
                print("\n\nThat number is a tad low\n\n")
            elif guess > number:
                print("\n\nThat number is a tad high\n\n")
            else:
                print("\n\nCongrats, you chose the right number!\n\n")
                break

        except (TypeError, ValueError):
            print("Sorry, numbers only please")
            guess = str(f"\'{guess}\' Which is an invalid character")
            continue
        except (UnboundLocalError):
            print("Sorry, numbers only please")
            continue
        finally:
            print(f"{name}, your last successful guess was {guess}")

if __name__ == "__main__":
    true = True
    start = int(sys.argv[1])
    end = int(sys.argv[2])
    number = random.randrange(start, end)  # Selects the winning number
    name = input("\t\t\t\t\nHello stranger, whats your name? ")
    guessingGame()

My test.py file looks like

import unittest
import main

class TestMain(unittest.TestCase):
    def test_input(self):
        true = True
        number = 5
        guess = 5
        result = main.guessingGame(number, guess)
        self.assertEqual(result)

if __name__ == "__main__":
    unittest.main()

I keep getting the error

Traceback (most recent call last):
  File "c:\Users\Robert\desktop\Side Projects\Udemy\Master python zero to Mastery\projects\python-number-guessing-game\test.py", line 10, in test_input
    result = main.guessingGame(number, guess)
  File "c:\Users\Robert\desktop\Side Projects\Udemy\Master python zero to Mastery\projects\python-number-guessing-game\main.py", line 6, in guessingGame
    while true:
NameError: name 'true' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

[Done] exited with code=1 in 0.375 seconds

Error message

I know I have much to do and much to learn, but I am hoping for some helpful guidance!

UPDATE:

Ok, I figured out the problem (kinda).

The issue is within my main.py file I need to have this

true = True

def guessingGame(number, guess, name='bob', start=1, end=20):
    while true:

        try:
            # guess = input(
            #     f"Number guesser.\t\t\n {name} choose a number between "
            #     f"{start} and {end}. Enter guess? : ")
            guess = int(guess)
            if guess < number:
                print("\n\nThat number is a tad low\n\n")
            elif guess > number:
                print("\n\nThat number is a tad high\n\n")

My test.py file

import unittest
import main

class TestMain(unittest.TestCase):
    def test_input(self):
        number = 5
        guess = 5
        start = 1
        end = 20
        name = "bob"
        result = main.guessingGame(number, guess)
        self.assertEqual(guess, number)

if __name__ == "__main__":
    unittest.main()

I needed to predefine the values and comment out the first little block of code. Once I did that, my test passed!!
Any ideas, on how to get around this piece, or was this bad design on my part?


来源: stackexchange

问:
Slow API Request Loop in Python
I am trying to make some simple API requests from IEX's cloud server to grab closing prices for a number of securities. I am successfully pulling the data, but it is taking forever and its not even a lot of data. It would be a HUGE help if anyone would be able to help me restructure my code to make it faster and more efficient. Below is what I have thus far.. Thanks so much guys</p>

```<code>for i, row in Universe.iterrows():
    try:
        request = urllib.request.urlopen('https://cloud.iexapis.com/stable/stock/'+Universe['ticker'][i]+'/chart/date/'+Px_1+'?chartByDay=true&token=TOKEN').read()
        data = json.loads(request)
        Universe['Px_1'][i] = data[0]['close']
    except:
        Universe['Px_1'][i] = np.nan
</code>```

答:
Use the requests package to create a reusable persistent connection, that should make each request faster:

```<code>import requests

session = requests.Session()

for i, row in Universe.iterrows():
    try:
        data = session.get(url).json()
        Universe['Px_1'][i] = data[0]['close']
    except:
        Universe['Px_1'][i] = np.nan
</code>```

You can also run the requests in parallel using a thread pool:

```<code>from multiprocessing.dummy import Pool

def get_px1(ticker):
    url = 'https://cloud.iexapis.com/stable/stock/' + ticker + '/chart/date/' + Px_1 + '?chartByDay=true&token=TOKEN'
    try:
        data = session.get(url).json()
        return data[0]['close']
    except:
        return np.nan

Universe['Px_1'] = Pool(20).map(get_px1, Universe.ticker)
</code>```

But whether a session can be used across threads is not entirely clear, you may have to use something special or fall back to requests.get. And the server may not be happy with such a high rate of requests.

Also beware of that except as it may silently swallow bugs in your code.

ContentLicense: CC BY-SA 4.0

Title: Slow API Request Loop in Python

Body:
I am trying to make some simple API requests from IEX's cloud server to grab closing prices for a number of securities. I am successfully pulling the data, but it is taking forever and its not even a lot of data. It would be a HUGE help if anyone would be able to help me restructure my code to make it faster and more efficient. Below is what I have thus far.. Thanks so much guys

for i, row in Universe.iterrows():
    try:
        request = urllib.request.urlopen('https://cloud.iexapis.com/stable/stock/'+Universe['ticker'][i]+'/chart/date/'+Px_1+'?chartByDay=true&token=TOKEN').read()
        data = json.loads(request)
        Universe['Px_1'][i] = data[0]['close']
    except:
        Universe['Px_1'][i] = np.nan

Body:
Use the requests package to create a reusable persistent connection, that should make each request faster:

import requests

session = requests.Session()

for i, row in Universe.iterrows():
    try:
        data = session.get(url).json()
        Universe['Px_1'][i] = data[0]['close']
    except:
        Universe['Px_1'][i] = np.nan

You can also run the requests in parallel using a thread pool:

from multiprocessing.dummy import Pool

def get_px1(ticker):
    url = 'https://cloud.iexapis.com/stable/stock/' + ticker + '/chart/date/' + Px_1 + '?chartByDay=true&token=TOKEN'
    try:
        data = session.get(url).json()
        return data[0]['close']
    except:
        return np.nan

Universe['Px_1'] = Pool(20).map(get_px1, Universe.ticker)

But whether a session can be used across threads is not entirely clear, you may have to use something special or fall back to requests.get. And the server may not be happy with such a high rate of requests.

Also beware of that except as it may silently swallow bugs in your code.


问:
Clearing data from Apache Nutch
I am just starting out with Apache Nutch and I have been following some tutorials which I have been succesful with. I would now like to delete all of the data that was collected while I've been playing around, is there a way to easily clear all downloaded data from Nutch?</p>

答: Purely from the Nutch side deleting all the segments (usually within the crawldb directory) should get you back into a clean slate. If you've been indexing data into Solr/ES/etc., you might want to (potentially) remove all that data as well. This last step might depend on which storage engine you're using.

Title: Clearing data from Apache Nutch


问:
How to parse special characters in XML for iPad?
I am getting problem while parsing xml files that contains some special characters like single quote,double quote (', "")etc.I am using NSXMLParser's parser:foundCharacters:method to collect characters in my code.

```<code><synctext type = "word" >They raced to the park Arthur pointed to a sign "Whats that say" he asked Zoo said DW Easy as pie</synctext>
</code>```

When i parse and save the text from above tag of my xml file,the resultant string is appearing,in GDB, as

"\n\t\tThey raced to the park Arthur pointed to a sign \"Whats that say\" he asked Zoo said DW Easy as pie";

Observe there are 2 issues:

1)Unwanted characters at the beginning of the string.

2)The double quotes around Whats that say.

Can any one please help me how to get rid of these unwanted characters and how to read special characters properly.

答: NSString*string =[string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" \n\t"]];</p>

ContentLicense: CC BY-SA 3.0

Body:
I am getting problem while parsing xml files that contains some special characters like single quote,double quote (', "")etc.I am using NSXMLParser's parser:foundCharacters:method to collect characters in my code.

<synctext type = "word" >They raced to the park Arthur pointed to a sign "Whats that say" he asked Zoo said DW Easy as pie</synctext>

When i parse and save the text from above tag of my xml file,the resultant string is appearing,in GDB, as

"\n\t\tThey raced to the park Arthur pointed to a sign \"Whats that say\" he asked Zoo said DW Easy as pie";

Observe there are 2 issues:

1)Unwanted characters at the beginning of the string.

2)The double quotes around Whats that say.

Can any one please help me how to get rid of these unwanted characters and how to read special characters properly.


问:
Iterate run inscript command line tool over all html files in subfolders
I would like to convert a large number of html files to txt files. I have downloaded the inscript command line tool from github but I am struggling to apply it to all html files which are located in subdirectories and then save these files as text files in the same directory where the html files are located.

I have tried:

for f in ./ do inscript.py -o test.txt done

答:
The following should work:

```<code>for d in ./**/*/; do
  pushd "$d"
  for f in *.html(N); do
    out=test-${f%.html}.txt
    inscript.py -o "$out" "$f"
  done
  popd
done
</code>```

The pattern .**/*/ will recursively match the current directory and all its subdirectories. pushd will change to a directory, but remember the current working directory. inscript.py does its thing, then popd returns to the original working directory so that the next value of d continues to be a valid
relative directory.

Changing the working directory isn't strictly necessary; it just simplifies the file paths involved, because you focus on the name of the file and ignore the rest of the path.

Body:
The following should work:

for d in ./**/*/; do
  pushd "$d"
  for f in *.html(N); do
    out=test-${f%.html}.txt
    inscript.py -o "$out" "$f"
  done
  popd
done

The pattern .**/*/ will recursively match the current directory and all its subdirectories. pushd will change to a directory, but remember the current working directory. inscript.py does its thing, then popd returns to the original working directory so that the next value of d continues to be a valid
relative directory.

Changing the working directory isn't strictly necessary; it just simplifies the file paths involved, because you focus on the name of the file and ignore the rest of the path.


问:
Why does %timeit loop different number of times?
On Jupter Notebook, i was trying to compare time taken between the two methods for finding the index with max value.

In the Image, the first function took, 1000 loops, and the second took 10000 loops, is this increase in loops due to the method itself OR Jupyter Just added more loops to get more accurate time per loop even though the second function maybe took 1000 only, is that the case?

答:
use -r to limit the number of run's:

```<code>import time
%timeit -r1 time.sleep(2)
# 2 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r4 time.sleep(2)
# 2 s ± 800 µs per loop (mean ± std. dev. of 4 runs, 1 loop each)

%timeit time.sleep(2)
# 2 s ± 46.5 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
use -r to limit the number of run's:

import time
%timeit -r1 time.sleep(2)
# 2 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r4 time.sleep(2)
# 2 s ± 800 µs per loop (mean ± std. dev. of 4 runs, 1 loop each)

%timeit time.sleep(2)
# 2 s ± 46.5 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
RuntimeError: expected scalar type Long but found Int in loss = criterion(outputs, y_train)
I built this acoustic model with features dim = [1124823,13] and labels dim = [1124823,1] and I split both to train, test, and dev. The problem that when I try to run my model I get this error

RuntimeError: expected scalar type Long but found Int in

  loss = criterion(outputs, y_train)

```<code>import torch
import torch.nn as nn
from fela import feat, labels
from Dataloader import train_loader, test_loader, X_train, X_test, X_val, y_train, y_test, y_val

################################################################################################
input_size = 13
hidden1_size = 13
hidden2_size = 128
hidden3_size = 64
output_size = 50

################################################################################################

class DNN(nn.Module):
   def __init__(self, input_size, hidden2_size, hidden3_size, output_size):
       super(DNN, self).__init__()
       self.fc1 = nn.Linear(input_size, hidden1_size)
       self.relu1 = nn.ReLU()
       self.fc2 = nn.Linear(hidden1_size, hidden2_size)
       self.relu2 = nn.ReLU()
       self.fc3 = nn.Linear(hidden2_size, hidden3_size)
       self.relu3 = nn.ReLU()
       self.fc4 = nn.Linear(hidden3_size, output_size)
       self.relu4 = nn.ReLU()

   def forward(self, x):
       out = self.fc1(x)
       out = self.relu1(out)
       out = self.fc2(out)
       out = self.relu2(out)
       out = self.fc3(out)
       out = self.relu3(out)
       out = self.fc4(out)
       out = self.relu4(out)
       return out
################################################################################################
# Instantiate the model
batch_size = 50
n_iterations = 50
no_epochs = 80
model = DNN(input_size, hidden2_size, hidden3_size, output_size)

################################################################################################
# Define the loss criterion and optimizer
criterion = nn.CrossEntropyLoss()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
print(model)
########################################################################################################################
# train the network
iter = 0
for epoch in range(no_epochs):
   for i, (X_train, y_train) in enumerate(train_loader):
       optimizer.zero_grad()
       outputs = model(X_train)
       loss = criterion(outputs, torch.max(labels, 1)[1])
       loss.backward()
       optimizer.step()
       iter += 1
       if iter % 500 == 0:
           correct = 0
           total = 0
           for X_test, y_test in test_loader:
               outputs = model(X_test)
               _, predicted = torch.max(outputs.data, 1)
               total += labels.size(0)
               correct += (predicted == labels).sum()
           accuracy = 100 * correct / total
           print(iter, loss.data[0], accuracy)
</code>```

答:
I think no_epochs=0 with this initialization. Possibly (len(train_loader) / batch_size) > n_iterations. Then int(no_eps) = 0. Try to change no_epochs to 100 manually, for example.</p>

```<code>no_eps = n_iterations / (len(train_loader) / batch_size)
no_epochs = int(no_eps)
for epoch in range(no_epochs):
</code>```

Body:
I built this acoustic model with features dim = [1124823,13] and labels dim = [1124823,1] and I split both to train, test, and dev. The problem that when I try to run my model I get this error

RuntimeError: expected scalar type Long but found Int in

  loss = criterion(outputs, y_train)

import torch
import torch.nn as nn
from fela import feat, labels
from Dataloader import train_loader, test_loader, X_train, X_test, X_val, y_train, y_test, y_val

################################################################################################
input_size = 13
hidden1_size = 13
hidden2_size = 128
hidden3_size = 64
output_size = 50

################################################################################################

class DNN(nn.Module):
   def __init__(self, input_size, hidden2_size, hidden3_size, output_size):
       super(DNN, self).__init__()
       self.fc1 = nn.Linear(input_size, hidden1_size)
       self.relu1 = nn.ReLU()
       self.fc2 = nn.Linear(hidden1_size, hidden2_size)
       self.relu2 = nn.ReLU()
       self.fc3 = nn.Linear(hidden2_size, hidden3_size)
       self.relu3 = nn.ReLU()
       self.fc4 = nn.Linear(hidden3_size, output_size)
       self.relu4 = nn.ReLU()

   def forward(self, x):
       out = self.fc1(x)
       out = self.relu1(out)
       out = self.fc2(out)
       out = self.relu2(out)
       out = self.fc3(out)
       out = self.relu3(out)
       out = self.fc4(out)
       out = self.relu4(out)
       return out
################################################################################################
# Instantiate the model
batch_size = 50
n_iterations = 50
no_epochs = 80
model = DNN(input_size, hidden2_size, hidden3_size, output_size)

################################################################################################
# Define the loss criterion and optimizer
criterion = nn.CrossEntropyLoss()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
print(model)
########################################################################################################################
# train the network
iter = 0
for epoch in range(no_epochs):
   for i, (X_train, y_train) in enumerate(train_loader):
       optimizer.zero_grad()
       outputs = model(X_train)
       loss = criterion(outputs, torch.max(labels, 1)[1])
       loss.backward()
       optimizer.step()
       iter += 1
       if iter % 500 == 0:
           correct = 0
           total = 0
           for X_test, y_test in test_loader:
               outputs = model(X_test)
               _, predicted = torch.max(outputs.data, 1)
               total += labels.size(0)
               correct += (predicted == labels).sum()
           accuracy = 100 * correct / total
           print(iter, loss.data[0], accuracy)

Body:
I think no_epochs=0 with this initialization. Possibly (len(train_loader) / batch_size) > n_iterations. Then int(no_eps) = 0. Try to change no_epochs to 100 manually, for example.

no_eps = n_iterations / (len(train_loader) / batch_size)
no_epochs = int(no_eps)
for epoch in range(no_epochs):


问:
How can I predict single sample of data using min max scaler when I am training the model with min max scaled data?
As explained in similar question, one can easily test the data when you have a set of samples.
If the user has to predict the target of a single sample, then how to proceed. Please help.

Thanks.

答:
You can use the same MinMaxScaler() object you've used while training to transform your single instance. Here's an example.

```<code># training data
X_train = np.array([[1, 2], [3, 4], [5, 6]])
y_train = np.array([1, 0])

# scaler
scaler = MinMaxScaler().fit(X_train)
</code>```

Scaling X_train:

```<code>X_train_scaled = scaler.transform(X_train)
</code>```

Train the model using X_train_scaled and y_train ...

Predicting on the new sample np.array([7, 8]):

```<code>new_sample = np.array([7, 8]).reshape(1, -1)  # because the scaler expects a 2D array
scaler.transform(new_sample)  # pass this to model.predict()
</code>```

Edit:

How Min-Max Normalization works:

The following transformation is applied to each feature (Wikipedia Link):

We will apply that to X_train

```<code>X_train = np.array([[1, 2], [3, 4], [5, 6]])

array([[1, 2],
       [3, 4],
       [5, 6]])

# min, max of each feature
mn = np.min(X_train, axis=0)  # array([1, 2])
mx = np.max(X_train, axis=0)  # array([5, 6])
</code>```

Calculating the scaled version:

```<code>(X_train - mn) / (mx - mn)

array([[0. , 0. ],
   [0.5, 0.5],
   [1. , 1. ]])
</code>```

The above matches with the result of:

```<code>scaler = MinMaxScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)

array([[0. , 0. ],
       [0.5, 0.5],
       [1. , 1. ]])
</code>```

When you supply a new input vector, the same transformation should apply using the above mn and mx values

```<code>new_smaple = np.array([7, 8]).reshape(1, -1)
(new_sample - mn) / (mx - mn)

array([[1.5, 1.5]])
</code>```

This matches the output of scaler.transform(new_sample)

Also, you can extract min, max from a fitted MinMaxScaler object using scaler.data_min_ and scaler.data_max_ which will match the above mn and mx.

Body:
You can use the same MinMaxScaler() object you've used while training to transform your single instance. Here's an example.

# training data
X_train = np.array([[1, 2], [3, 4], [5, 6]])
y_train = np.array([1, 0])

# scaler
scaler = MinMaxScaler().fit(X_train)

Scaling X_train:

X_train_scaled = scaler.transform(X_train)

Train the model using X_train_scaled and y_train ...

Predicting on the new sample np.array([7, 8]):

new_sample = np.array([7, 8]).reshape(1, -1)  # because the scaler expects a 2D array
scaler.transform(new_sample)  # pass this to model.predict()

Edit:

How Min-Max Normalization works:

The following transformation is applied to each feature (Wikipedia Link):

We will apply that to X_train

X_train = np.array([[1, 2], [3, 4], [5, 6]])

array([[1, 2],
       [3, 4],
       [5, 6]])

# min, max of each feature
mn = np.min(X_train, axis=0)  # array([1, 2])
mx = np.max(X_train, axis=0)  # array([5, 6])

Calculating the scaled version:

(X_train - mn) / (mx - mn)

array([[0. , 0. ],
   [0.5, 0.5],
   [1. , 1. ]])

The above matches with the result of:

scaler = MinMaxScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)

array([[0. , 0. ],
       [0.5, 0.5],
       [1. , 1. ]])

When you supply a new input vector, the same transformation should apply using the above mn and mx values

new_smaple = np.array([7, 8]).reshape(1, -1)
(new_sample - mn) / (mx - mn)

array([[1.5, 1.5]])

This matches the output of scaler.transform(new_sample)

Also, you can extract min, max from a fitted MinMaxScaler object using scaler.data_min_ and scaler.data_max_ which will match the above mn and mx.


问:
SQL Server agent job failed. The package executed successfully
Job runs from SQL Server 2008 64 bit

Job step kicks off a SSIS package which runs successfully in BIDS. SSIS package copies data from an Oracle server to a database in SQL Server

The login for the connection manager for the Oracle database is different than the login used to create the SQL Agent job. I doubt this is the issue because I have another job which does the exact same thing with same parameters as this job and SSIS package the only difference is the Job that works connects to a different Oracle database.

The SSIS package is copying over the data nightly, record counts in source (Oracle) and destination (SQL Server) match but the error I get when I view the history is:

X - The job failed. The Job was invoked by.....

Selected row details:

  Date      5/31/2013 12:00:00 AM

  Log       Job History (DailyPull)

Step ID       0

  Server        SQL00

  Job Name      DailyPull

  Step Name     (Job outcome)

  Duration      00:34:28

  Sql Severity      0

  Sql Message ID        0

  Operator Emailed

  Operator Net sent

  Operator Paged

  Retries Attempted     0

Message

  The job failed. The Job was invoked by Schedule 20 (DailyPullSchedule). The last step to run was step 1 (DailyPull).

答:
Here is what worked for me:

The problem happened when we changed the account other than who created it and used a proxy for the new account.

copy the package to another folder

changed the Name for the 'CreatorComputerName'

changed the 'CreatorName' to the new account (our new account has a sys admin right)

save and reload the package in the job.

Success!


问:
open a text area on click of a button - Jquery
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

```<code><span style="width:20px;height:20px" class="remarkButton"></span>

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}
</code>```

答:
try this:

```<code><button id="showarea" name="showarea" type="button" value="Show Textarea" />
<textarea id="textarea" name="text"></textarea>
<button id="textarea-ok" name="ok" type="button" value="Ok" />
<script type="text/javascript">
$("#textarea, #textarea-ok").hide(); // or you can have hidden w/ CSS
$("#showarea").click(function(){
      $("#textarea").fadeIn(4000);
});
$("#textarea-ok").click(function(){
      $("#textarea").fadeOut(4000);
});
</code>```

It clears the space also so it looks like new textarea created and removed

Body:
Solution here: http://jsfiddle.net/kralco626/E9XVr/53/

Note: I think this is a duplicate of this question: how to show text area on button click? However, the OP of that question never followed up and I don't think any of the answers actually answer the question. I think Tomalak's comment on that question

Seems to me that, if anything, he wanted to pop up a textarea, wait for input into it, have the user press some 'OK' button then store the result in a variable.

Pretty much sums it up.

When the user clicks a button, I would like a text area to open in which the user can enter some text click an OK button and then the text area will close.

I don't want a dialog box, it's too intrusive, I want just a plain simple textarea or similar to open so that the top left of the text area is positioned at the bottom left of the button.

Thanks!

$(".remarkButton").button({ icons: { primary: "ui-icon-pencil" }, text: false }).click(function () {
       $(...something to show text area...).data("$clickedButton",$(this));
});

//called when the OK button on the text area is clicked
function saveRemark($referenceToTextArea)
{
$referenceToTextArea.data("$clickedButton").data("remark",$referenceToTextArea.text());
}

Body:
try this:

<button id="showarea" name="showarea" type="button" value="Show Textarea" />
<textarea id="textarea" name="text"></textarea>
<button id="textarea-ok" name="ok" type="button" value="Ok" />
<script type="text/javascript">
$("#textarea, #textarea-ok").hide(); // or you can have hidden w/ CSS
$("#showarea").click(function(){
      $("#textarea").fadeIn(4000);
});
$("#textarea-ok").click(function(){
      $("#textarea").fadeOut(4000);
});

It clears the space also so it looks like new textarea created and removed


问:
Asp.Net Core 3.1 Cookie Authentication loop to login page
When I successfully signed in to the HTTP context and I'm redirected to the home controller, the Authorize Attribute of the HomeController redirects me to the login path, because I don't know. (Infinite loop)

The validate async method doesn't sign me out or reject the cookie (I checked it.)

But where's the problem?
I have the same authentication process in an ASP.NET Core 2.1 project and there it works perfectly.

I test it with a custom authorize attribute to check the context. In the context I've a principal and I'm authenticated.

But why redirect me the standard authorize attribute?

My configuration is:

HomeController.cs

```<code>public class HomeController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        return this.View("Index");
    }
}
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/auth/login/";
                options.ExpireTimeSpan = TimeSpan.FromDays(7);
                options.Events.OnValidatePrincipal = ValidateAsync;
            });

        services.AddControllersWithViews();

        services.AddAntiforgery();

        services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
        {
            options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection"));
            options.EnableSensitiveDataLogging();
        });
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if(env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();
        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

public static async Task ValidateAsync(CookieValidatePrincipalContext context)
    {
        context = context ?? throw new ArgumentNullException(nameof(context));

        String userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value;

        if(userId == null)
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        ApplicationDbContext dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
        User user = await dbContext.Users.FindAsync(Guid.Parse(userId));

        if(user == null)
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        if(!user.StaySignedIn &&
            user.LastLogin != null &&
            (user.LastLogin.Subtract(TimeSpan.FromDays(1)) > DateTimeOffset.Now))
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }
    }
</code>```

AuthController.cs

```<code>[Route("/login")]
    [Route("/auth/login")]
    public async Task<IActionResult> Login([FromForm]LoginModel loginModel)
    {
        Claim nameIdentifier = new Claim(ClaimTypes.NameIdentifier, user.Id.ToString());

        ClaimsIdentity userIdentity = new ClaimsIdentity(new List<Claim> { nameIdentifier }, CookieAuthenticationDefaults.AuthenticationScheme);
        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);

        await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
        return this.RedirectToAction("Index", "Home");
    }
</code>```

答:
I found the solution for my problem.

The order of

```<code>app.UseAuthorization();
app.UseAuthentication();
</code>```

Must be changed and then it works.

Body:
When I successfully signed in to the HTTP context and I'm redirected to the home controller, the Authorize Attribute of the HomeController redirects me to the login path, because I don't know. (Infinite loop)

The validate async method doesn't sign me out or reject the cookie (I checked it.)

But where's the problem?
I have the same authentication process in an ASP.NET Core 2.1 project and there it works perfectly.

I test it with a custom authorize attribute to check the context. In the context I've a principal and I'm authenticated.

But why redirect me the standard authorize attribute?

My configuration is:

HomeController.cs

public class HomeController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        return this.View("Index");
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/auth/login/";
                options.ExpireTimeSpan = TimeSpan.FromDays(7);
                options.Events.OnValidatePrincipal = ValidateAsync;
            });

        services.AddControllersWithViews();

        services.AddAntiforgery();

        services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
        {
            options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection"));
            options.EnableSensitiveDataLogging();
        });
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if(env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();
        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

public static async Task ValidateAsync(CookieValidatePrincipalContext context)
    {
        context = context ?? throw new ArgumentNullException(nameof(context));

        String userId = context.Principal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value;

        if(userId == null)
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        ApplicationDbContext dbContext = context.HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
        User user = await dbContext.Users.FindAsync(Guid.Parse(userId));

        if(user == null)
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        if(!user.StaySignedIn &&
            user.LastLogin != null &&
            (user.LastLogin.Subtract(TimeSpan.FromDays(1)) > DateTimeOffset.Now))
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }
    }

AuthController.cs

[Route("/login")]
    [Route("/auth/login")]
    public async Task<IActionResult> Login([FromForm]LoginModel loginModel)
    {
        Claim nameIdentifier = new Claim(ClaimTypes.NameIdentifier, user.Id.ToString());

        ClaimsIdentity userIdentity = new ClaimsIdentity(new List<Claim> { nameIdentifier }, CookieAuthenticationDefaults.AuthenticationScheme);
        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);

        await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
        return this.RedirectToAction("Index", "Home");
    }

Body:
I found the solution for my problem.

The order of

app.UseAuthorization();
app.UseAuthentication();

Must be changed and then it works.


问:
Flex container items exceeding width
Hello I have a problem where my container is exceeding the maximum allowed width of my flex container (with justify space - between)

basically i divided my 3 children into 33.33%, but even so it exceeds the width:

img:

my jsx****:

```<code>const NavAcessibility = props => {
  return (
    <Accessibility>
      <ul>
        <li>
          <a>
            <p>Acessibilidade</p>
          </a>
        </li>
        <li>
          <a>A-</a>
        </li>
        <li>
          <a>A+</a>
        </li>
        <li>
          <a>
            <FontAwesomeIcon
              className="adjust"
              icon={faAdjust}
              size="1x"
              fixedWidth
              color="white"
            />
          </a>
        </li>
      </ul>
    </Accessibility>
  );
};

const ItemsTop = () => {
  return (
    <>
      <ImgWrap>
        <img src={LogoImg} />
      </ImgWrap>
      <SearchContainer>
        <IconContainer>
          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />
        </IconContainer>
        <input placeholder="Pesquisar" />
      </SearchContainer>
    </>
  );
};

const TopHeader = () => {
  return (
    <ContainerTop>
      <HeaderTop>
        <ItemsTop />
        <NavAcessibility />
      </HeaderTop>
    </ContainerTop>
  );
};
</code>```

my css:

```<code>export const ContainerTop = styled.div`
  position: relative;
  width: 100%;
  background: red;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.2);
`;

export const HeaderTop = styled.div`
  ${mxw80}
  padding-bottom: 10px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1em 0;
`;

export const ImgWrap = styled.div`
  width: 33.3333%;
  display: flex;
  align-items: center;
  & > img {
    width: 80px;
  }
`;

export const IconContainer = styled.div``;
export const SearchContainer = styled.div`
  display: inline-flex;
  align-items: center;
  width: 33.3333%;
  border-radius: 25px;
  overflow: hidden;
  height: 50px;
  border: 0;
  background: rgba(0, 0, 0, 0.1);
  box-shadow: 3px 3px 6px 0 rgba(0, 0, 0, 0.07);
  transition: all 0.4s;
  margin-right: 20px;
  ${IconContainer} {
    ${flexAlignCenter}
    width: 50px;
    padding: 0.5rem 1.3rem;
    height: 100%;
    & > svg {
      font-size: 1.3em;
      color: white;
    }
  }
  & > input {
    background: transparent;
    width: calc(100% - 50px);
    height: 100%;
    border: 0;
    padding: 0.5rem 0.5rem 0.5rem 0.5rem;
    outline: none;
    color: white;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    box-sizing: initial;
    font-family: Roboto, Arial, sans-serif;
    ::placeholder {
      font-size: 16px;
      color: white;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      box-sizing: initial;
      font-family: Roboto, Arial, sans-serif;
    }
  }
`;

export const Accessibility = styled.nav`
  width: 33.3333%;
  height: 100%;
  & > ul {
    ${flexAlignCenter}
    width:100%;
    flex-wrap: wrap;
    height: auto;
    justify-content: center;
  }
  & > ul > li {
    position: relative;
    display: inline-block;
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
    color: #fff;
    user-select: none;
  }
  & > ul > li:nth-child(2) {
    cursor: not-allowed;
    pointer-events: none;
    font-size: 18px;
    font-weight: 700;
    font-style: italic;
    opacity: 0.5;
    padding: 0 9px;
  }
  & > ul > li:nth-child(3) {
    font-size: 18px;
    font-weight: 700;
    font-size: 18px;
    font-weight: 700;
    padding: 0 9px;
  }
  & > ul > li > a {
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
  }
  & > ul > li > a > p {
    position: relative;
    display: inline-block;
    pointer-events: none;
    padding: 0 9px;
  }
`;
</code>```

example:

https://codesandbox.io/s/long-monad-m54pu

I can't find where I went wrong.

答:
Try to use width in 100% rather then in rem

```<code>.css-ydgvn1-HeaderTop {
    height: 100%;
    margin: 0 auto;
    max-width: 100% !important;
    width: 100% !important;
    padding-bottom: 10px;
    padding-top: 10px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-align-items: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    padding: 1em 0;
}
</code>```

Title: Flex container items exceeding width

Body:
Hello I have a problem where my container is exceeding the maximum allowed width of my flex container (with justify space - between)

basically i divided my 3 children into 33.33%, but even so it exceeds the width:

img:

my jsx****:

const NavAcessibility = props => {
  return (
    <Accessibility>

Acessibilidade

          A-

          A+

            <FontAwesomeIcon
              className="adjust"
              icon={faAdjust}
              size="1x"
              fixedWidth
              color="white"
            />

    </Accessibility>
  );
};

const ItemsTop = () => {
  return (
    <>
      <ImgWrap>

      </ImgWrap>
      <SearchContainer>
        <IconContainer>
          <FontAwesomeIcon
            className="searchIcon"
            icon={faSearch}
            size="2x"
            fixedWidth
            color="white"
          />
        </IconContainer>
        <input placeholder="Pesquisar" />
      </SearchContainer>
    </>
  );
};

const TopHeader = () => {
  return (
    <ContainerTop>
      <HeaderTop>
        <ItemsTop />
        <NavAcessibility />
      </HeaderTop>
    </ContainerTop>
  );
};

my css:

export const ContainerTop = styled.div`
  position: relative;
  width: 100%;
  background: red;
  box-shadow: 0 0 5px rgba(18, 23, 39, 0.2);
`;

export const HeaderTop = styled.div`
  ${mxw80}
  padding-bottom: 10px;
  padding-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1em 0;
`;

export const ImgWrap = styled.div`
  width: 33.3333%;
  display: flex;
  align-items: center;
  & > img {
    width: 80px;
  }
`;

export const IconContainer = styled.div``;
export const SearchContainer = styled.div`
  display: inline-flex;
  align-items: center;
  width: 33.3333%;
  border-radius: 25px;
  overflow: hidden;
  height: 50px;
  border: 0;
  background: rgba(0, 0, 0, 0.1);
  box-shadow: 3px 3px 6px 0 rgba(0, 0, 0, 0.07);
  transition: all 0.4s;
  margin-right: 20px;
  ${IconContainer} {
    ${flexAlignCenter}
    width: 50px;
    padding: 0.5rem 1.3rem;
    height: 100%;
    & > svg {
      font-size: 1.3em;
      color: white;
    }
  }
  & > input {
    background: transparent;
    width: calc(100% - 50px);
    height: 100%;
    border: 0;
    padding: 0.5rem 0.5rem 0.5rem 0.5rem;
    outline: none;
    color: white;
    font-size: 16px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    box-sizing: initial;
    font-family: Roboto, Arial, sans-serif;
    ::placeholder {
      font-size: 16px;
      color: white;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      box-sizing: initial;
      font-family: Roboto, Arial, sans-serif;
    }
  }
`;

export const Accessibility = styled.nav`
  width: 33.3333%;
  height: 100%;
  & > ul {
    ${flexAlignCenter}
    width:100%;
    flex-wrap: wrap;
    height: auto;
    justify-content: center;
  }
  & > ul > li {
    position: relative;
    display: inline-block;
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
    color: #fff;
    user-select: none;
  }
  & > ul > li:nth-child(2) {
    cursor: not-allowed;
    pointer-events: none;
    font-size: 18px;
    font-weight: 700;
    font-style: italic;
    opacity: 0.5;
    padding: 0 9px;
  }
  & > ul > li:nth-child(3) {
    font-size: 18px;
    font-weight: 700;
    font-size: 18px;
    font-weight: 700;
    padding: 0 9px;
  }
  & > ul > li > a {
    font-family: "Open Sans", sans-serif;
    font-size: 13px;
    line-height: 24px;
  }
  & > ul > li > a > p {
    position: relative;
    display: inline-block;
    pointer-events: none;
    padding: 0 9px;
  }
`;

example:

https://codesandbox.io/s/long-monad-m54pu

I can't find where I went wrong.

Body:
Try to use width in 100% rather then in rem

.css-ydgvn1-HeaderTop {
    height: 100%;
    margin: 0 auto;
    max-width: 100% !important;
    width: 100% !important;
    padding-bottom: 10px;
    padding-top: 10px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-align-items: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    padding: 1em 0;
}


问:
How to make div resize and scrollable between sibling divs
Basically I have this Angular material side nav with expandable navigation items

I want to make the second div scroll able when the items expand beyond the third div and also resizable so when I decrease the window size, it should always resize to fit between div 1 and and div 3.

I managed to implement the scrolling behavior with the following style applied:

```<code>title-div {
    min-height: 10%;
}

items-div {

    height: 80% //To force the info-div to be positioned at the bottom
    max-height: 80%
    overflow: auto;
}

info-div {
    min-height: 10%;
}
</code>```

However the resizing is not working properly. At a certain height the info-div(3) starts to get cut off instead of the item-div(2) resizing smaller for the info-div to fit in. How can I make this work?

答:
when you set your second dives height to the relative space it should take and use overflow: auto it should work.

a POC:

* {
  box-sizing: border-box;
  margin: 0;
}

.container {
  width: 100px;
  border: solid 2px;
}

.one,
.three {
  background: blue;
  border: solid 1px;
  height: 50px;
  padding: 10px;
}

.two {
  padding: 10px;
  overflow: auto;
  height: calc(100vh - 100px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="one">title</div>
  <div class="two">
    body<br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
  </div>
  <div class="three">title</div>

</div></code>```

Body:
Basically I have this Angular material side nav with expandable navigation items

I want to make the second div scroll able when the items expand beyond the third div and also resizable so when I decrease the window size, it should always resize to fit between div 1 and and div 3.

I managed to implement the scrolling behavior with the following style applied:

title-div {
    min-height: 10%;
}

items-div {

    height: 80% //To force the info-div to be positioned at the bottom
    max-height: 80%
    overflow: auto;
}

info-div {
    min-height: 10%;
}

However the resizing is not working properly. At a certain height the info-div(3) starts to get cut off instead of the item-div(2) resizing smaller for the info-div to fit in. How can I make this work?

Body:
when you set your second dives height to the relative space it should take and use overflow: auto it should work.

a POC:

* {
  box-sizing: border-box;
  margin: 0;
}

.container {
  width: 100px;
  border: solid 2px;
}

.one,
.three {
  background: blue;
  border: solid 1px;
  height: 50px;
  padding: 10px;
}

.two {
  padding: 10px;
  overflow: auto;
  height: calc(100vh - 100px);
}

<div class="container">
  <div class="one">title</div>
  <div class="two">
    body<br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
    <br> body
  </div>
  <div class="three">title</div>

</div>


问:
How to use Promises with async and await in Javascript
I have a method that returns a JSON of all objects

```<code>const getAllItems=async function(req,res){
    localDB.find({
        selector:{type:'item'},
        fields: ['_id', 'itemNumber','itemName',"compatablities","companyID"],
        sort: ['_id']
    }).then(async function (result) {
        if (result) {
            var refinedResult=[]
            //console.log(result.docs[0]);
            for (i = 0; i < result.docs.length; i++) {
                    var parentItem={
                        itemName:result.docs[i].itemName,
                        itemNumber:result.docs[i].itemNumber,
                        companyID:result.docs[i].companyID,
                        parentItemNo:"Parent"
                        }
                        console.log("before");

                        const resolvedN=await resolveName(parentItem.companyID);
                        console.log(resolvedN)
                        console.log("Passed");
                        refinedResult.push(parentItem);
                    for (j = 0; j < result.docs[i].compatablities.length || 0; j++) {
                        var oneCompatItemConstruct={
                            itemName:result.docs[i].itemName,
                            itemNumber:result.docs[i].compatablities[j].itemNumber,
                            companyID:result.docs[i].compatablities[j].companyID,
                            parentItemNo:result.docs[i].itemNumber,
                        }
                        //console.log(oneCompatItemConstruct);
                        refinedResult.push(oneCompatItemConstruct);
                }
              }
            return res.status(200).json({
                refinedResult
            })
        }
      }).catch(function (err) {
        console.log(err);
      })
}
</code>```

and the objects have an ID to be resolved to a name so
i wrote a function to resolve its name and takes cid as a param and returns a string

```<code>function resolveName(c_id){
    localDB.find({
        selector:{type:'company',_id:c_id},
        fields: ['companyName'],
        })
        .then(company=>{
        if (company.docs.length >=1) {
            console.log(c_id);
            const result = company.docs[0].companyName
            return result
        }
        else{
            return null
        }}).catch(err => {
                    console.log(err);
                    res.status(500).json({
                        error: err
                    });
                });
}
</code>```

i want the function to be called on each loop and update the code while its executing, how
would i do that?

答:
Simply wrap your function in a Promise and return values with resolve and reject :

```<code>function resolveName(c_id) {
    return new Promise((resolve, reject) => {
        localDB.find({
                selector: { type:'company', _id:c_id },
                fields: ['companyName'],
            })
            .then(company=> {
                if (company.docs.length >= 1) {
                    console.log(c_id);
                    const result = company.docs[0].companyName
                    resolve(result)
                }
                else {
                    resolve(null)
                }
            })
            .catch(err => {
                reject(err);
                res.status(500).json({
                error: err
            });
        });
    });
}
</code>```

Body:
I have a method that returns a JSON of all objects

const getAllItems=async function(req,res){
    localDB.find({
        selector:{type:'item'},
        fields: ['_id', 'itemNumber','itemName',"compatablities","companyID"],
        sort: ['_id']
    }).then(async function (result) {
        if (result) {
            var refinedResult=[]
            //console.log(result.docs[0]);
            for (i = 0; i < result.docs.length; i++) {
                    var parentItem={
                        itemName:result.docs[i].itemName,
                        itemNumber:result.docs[i].itemNumber,
                        companyID:result.docs[i].companyID,
                        parentItemNo:"Parent"
                        }
                        console.log("before");

                        const resolvedN=await resolveName(parentItem.companyID);
                        console.log(resolvedN)
                        console.log("Passed");
                        refinedResult.push(parentItem);
                    for (j = 0; j < result.docs[i].compatablities.length || 0; j++) {
                        var oneCompatItemConstruct={
                            itemName:result.docs[i].itemName,
                            itemNumber:result.docs[i].compatablities[j].itemNumber,
                            companyID:result.docs[i].compatablities[j].companyID,
                            parentItemNo:result.docs[i].itemNumber,
                        }
                        //console.log(oneCompatItemConstruct);
                        refinedResult.push(oneCompatItemConstruct);
                }
              }
            return res.status(200).json({
                refinedResult
            })
        }
      }).catch(function (err) {
        console.log(err);
      })
}

and the objects have an ID to be resolved to a name so
i wrote a function to resolve its name and takes cid as a param and returns a string

function resolveName(c_id){
    localDB.find({
        selector:{type:'company',_id:c_id},
        fields: ['companyName'],
        })
        .then(company=>{
        if (company.docs.length >=1) {
            console.log(c_id);
            const result = company.docs[0].companyName
            return result
        }
        else{
            return null
        }}).catch(err => {
                    console.log(err);
                    res.status(500).json({
                        error: err
                    });
                });
}

i want the function to be called on each loop and update the code while its executing, how
would i do that?

Body:
Simply wrap your function in a Promise and return values with resolve and reject :

function resolveName(c_id) {
    return new Promise((resolve, reject) => {
        localDB.find({
                selector: { type:'company', _id:c_id },
                fields: ['companyName'],
            })
            .then(company=> {
                if (company.docs.length >= 1) {
                    console.log(c_id);
                    const result = company.docs[0].companyName
                    resolve(result)
                }
                else {
                    resolve(null)
                }
            })
            .catch(err => {
                reject(err);
                res.status(500).json({
                error: err
            });
        });
    });
}


问:
Filemaker Pro 18 Import records from another file
I have two filemaker files, one has a set of tables and the other one has the same set of tables and a few more. I want to be able to import all the data from the first fm file to the second one. I know I can use the import function and import it table by table, but since there're around 70 tables so I'm hoping there can be a quicker way to do it.

Thanks in advance!

答:
There is a tool, DataMigration tool, that tool is able to make what you are trying to do.

https://support.filemaker.com/s/article/New-FileMaker-data-migration-tool?language=en_US

it is really extremely fast.


问:
How can I set redux state in a function (not component)
I have a onReady callback which fires whenever a global object is loaded from an external library. The object is only loaded when authentication is done.

There are pages that require authentication and there are some that are not, so i don't want to load it before loading the page.

I have therefore created a service  which is not a component, which fires previously mentioned onReady event, which should set the flag the the library has finished loading and I could do stuff with it. The solution that came to my mind is to set it globally in a redux store, and then whenever onReady is fired I would set the state like this.

```<code>export const onReady = event => {
  const dispatch = useDispatch();
  dispatch(setReady());
}
</code>```

Which results with following error:

```<code>×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
</code>```

So I am wondering how can I set global redux state in a service function? Other solutions solving the problem would also be appreciated.

答:
You can use dispatch directly from Redux:

```<code>import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  }
}
store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))
</code>```

Example from: https://redux.js.org/api/store#dispatchaction.

Replace the store with your own store.

Alternatively you can rename onReady to useOnReady, so React will mark it as a Hook.

Body:
I have a onReady callback which fires whenever a global object is loaded from an external library. The object is only loaded when authentication is done.

There are pages that require authentication and there are some that are not, so i don't want to load it before loading the page.

I have therefore created a service  which is not a component, which fires previously mentioned onReady event, which should set the flag the the library has finished loading and I could do stuff with it. The solution that came to my mind is to set it globally in a redux store, and then whenever onReady is fired I would set the state like this.

export const onReady = event => {
  const dispatch = useDispatch();
  dispatch(setReady());
}

Which results with following error:

×
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

So I am wondering how can I set global redux state in a service function? Other solutions solving the problem would also be appreciated.

Body:
You can use dispatch directly from Redux:

import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  }
}
store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

Example from: https://redux.js.org/api/store#dispatchaction.

Replace the store with your own store.

Alternatively you can rename onReady to useOnReady, so React will mark it as a Hook.


问:
Label encoding across multiple columns in scikit-learn
I'm trying to use scikit-learn's LabelEncoder to encode a pandas DataFrame of string labels. As the dataframe has many (50+) columns, I want to avoid creating a LabelEncoder object for each column; I'd rather just have one big LabelEncoder objects that works across all my columns of data.

Throwing the entire DataFrame into LabelEncoder creates the below error.  Please bear in mind that I'm using dummy data here; in actuality I'm dealing with about 50 columns of string labeled data, so need a solution that doesn't reference any columns by name.

```<code>import pandas
from sklearn import preprocessing

df = pandas.DataFrame({
    'pets': ['cat', 'dog', 'cat', 'monkey', 'dog', 'dog'],
    'owner': ['Champ', 'Ron', 'Brick', 'Champ', 'Veronica', 'Ron'],
    'location': ['San_Diego', 'New_York', 'New_York', 'San_Diego', 'San_Diego',
                 'New_York']
})

le = preprocessing.LabelEncoder()

le.fit(df)
</code>```

Traceback (most recent call last):
        File "", line 1, in
        File "/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/preprocessing/label.py", line 103, in fit
          y = column_or_1d(y, warn=True)
        File "/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 306, in column_or_1d
          raise ValueError("bad input shape {0}".format(shape))
      ValueError: bad input shape (6, 3)

Any thoughts on how to get around this problem?

答:
Using Neuraxle

TLDR; You here can use the FlattenForEach wrapper class to simply transform your df like: FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df).

With this method, your label encoder will be able to fit and transform within a regular scikit-learn Pipeline. Let's simply import:

from sklearn.preprocessing import LabelEncoder
from neuraxle.steps.column_transformer import ColumnTransformer
from neuraxle.steps.loop import FlattenForEach
```

<h2>Same shared encoder for columns:</h2>

<p>Here is how one shared LabelEncoder will be applied on all the data to encode it:</p>

<pre class="lang-py prettyprint-override"><code>    p = FlattenForEach(LabelEncoder(), then_unflatten=True)
</code>```

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [6, 7, 6, 8, 7, 7],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)
```

<h2>Different encoders per column:</h2>

<p>And here is how a first standalone LabelEncoder will be applied on the pets, and a second will be shared for the columns owner and location. So to be precise, we here have a mix of different and shared label encoders:</p>

<pre class="lang-py prettyprint-override"><code>    p = ColumnTransformer([
        # A different encoder will be used for column 0 with name "pets":
        (0, FlattenForEach(LabelEncoder(), then_unflatten=True)),
        # A shared encoder will be used for column 1 and 2, "owner" and "location":
        ([1, 2], FlattenForEach(LabelEncoder(), then_unflatten=True)),
    ], n_dimension=2)
</code>```

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [0, 1, 0, 2, 1, 1],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)
```

Body:
I'm trying to use scikit-learn's LabelEncoder to encode a pandas DataFrame of string labels. As the dataframe has many (50+) columns, I want to avoid creating a LabelEncoder object for each column; I'd rather just have one big LabelEncoder objects that works across all my columns of data.

Throwing the entire DataFrame into LabelEncoder creates the below error.  Please bear in mind that I'm using dummy data here; in actuality I'm dealing with about 50 columns of string labeled data, so need a solution that doesn't reference any columns by name.

import pandas
from sklearn import preprocessing

df = pandas.DataFrame({
    'pets': ['cat', 'dog', 'cat', 'monkey', 'dog', 'dog'],
    'owner': ['Champ', 'Ron', 'Brick', 'Champ', 'Veronica', 'Ron'],
    'location': ['San_Diego', 'New_York', 'New_York', 'San_Diego', 'San_Diego',
                 'New_York']
})

le = preprocessing.LabelEncoder()

le.fit(df)

Traceback (most recent call last):
        File "", line 1, in
        File "/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/preprocessing/label.py", line 103, in fit
          y = column_or_1d(y, warn=True)
        File "/Users/bbalin/anaconda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 306, in column_or_1d
          raise ValueError("bad input shape {0}".format(shape))
      ValueError: bad input shape (6, 3)

Any thoughts on how to get around this problem?

Body:
Using Neuraxle

TLDR; You here can use the FlattenForEach wrapper class to simply transform your df like: FlattenForEach(LabelEncoder(), then_unflatten=True).fit_transform(df).

With this method, your label encoder will be able to fit and transform within a regular scikit-learn Pipeline. Let's simply import:

from sklearn.preprocessing import LabelEncoder
from neuraxle.steps.column_transformer import ColumnTransformer
from neuraxle.steps.loop import FlattenForEach

Same shared encoder for columns:

Here is how one shared LabelEncoder will be applied on all the data to encode it:

    p = FlattenForEach(LabelEncoder(), then_unflatten=True)

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [6, 7, 6, 8, 7, 7],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)

Different encoders per column:

And here is how a first standalone LabelEncoder will be applied on the pets, and a second will be shared for the columns owner and location. So to be precise, we here have a mix of different and shared label encoders:

    p = ColumnTransformer([
        # A different encoder will be used for column 0 with name "pets":
        (0, FlattenForEach(LabelEncoder(), then_unflatten=True)),
        # A shared encoder will be used for column 1 and 2, "owner" and "location":
        ([1, 2], FlattenForEach(LabelEncoder(), then_unflatten=True)),
    ], n_dimension=2)

Result:

    p, predicted_output = p.fit_transform(df.values)
    expected_output = np.array([
        [0, 1, 0, 2, 1, 1],
        [1, 3, 0, 1, 5, 3],
        [4, 2, 2, 4, 4, 2]
    ]).transpose()
    assert np.array_equal(predicted_output, expected_output)


问:
How to list all the recently installed softwares in linux other than rpm and yum command
I want to list all the recently installed softwares in linux other than rpm and yum command(because these commands will list only the softwares installed using them). I want to list apps installed from all the sources.</p>

答: You can't. Software can be installed using so many ways that you can't think about all. Of course you can check in /opt and /usr/local but it's big probability you will miss something.


问:
Large Binary (byte[]) File transfer through WCF
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>
</code>```

Client (Asp.net page) Web.Config

```<code><system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>
</code>```

答:
Have you had a look at using Streaming Transfer?

Windows Communication Foundation (WCF)
  can send messages using either
  buffered or streamed transfers. In the
  default buffered-transfer mode, a
  message must be completely delivered
  before a receiver can read it. In
  streaming transfer mode, the receiver
  can begin to process the message
  before it is completely delivered. The
  streaming mode is useful when the
  information that is passed is lengthy
  and can be processed serially.
  Streaming mode is also useful when the
  message is too large to be entirely
  buffered.

http://msdn.microsoft.com/en-us/library/ms789010.aspx

Body:
I am trying to build a WCF service that allows me to send large binary files from clients to the service.

However I am only able to successfully transfer files up to 3-4MB. (I fail when I try to transfer 4.91MB and, off course, anything beyond)

The Error I get if I try to send the 4.91MB file is:

Exception Message: An error occurred while receiving the HTTP response to http://localhost:56198/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.

Inner Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.

Inner Exception Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Inner Exception Message: An existing connection was forcibly closed by the remote host

This error occurs at client side as soon as the byte[] file is sent as a method parameter to the exposed service method.

I have a breakpoint at the service method's first line, in case of successful file transfers (below 3MB) that break point is hit and the file gets transferred. However in this case as soon as the method is called, the error comes. The breakpoint in the service is not hit in case of this error.

I am going to paste my  sections of my Service Web.config and Asp Page (Client) Web.config. If you also require the code that send the file and accepts the file, let me know, I'll send that as well.

Service Web.Config

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpEndpointBinding" closeTimeout="01:01:00"
      openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
      messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
        maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
    <services>
        <service behaviorConfiguration="DragDrop.Service.ServiceBehavior" name="DragDrop.Service.Service">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpEndpointBinding" contract="DragDrop.Service.IService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="DragDrop.Service.ServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

Client (Asp.net page) Web.Config

<system.serviceModel>
<bindings>
   <basicHttpBinding>
      <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
         openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
         allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
         maxBufferSize="2147483646" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
         messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedResponse"
         useDefaultWebProxy="true">
         <readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646"
            maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
         <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
               realm="">
               <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
         </security>
      </binding>
   </basicHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="debuggingBehaviour">
      <dataContractSerializer maxItemsInObjectGraph="2147483646" />
    </behavior>
  </endpointBehaviors>
</behaviors>

<client>
   <endpoint address="http://localhost:56198/Service.svc" binding="basicHttpBinding"
      bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference.IService"
      name="BasicHttpBinding_IService" behaviorConfiguration="debuggingBehaviour" />
</client>
</system.serviceModel>


问:
Laravel include image in Blade file not from public folder
I need to include an image in a blade from my source folder without passing from the public folder, this due the blade is used to generate a pdf file, not a view for a public page. How can I do this? Every answer/example I found uses the public folder, but I don't need it.</p>

答:
You can use storage_path() to retrieve a file from storage and include it.

Ref: https://laravel.com/docs/5.7/helpers#method-storage-path


问:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
</code>```

application.properties:

```<code># Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test
</code>```

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

I have started mongod with the following output:

```<code>C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)
</code>```

答: I removed an obsolete dependency on mybatis in the pom.xml to get mine running.</p>

Body:
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

application.properties:

# Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

I have started mongod with the following output:

C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)


问:
Azure- zip push deployment for a function app doesn't work
I am trying to update the code in my App Function from the CLI using the kudu zip push deployment for a function app.
I am using this command-

```<code>az functionapp deployment source config-zip --name funcApp1 --resource-group MyGroup --src C:\Users\user\Documents\funcApp1.zip
</code>```

And getting this output-

```<code>Getting scm site credentials for zip deployment Starting zip deployment. This operation can take a while to complete ... Deployment endpoint responded with status code 202
</code>```

It looks like it worked but I can't see the updated code in the App Function from the CLI.
What can be the problem?

答:
Seems like you use the wrong command.

Have a look of this:https://learn.microsoft.com/en-us/azure/azure-functions/deployment-zip-push#cli

The command should be:

```<code>az functionapp deployment source config-zip -g <resource_group> -n <app_name> --src <zip_file_path>
</code>```

Body:
I am trying to update the code in my App Function from the CLI using the kudu zip push deployment for a function app.
I am using this command-

az functionapp deployment source config-zip --name funcApp1 --resource-group MyGroup --src C:\Users\user\Documents\funcApp1.zip

And getting this output-

Getting scm site credentials for zip deployment Starting zip deployment. This operation can take a while to complete ... Deployment endpoint responded with status code 202

It looks like it worked but I can't see the updated code in the App Function from the CLI.
What can be the problem?

Body:
Seems like you use the wrong command.

Have a look of this:https://learn.microsoft.com/en-us/azure/azure-functions/deployment-zip-push#cli

The command should be:

az functionapp deployment source config-zip -g <resource_group> -n <app_name> --src <zip_file_path>


问:
How to import a txt file with single quote mark in a variable and another in another variable
I have a file prova.txt, which contains:

```<code>001|PROVA|MILANO|1000
002|'80S WERE GREAT|FORLI'|1100
003|'80S WERE GREAT|ROMA|1110
</code>```

I'm importing it as a SAS dataset with this code:

```<code>libname mylib "/my/lib";

data prova;
infile '/my/lib/prova.txt'
    dlm='|' dsd lrecl=50 truncover;
format
    codice  $3.
    nome    $20.
    luogo   $20.
    importo 4.
    ;
input
    codice  :$3.
    nome    :$20.
    luogo   :$20.
    importo :4.
    ;
run;
</code>```

And I get this result:

As you can see, the first and the third records are imported well, whereas the second has nome = 80S WERE GREAT|FORLI and the rest of the variable are a mess.

How can I correctly import this file?

P.S. = the single quote marks in the file are correct. FORLI' is name of a town in Italy and there is a firm whose name begins with '80. Of course these are not the real names, but the real case is exactly like that. I need to import the variables with a quote marks in their content.

答:
The DSD and DLM cause the single quoted (') embedded delimiter (|) to be part of the data value.

Remove the DSD options and the delimiter will not be considered 'value embedded' and thus become a value separator for the example case of 002|'80S WERE GREAT|FORLI'|1100

The format statement implicitly defines a variable value type and length if it contains the first mention of a variable in the step.  Because of that you can simplify the input statement to be just a list of the variables:

```<code>filename sample 'c:\temp\sample.txt';
data _null_;
  file sample;
  input;
  put _infile_;
datalines;
001|PROVA|MILANO|1000
002|'80S WERE GREAT|FORLI'|1100
003|'80S WERE GREAT|ROMA|1110
;

data want;
data prova;
infile sample dlm='|' lrecl=50 truncover;
format
    codice  $3.
    nome    $20.
    luogo   $20.
    importo 4.
    ;
input
    codice
    nome
    luogo
    importo
    ;

putlog _infile_;
run;

proc print;
run;
</code>```

Body:
I have a file prova.txt, which contains:

001|PROVA|MILANO|1000
002|'80S WERE GREAT|FORLI'|1100
003|'80S WERE GREAT|ROMA|1110

I'm importing it as a SAS dataset with this code:

libname mylib "/my/lib";

data prova;
infile '/my/lib/prova.txt'
    dlm='|' dsd lrecl=50 truncover;
format
    codice  $3.
    nome    $20.
    luogo   $20.
    importo 4.
    ;
input
    codice  :$3.
    nome    :$20.
    luogo   :$20.
    importo :4.
    ;
run;

And I get this result:

As you can see, the first and the third records are imported well, whereas the second has nome = 80S WERE GREAT|FORLI and the rest of the variable are a mess.

How can I correctly import this file?

P.S. = the single quote marks in the file are correct. FORLI' is name of a town in Italy and there is a firm whose name begins with '80. Of course these are not the real names, but the real case is exactly like that. I need to import the variables with a quote marks in their content.

Body:
The DSD and DLM cause the single quoted (') embedded delimiter (|) to be part of the data value.

Remove the DSD options and the delimiter will not be considered 'value embedded' and thus become a value separator for the example case of 002|'80S WERE GREAT|FORLI'|1100

The format statement implicitly defines a variable value type and length if it contains the first mention of a variable in the step.  Because of that you can simplify the input statement to be just a list of the variables:

filename sample 'c:\temp\sample.txt';
data _null_;
  file sample;
  input;
  put _infile_;
datalines;
001|PROVA|MILANO|1000
002|'80S WERE GREAT|FORLI'|1100
003|'80S WERE GREAT|ROMA|1110
;

data want;
data prova;
infile sample dlm='|' lrecl=50 truncover;
format
    codice  $3.
    nome    $20.
    luogo   $20.
    importo 4.
    ;
input
    codice
    nome
    luogo
    importo
    ;

putlog _infile_;
run;

proc print;
run;


问:
How can i format the date into specified format which comes from db in <g:select>
I need to have a dropdown which holds dates.

when i write

```<code><g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />
</code>```

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?

答:
This is the shortest solution I can think of (untested):</p>

```<code><g:set var="dateFormat" value="MM/dd/yyyy"/>

<g:select id="dob" name="dob" from="${Person.list().dateOfBirth*.format(dateFormat)}"
    value="${personInstance?.dateOfBirth?.format(dateFormat)}" />
</code>```

Body:
I need to have a dropdown which holds dates.

when i write

<g:select id="dob" name="dob" from="${Person.list().dateOfBirth}"  value="${personInstance?.dateOfBirth}" />

this displays the date in the format 2011-05-17 00:00:00.0 But i need to have the format mm/dd/yyyy.

How can i do that?

Body:
This is the shortest solution I can think of (untested):

<g:set var="dateFormat" value="MM/dd/yyyy"/>

<g:select id="dob" name="dob" from="${Person.list().dateOfBirth*.format(dateFormat)}"
    value="${personInstance?.dateOfBirth?.format(dateFormat)}" />