问:
const_defined? vs. defined? in Ruby
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

```<code>if defined? :String
</code>```

or I can write

```<code>if self.class.const_defined? :String
</code>```

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

答:
TL;DR

There may be cases where you can use them interchangeably, but one is a keyword and the other a method. In addition, the semantics and return values of the two are quite different.

Keywords vs. Methods

Among other things, one key difference is that Module#const_defined? is a method on a class or module that looks up constants in a class and its ancestors, while defined? is a keyword that determines whether its argument is currently known at the calling point in your code.

For example:

```<code>char = 'a'

char.const_defined?
#=> NoMethodError (undefined method `const_defined?' for "a":String)

defined? char
#=> "local-variable"
</code>```

Exceptions vs. Return Values

If you're only concerned about constants, then the main difference is that you can use defined? to determine whether a constant is currently in scope without triggering a NoMethodError exception. For example:

```<code>defined? String
#=> "constant"

defined? FooBarBaz
#=> nil
</code>```

As a bonus, defined? will tell what type of object you're passing as an argument (e.g. "constant"), while #const_defined? returns a truthy value.

```<code>Float.constants
#=> [:ROUNDS, :RADIX, :MANT_DIG, :DIG, :MIN_EXP, :MAX_EXP, :MIN_10_EXP, :MAX_10_EXP, :MIN, :MAX, :EPSILON, :INFINITY, :NAN]

defined? Float::NAN
#=> "constant"

Float.const_defined? :NAN
#=> true
</code>```

As a rule of thumb, it's often considered best practice to reserve exceptions for handling something unexpected that may require your application to halt. Introspection or branching should generally rely on return values or Booleans, so defined? is usually a better choice if you aren't already expecting a given class to already be defined and available within the current scope.

Title: const_defined? vs. defined? in Ruby

Body:
To test, whether a constant (say: a class) is known at a certain point in the code, I can write for instance:

if defined? :String

or I can write

if self.class.const_defined? :String

Is there a situation where I these two ways of testing would make a difference? Note that I don't ask about the case where I have an explicit receiver, such as MyModule.const_defined? :Something, but only for the case where I want to test whether a certain constant (which in my case happens to be a constant denoting a class) is already defined.

Body:
TL;DR

There may be cases where you can use them interchangeably, but one is a keyword and the other a method. In addition, the semantics and return values of the two are quite different.

Keywords vs. Methods

Among other things, one key difference is that Module#const_defined? is a method on a class or module that looks up constants in a class and its ancestors, while defined? is a keyword that determines whether its argument is currently known at the calling point in your code.

For example:

char = 'a'

char.const_defined?
#=> NoMethodError (undefined method `const_defined?' for "a":String)

defined? char
#=> "local-variable"

Exceptions vs. Return Values

If you're only concerned about constants, then the main difference is that you can use defined? to determine whether a constant is currently in scope without triggering a NoMethodError exception. For example:

defined? String
#=> "constant"

defined? FooBarBaz
#=> nil

As a bonus, defined? will tell what type of object you're passing as an argument (e.g. "constant"), while #const_defined? returns a truthy value.

Float.constants
#=> [:ROUNDS, :RADIX, :MANT_DIG, :DIG, :MIN_EXP, :MAX_EXP, :MIN_10_EXP, :MAX_10_EXP, :MIN, :MAX, :EPSILON, :INFINITY, :NAN]

defined? Float::NAN
#=> "constant"

Float.const_defined? :NAN
#=> true

As a rule of thumb, it's often considered best practice to reserve exceptions for handling something unexpected that may require your application to halt. Introspection or branching should generally rely on return values or Booleans, so defined? is usually a better choice if you aren't already expecting a given class to already be defined and available within the current scope.


来源: stackexchange

问:
Am i violating any NF RULE on my database design?
Good day!

I am a newbie on creating database... I need to create a db for my recruitment web application.

My database schema is as follows:

NOTE: I included the applicant_id on other tables... e.g. exam, interview, exam type.

Am i violating any normalization rule? If i do, what do you recommend to improve my design? Thank you

答:
Overall looks good. A few minor points to consider:

Interviewer is also a person. You will need to use program logic to prevent different / misspellings.

The longest real life email address I've seen was 62 characters.

In exam you use the reserved word date for a column name

(subjective) I would rename applicant_date to applied_at

I don't see a postal / zip code for the applicant

All result columns are VARCHAR(4). If they use the same values, can they be normalized?

Birthdate is better to store then age. You don't want to schedule someone for an interview on their birthdate (or if you're cruel by nature, you do want that :) ). Age can be derived from it and will also be correct at all times.

EDIT:
Given that result is PASS or FAIL, simply declare the field a boolean and name it 'passed'. A lot faster.

ContentLicense: CC BY-SA 3.0


答:
First things first, defined? is a keyword which behaves a bit similar similar to a method. It receives the name of the thing (variable, constant, ...) to check. What makes this method different from all others is that the parser will not resolve the value of the given name but rather check directly for whether it is defined (hence the keyword property). To check if a constant is defined, you thus have to pass the actual name (rather than a Symbol):

```<code>if defined?(String)
</code>```

The const_defined? on the oither hand is more regular. It expects a Symbol or String with the name of a constant and checks whether it is defined on the receiver.

Now as for the differences between the two (when used correctly): if you use them both within the context of an instance method to check for the existence of a constant, they work the same.

When running e.g. in a class definition (such that self is e.g. a class), you need to make sure to use the correct receiver for your const_defined method, e.g. if self.const_defined? :String.

Also, defined? can check for a lot more than just constants (e.g. methods, expressions, variables, ...)

If you want to use this to make sure you actually have the name of a constant at hand in a given variable, you need to use const_defined?. If you want to "statically" check whether an constant was defined, you can use defined?.

ContentLicense: CC BY-SA 4.0

Title: const_defined? vs. defined? in Ruby

Body:
First things first, defined? is a keyword which behaves a bit similar similar to a method. It receives the name of the thing (variable, constant, ...) to check. What makes this method different from all others is that the parser will not resolve the value of the given name but rather check directly for whether it is defined (hence the keyword property). To check if a constant is defined, you thus have to pass the actual name (rather than a Symbol):

if defined?(String)

The const_defined? on the oither hand is more regular. It expects a Symbol or String with the name of a constant and checks whether it is defined on the receiver.

Now as for the differences between the two (when used correctly): if you use them both within the context of an instance method to check for the existence of a constant, they work the same.

When running e.g. in a class definition (such that self is e.g. a class), you need to make sure to use the correct receiver for your const_defined method, e.g. if self.const_defined? :String.

Also, defined? can check for a lot more than just constants (e.g. methods, expressions, variables, ...)

If you want to use this to make sure you actually have the name of a constant at hand in a given variable, you need to use const_defined?. If you want to "statically" check whether an constant was defined, you can use defined?.


问:
How can I access my downloads folder using Dockerfile?
I have to following Dockerfile to create a container image. This works fine for some scripts.

```<code>FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt
</code>```

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

答:
You can mount your downloads folder to your Docker service
Assuming you have built your service with image name NAMEOFBUILTDOCKER

docker run -d \
  --name devtest \
  --mount source=pathto/downloads,target=/work \
  NAMEOFYOURBUILTDOCKER
```

Mount is more verbose than —volume but accomplish the same. This will spin up your service in a detached mode(-d), with name devtest where the contents of downloads are in work.

Body:
I have to following Dockerfile to create a container image. This works fine for some scripts.

FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

Body:
You can mount your downloads folder to your Docker service
Assuming you have built your service with image name NAMEOFBUILTDOCKER

docker run -d \
  --name devtest \
  --mount source=pathto/downloads,target=/work \
  NAMEOFYOURBUILTDOCKER

Mount is more verbose than —volume but accomplish the same. This will spin up your service in a detached mode(-d), with name devtest where the contents of downloads are in work.


问:
IOS notification when Application is closed
i have a ios application where to which i send remote notification when sending notification from server i am setting content -available = 1 and sound = ""
When on IOS device i am using

applicaiton(didReceiveRemoteNotification:fetchCompletionHandler:)

I seeing that app reaches this method when in background but when app is closed this method is not getting called But is not getting called when application is closed

applicaiton(didReceiveRemoteNotification:fetchCompletionHandler:)

My handler in this method is

```<code>        let userInfoDic = userInfo as NSDictionary as? [String: Any]
        let cato = userInfoDic?["cato"] as? String
if cato == "message" {
            let state: UIApplicationState = UIApplication.shared.applicationState
            if state == .active{
                print("Application is Active Socket IO will Handle This")
            }else{
                let apnMessage = userInfoDic?["apnMessage"] as? [String: Any]
                if (apnMessage == nil){
                    print("Error Fetching Message")
                }else{
                let count = UserDefaults.standard.integer(forKey:"TotalUnredMessage")

                    DispatchQueue.main.async {
                        UIApplication.shared.applicationIconBadgeNumber = count + 1
                    }
                    UserDefaults.standard.set(count, forKey: "TotalUnredMessage")
          }
}
</code>```

So what should i change for this methods to run even when applicaiton is closed

Thanks

答:
To complete Prakash Shaiva by showing how to retrieve the notification userIn didFinishWithLaunchOptions

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

     if let launchOptions = launchOptions,
            let userInfo =  launchOptions[.remoteNotification] as? [AnyHashable: Any] {
            //some code here and post when needed like below
            NotificationCenter.default.post(name: NSNotification.Name("your notification name"),  object: nil)
        }
}
</code>```

Body:
i have a ios application where to which i send remote notification when sending notification from server i am setting content -available = 1 and sound = ""
When on IOS device i am using

applicaiton(didReceiveRemoteNotification:fetchCompletionHandler:)

I seeing that app reaches this method when in background but when app is closed this method is not getting called But is not getting called when application is closed

applicaiton(didReceiveRemoteNotification:fetchCompletionHandler:)

My handler in this method is

        let userInfoDic = userInfo as NSDictionary as? [String: Any]
        let cato = userInfoDic?["cato"] as? String
if cato == "message" {
            let state: UIApplicationState = UIApplication.shared.applicationState
            if state == .active{
                print("Application is Active Socket IO will Handle This")
            }else{
                let apnMessage = userInfoDic?["apnMessage"] as? [String: Any]
                if (apnMessage == nil){
                    print("Error Fetching Message")
                }else{
                let count = UserDefaults.standard.integer(forKey:"TotalUnredMessage")

                    DispatchQueue.main.async {
                        UIApplication.shared.applicationIconBadgeNumber = count + 1
                    }
                    UserDefaults.standard.set(count, forKey: "TotalUnredMessage")
          }
}

So what should i change for this methods to run even when applicaiton is closed

Thanks

Body:
To complete Prakash Shaiva by showing how to retrieve the notification userIn didFinishWithLaunchOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

     if let launchOptions = launchOptions,
            let userInfo =  launchOptions[.remoteNotification] as? [AnyHashable: Any] {
            //some code here and post when needed like below
            NotificationCenter.default.post(name: NSNotification.Name("your notification name"),  object: nil)
        }
}


问:
data reading from text file and writing
I have text file containing data like

ramesh

3.7

shyam

3.2

hari

3.0

manish

4.0

as name and GPA scores i need to display and write it to another text file in format like

NAME          SCORE

Ramesh           3.7

shyam            3.2

hari             3.0

manish           4.0

and another format like :

NAME  ramesh   shyam   hari   manish

marks  3.7      3.2     3.0     4.0

the code I used to separe is as follos

```<code>infile = open("data.txt", "r")

names = []
marks= []
odd_lines = []
even_lines = []
for odd_line, even_line in zip(infile, infile):
    odd_lines.append(odd_line.rstrip('\n'))
    even_lines.append(even_line.rstrip('\n'))

names = odd_lines
marks = even_lines
</code>```

but i am unable to display and wrtie in required format..anhy help please

答:
The format that you used could be improved with something like:
NAME, MARKS

But if you want a solution for this format, try and use something like:

```<code>with open("data.txt", "r") as file:
  names = file.read().splitlines()[::2]
  marks = file.read().splitlines()[1::2]
  namesNmarks = list(zip(names, marks))
for name, marks in namesNmarks:
  print(f"{name}: {marks}")
</code>```

Title: data reading from text file and writing

Body:
I have text file containing data like

ramesh

3.7

shyam

3.2

hari

3.0

manish

4.0

as name and GPA scores i need to display and write it to another text file in format like

NAME          SCORE

Ramesh           3.7

shyam            3.2

hari             3.0

manish           4.0

and another format like :

NAME  ramesh   shyam   hari   manish

marks  3.7      3.2     3.0     4.0

the code I used to separe is as follos

infile = open("data.txt", "r")

names = []
marks= []
odd_lines = []
even_lines = []
for odd_line, even_line in zip(infile, infile):
    odd_lines.append(odd_line.rstrip('\n'))
    even_lines.append(even_line.rstrip('\n'))

names = odd_lines
marks = even_lines

but i am unable to display and wrtie in required format..anhy help please

Body:
The format that you used could be improved with something like:
NAME, MARKS

But if you want a solution for this format, try and use something like:

with open("data.txt", "r") as file:
  names = file.read().splitlines()[::2]
  marks = file.read().splitlines()[1::2]
  namesNmarks = list(zip(names, marks))
for name, marks in namesNmarks:
  print(f"{name}: {marks}")


问:
How do I run standalone lint from Android SDK Tools on a Gradle Project
When I try to run the lint tool provided in the Android SDK Command Line tools, it fails with the following error

```<code>build.gradle: Error: "." is a Gradle project. To correctly analyze Gradle projects, you should run "gradlew lint" instead. [LintError]
1 errors, 0 warnings
</code>```

My use case requires me to run the standalone lint in a CI environment with specific checks. How do I get around this error?

答:
I searched around for documentation and answers. Documentation doesn't have much information on the topic. I had found one answer before posting this question but the provided suggestions around the error didn't work either. In the end, as Chester said, it didn't even matter.

Since I am running the tool in a CI environment, I ended up doing the following

# delete the build.gradle files from the project
find . -type f -name "build.gradle" -exec rm -f {} \;

# run the lint with whatever checks. It works!!
lint --check Whatever .

# stash everything except the deleted files
git add **/*/build.gradle
git stash -k

# stash the deleted files
git stash

# drop the stash with deleted files
git stash drop

# pop the stash with everything else
git stash pop
```

It's a dirty hack. Always open to better solutions!

Body:
When I try to run the lint tool provided in the Android SDK Command Line tools, it fails with the following error

build.gradle: Error: "." is a Gradle project. To correctly analyze Gradle projects, you should run "gradlew lint" instead. [LintError]
1 errors, 0 warnings

My use case requires me to run the standalone lint in a CI environment with specific checks. How do I get around this error?

Body:
I searched around for documentation and answers. Documentation doesn't have much information on the topic. I had found one answer before posting this question but the provided suggestions around the error didn't work either. In the end, as Chester said, it didn't even matter.

Since I am running the tool in a CI environment, I ended up doing the following

# delete the build.gradle files from the project
find . -type f -name "build.gradle" -exec rm -f {} \;

# run the lint with whatever checks. It works!!
lint --check Whatever .

# stash everything except the deleted files
git add **/*/build.gradle
git stash -k

# stash the deleted files
git stash

# drop the stash with deleted files
git stash drop

# pop the stash with everything else
git stash pop

It's a dirty hack. Always open to better solutions!


问:
How to get the desired character by split or substring method in stringArray JS?
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

```<code>[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]
</code>```

The result I want;

```<code>[<=3123,>=32414,>=12]
</code>```

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.

答:
Use search to find the index of starting positiong and using string length you can slice the string.</p>

```<code>var str = "definitions1<=3123";
var m = str.search("<");
var n = str.slice(m,str.length);
console.log(n);
</code>```

Body:
There is an array and there are strings that are different from each other but contain operations.All of the strings have a large operator and a small operator.I want to separate the characters from the operator and later.

My example Array;

[definitions1<=3123,definitions31241>=32414,definitions123213123>=12]

The result I want;

[<=3123,>=32414,>=12]

When i try with split method like this,

(split(<).pop()) or (split(>).pop())

Result = [=3123,=32414,=12]  i could not get (<,>) operator.

When i tried with subStr, I cannot give standard start and finish parameters because strings are different lengths.

I would be glad if someone shows regular expression method or a simpler way.

Body:
Use search to find the index of starting positiong and using string length you can slice the string.

var str = "definitions1<=3123";
var m = str.search("<");
var n = str.slice(m,str.length);
console.log(n);


问:
How to add one more row and double of selected rows to the protected data using getRange() or getActiveRange() in Google Apps Script?
I manually select A41 to F80 and it is nicely protecting A41 to F80 using the following line of code.

However, I want to (i) add one more row to the protected data (A41 to F81) though I will select A41 to F80.

Also in another case I want to add double of selected rows plus one to the protected data (A41:F121) though I will select A41 to F80.

Probably getActiveRange() won't work, then I tried to use getRange() but can't solve it. Please help me to solve it.

```<code>var protection = SpreadsheetApp.getActiveSheet().getActiveRange().protect().setDescription(description);
</code>```

答:
You need to create a new range

For this, use first the method getHeight() to retrieve the height of activeRange.

Then, add 1 to it.

Create a new range with the method getRange(row, column, numRows, numColumns)

Whereby row, column and numColumns can be taken from activeRange - only the height is new.

Sample:

```<code>var activeRange = SpreadsheetApp.getActiveRange();
var height = activeRange.getHeight();
var newHeight = height + 1;
var activeSheet = SpreadsheetApp.getActiveSheet();
var newRange = activeSheet.getRange(activeRange.getRow(), activeRange.getColumn(), newHeight, activeRange.getWidth());
var protection = newRange.protect().setDescription(description);
</code>```

Body:
I manually select A41 to F80 and it is nicely protecting A41 to F80 using the following line of code.

However, I want to (i) add one more row to the protected data (A41 to F81) though I will select A41 to F80.

Also in another case I want to add double of selected rows plus one to the protected data (A41:F121) though I will select A41 to F80.

Probably getActiveRange() won't work, then I tried to use getRange() but can't solve it. Please help me to solve it.

var protection = SpreadsheetApp.getActiveSheet().getActiveRange().protect().setDescription(description);

Body:
You need to create a new range

For this, use first the method getHeight() to retrieve the height of activeRange.

Then, add 1 to it.

Create a new range with the method getRange(row, column, numRows, numColumns)

Whereby row, column and numColumns can be taken from activeRange - only the height is new.

Sample:

var activeRange = SpreadsheetApp.getActiveRange();
var height = activeRange.getHeight();
var newHeight = height + 1;
var activeSheet = SpreadsheetApp.getActiveSheet();
var newRange = activeSheet.getRange(activeRange.getRow(), activeRange.getColumn(), newHeight, activeRange.getWidth());
var protection = newRange.protect().setDescription(description);


问:
JEST throws .finally is not a function
Here is my react component:

```<code>import { sendAnalytics } from 'analytics';

class MyComponent extends React.Component {
    myMethod() {
        console.log('do something!');
    }

    render() {
        return (
            <Button
                onClick={submitAnalytics({name: 'foo'}).finally(this.myMethod())}
                dataset={{"data-id": "button"}}
            > Send Analytics
            </Button>
            }
        )
    }
}
</code>```

And my test is like so:

```<code>import * as analytics from 'analytics';
jest.mock('analytics');

describe('Analytics', () => {
    it('Should call analytics when button is clicked', () => {
        analytics.submitAnalytics.mockResolvedValue(Promise.resolve(true));
        const tree = ReactTestRenderer.create(<MyComponent />);

        // Actual implementation of following 3 lines is slightly different.
        const button = tree.root.findByProps({"data-id": "button"});
        button.props.onClick();
        expect(analytics.submitAnalytics).toHaveBeenCalled();
    });
});
</code>```

I tried several different mocking strategies like:

```<code>analytics.submitAnalytics.mockImplementation(() => {
    return Promise.resolve(true)
});
</code>```

Nothing seems to work out. I keep getting the following error:

TypeError: (0 , analytics.submitAnalytics)(...).finally is not a function.

I don't know why. Any help appreciated.
Please let me know if you need any more contextual code.

答:
I faced same challenge.
Reason-  Jest runs in Node enviroment,and "Finally" is supported from Node version- 10.0.0. But my Jenkins versions was 8.x so As a quick fix you can remove finally from code. Later we can upgrade local and remote server version.

Below is MDN link-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

Title: JEST throws .finally is not a function

Body:
Here is my react component:

import { sendAnalytics } from 'analytics';

class MyComponent extends React.Component {
    myMethod() {
        console.log('do something!');
    }

    render() {
        return (
            <Button
                onClick={submitAnalytics({name: 'foo'}).finally(this.myMethod())}
                dataset={{"data-id": "button"}}
            > Send Analytics
            </Button>
            }
        )
    }
}

And my test is like so:

import * as analytics from 'analytics';
jest.mock('analytics');

describe('Analytics', () => {
    it('Should call analytics when button is clicked', () => {
        analytics.submitAnalytics.mockResolvedValue(Promise.resolve(true));
        const tree = ReactTestRenderer.create(<MyComponent />);

        // Actual implementation of following 3 lines is slightly different.
        const button = tree.root.findByProps({"data-id": "button"});
        button.props.onClick();
        expect(analytics.submitAnalytics).toHaveBeenCalled();
    });
});

I tried several different mocking strategies like:

analytics.submitAnalytics.mockImplementation(() => {
    return Promise.resolve(true)
});

Nothing seems to work out. I keep getting the following error:

TypeError: (0 , analytics.submitAnalytics)(...).finally is not a function.

I don't know why. Any help appreciated.
Please let me know if you need any more contextual code.


问:
Shortcut alt+enter is not working in Android Studio
alt +  enterfor importing was work normally maybe until I updated Android Studio,
my version now is2.3.3

as this screenshot, I can't press alt +  enter at all, knowing that I have tested them on other programs and they are working normally

答:
In my case (v4.0.0) there was a plugin (CSV Plugin) blocking the shortcut alt +  enter.

Generally speaking, my suggestion is to try deactivating all the plugins and see if then it works.


问:
How can i use selenium python to get a user's following on Ibstagram
How can I use selnium python to get the list of people followed by a specific person?
I've been able to get to the list so far with:

```<code>    def getUserFollowing(self, username, maxima=None):
        self.browser.get('https://www.instagram.com/' + username)
        urlTEMP=username+'/following/'
        followingListButton = self.browser.find_element_by_xpath('//a[contains(@href,urlTEMP)]')
        followingListButton.click()
        actionChain = webdriver.ActionChains(self.browser)
        following = []
</code>```

I don't know how i can make it load the list to the very end and how i can return it as a list.
Any and all help will be appreciated.
:>

答:
Here is the functions I'm using for a while:

```<code>def get_users(no): #no = number of desired usernames
   n = no
   ac = webdriver.ActionChains(driver)
   ac.key_down(Keys.SPACE).perform() #space button to load more users
   sleep(0.5)
   if len(driver.find_elements_by_class_name('d7ByH')) < int(n):
       sleep(1)
       get_users(n)
   else:
       for item in driver.find_elements_by_class_name('d7ByH'): #class name for usernames
           vt_users.append(item.text) #your list name here
</code>```

This function will expand the list until desired number of usernames are not loaded and then you can get all usernames(or whatever you want) in a list. Before calling this function click on the following button and add this also: driver.find_element_by_class_name('isgrP').click() for two times so that clicking on space scrolls the list successfully.

Hope you got what I want to tell.

Body:
How can I use selnium python to get the list of people followed by a specific person?
I've been able to get to the list so far with:

    def getUserFollowing(self, username, maxima=None):
        self.browser.get('https://www.instagram.com/' + username)
        urlTEMP=username+'/following/'
        followingListButton = self.browser.find_element_by_xpath('//a[contains(@href,urlTEMP)]')
        followingListButton.click()
        actionChain = webdriver.ActionChains(self.browser)
        following = []

I don't know how i can make it load the list to the very end and how i can return it as a list.
Any and all help will be appreciated.
:>

Body:
Here is the functions I'm using for a while:

def get_users(no): #no = number of desired usernames
   n = no
   ac = webdriver.ActionChains(driver)
   ac.key_down(Keys.SPACE).perform() #space button to load more users
   sleep(0.5)
   if len(driver.find_elements_by_class_name('d7ByH')) < int(n):
       sleep(1)
       get_users(n)
   else:
       for item in driver.find_elements_by_class_name('d7ByH'): #class name for usernames
           vt_users.append(item.text) #your list name here

This function will expand the list until desired number of usernames are not loaded and then you can get all usernames(or whatever you want) in a list. Before calling this function click on the following button and add this also: driver.find_element_by_class_name('isgrP').click() for two times so that clicking on space scrolls the list successfully.

Hope you got what I want to tell.


问:
How to loop through relationship tables with SQLAlchemy?
I am learning Flask and I want to create a database which contains 3 tables which are related between them:

Company: info about the company I worked for (made up :) )

Job: info about the role I had in each company

Task: info about the tasks i had in each job i had in each company.

Here is the code:

```<code>from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///work_experience.db'
db = SQLAlchemy(app)

class Company(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False, default=None)
    location   = db.Column(db.String(20), nullable=False, default='N/A')
    jobs = db.relationship('Job', backref='company_')

class Job(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    position = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False)
    company_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    tasks = db.relationship('Task', backref='job_')

class Task(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False)
    job_id = db.Column(db.Integer, db.ForeignKey('job.id'))

db.create_all()
</code>```

My I idea is to have a for loop (which eventualy I will write with Jinja2, but for now python code is fine) in such a way that I can print for each company the job that I had and what task I accomplished.
Of course I could have all the data in just one table but I am trying to learn.

Therefore the output should be something like this:

```<code>for company in Companies:
    for job in Jobs:
        for Task in Tasks:
            print(company, job, task)
</code>```

Can you suggest me a smart and elegant way to achieve my goal? Thanks in advance.

答:
If I understand correct you want a list of all your Companies, Jobs, Tasks. You can get these by querying your database (assuming you have already inserted some tuples):

for c in Company.query.all():
    print(c.name)
    for r in c.roles:
        print('\t',r.position)
        for t in r.tasks:
            print('\t\t',t.description)
```

Body:
I am learning Flask and I want to create a database which contains 3 tables which are related between them:

Company: info about the company I worked for (made up :) )

Job: info about the role I had in each company

Task: info about the tasks i had in each job i had in each company.

Here is the code:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///work_experience.db'
db = SQLAlchemy(app)

class Company(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False, default=None)
    location   = db.Column(db.String(20), nullable=False, default='N/A')
    jobs = db.relationship('Job', backref='company_')

class Job(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    position = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False)
    company_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    tasks = db.relationship('Task', backref='job_')

class Task(db.Model):
    id   = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(100), nullable=False)
    start_date = db.Column(db.DateTime, nullable=False)
    end_date   =  db.Column(db.DateTime, nullable=False)
    job_id = db.Column(db.Integer, db.ForeignKey('job.id'))

db.create_all()

My I idea is to have a for loop (which eventualy I will write with Jinja2, but for now python code is fine) in such a way that I can print for each company the job that I had and what task I accomplished.
Of course I could have all the data in just one table but I am trying to learn.

Therefore the output should be something like this:

for company in Companies:
    for job in Jobs:
        for Task in Tasks:
            print(company, job, task)

Can you suggest me a smart and elegant way to achieve my goal? Thanks in advance.


问:
Laravel Admin dashboard
I'm having a Laravel project with an admin side.
I want the admin to have access to registered users.
I'm having a route called users on the admin dashboard. When that route is clicked I want to display all registered users.

Any help please..

答:
first, make a controller.
example: - UsersController
code: -

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use DB;
class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        $all_users = DB::table('users');
        $all_users = $all_users->get();
        return view('home')->with(['all_users'  => $all_users]);
    }
}

</code>```

The route would be like: -

```<code>Route::get('home', 'UsersController@index');
</code>```

The Home view page would be like: -

```<code>    <table class="table table-info table-hover">
    <thead>
      <tr class="table-primary">
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Username</th>
        <th>Status</th>
        <th>User Created At</th>
      </tr>
    </thead>
    <tbody>
      @foreach ($all_users as $users)
            <tr>

            <td>{{ $id_loop++ }}</td>
          <td>{{ $users->name }}</td>
          <td>{{ $users->email }}</td>
          <td>{{ $users->username }}</td>
          <td>
           @if(Cache::has('user-is-online-' . $users->id))
             <span class="text-success"><b>Online</b></span>
           @else
             <span class="text-secondary"><b>Offline</b></span>
           @endif
          </td>
          <td>{{ $users->created_at }}</td>
         </tr>
        @endforeach
    </tbody>
  </table>
</code>```

Title: Laravel Admin dashboard

Body:
first, make a controller.
example: - UsersController
code: -

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use DB;
class UsersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        $all_users = DB::table('users');
        $all_users = $all_users->get();
        return view('home')->with(['all_users'  => $all_users]);
    }
}

The route would be like: -

Route::get('home', 'UsersController@index');

The Home view page would be like: -

    <table class="table table-info table-hover">
    <thead>
      <tr class="table-primary">
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Username</th>
        <th>Status</th>
        <th>User Created At</th>
      </tr>
    </thead>
    <tbody>
      @foreach ($all_users as $users)
            <tr>

            <td>{{ $id_loop++ }}</td>
          <td>{{ $users->name }}</td>
          <td>{{ $users->email }}</td>
          <td>{{ $users->username }}</td>
          <td>
           @if(Cache::has('user-is-online-' . $users->id))
             <span class="text-success"><b>Online</b></span>
           @else
             <span class="text-secondary"><b>Offline</b></span>
           @endif
          </td>
          <td>{{ $users->created_at }}</td>
         </tr>
        @endforeach
    </tbody>
  </table>


问:
Connecting to database without running server in Apache Xindice
I am new to "Apache Xindice". I tried some examples from the internet and it
worked, but I have to run the server before running my applications.This allows it to connect to the database.

I don't want to run the server because my application runs locally
and I don't want to disturb the user with the server. I need to
connect to the database from my application only, the path of the
database is relative to the program.

thanks.

答:
Hm, Apache Xindice seems to be out of date. The latest news entry was 2007.

There are some currently maintained embeddable XML databases like Berkeley DB XML, eXist and Qizx XML database engine. All of them also supports XQuery as the query language.


问:
Serilog.Sinks.File support on windows 8.1 (WinRT)
I have developed an Windows8.1 store app for which I need to log info to a local file.

I could install Serilog nuget to my app but could not install the Serilog.Sinks.File (or .Console).

Could someone help me installing serilog on my app so that i could write to a file.

Thanks,
Atin..

答:
All the steps you need to add Serilog to your app is in the Getting Started guide in Serilog's wiki.

Because you're using UWP, you have restrictions on where you can write in the filesystem, and typically you'd write the log to the app's local folder which you can get via ApplicationData.Current.LocalFolder.Path

e.g.

```<code>public App()
{
    InitializeComponent();
    Suspending += OnSuspending;

    var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "App.log");

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.File(logFilePath)
        .CreateLogger();

    Log.Information("Hello UWP!");
}
</code>```

Body:
All the steps you need to add Serilog to your app is in the Getting Started guide in Serilog's wiki.

Because you're using UWP, you have restrictions on where you can write in the filesystem, and typically you'd write the log to the app's local folder which you can get via ApplicationData.Current.LocalFolder.Path

e.g.

public App()
{
    InitializeComponent();
    Suspending += OnSuspending;

    var logFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "App.log");

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.File(logFilePath)
        .CreateLogger();

    Log.Information("Hello UWP!");
}


问:
Discord, is there a way to mass delete all deletable roles?
As I said in the title, I want to try deleting all deletable roles, only deletable ones
I tried making a code it looks like this

```<code>message.guild.roles.cache.forEach(role => role.deletable && role.delete())
</code>```

Unfortunately, it does not print any errors, and it doesn't work

答:
message.guild.roles.cache.each(role => {
  if (role.editable && role.name !== "@everyone") {
     // you can do .catch(err => undefined) too
     role.delete().catch(err => console.log(role.name));
  }
});
```

Body:
As I said in the title, I want to try deleting all deletable roles, only deletable ones
I tried making a code it looks like this

message.guild.roles.cache.forEach(role => role.deletable && role.delete())

Unfortunately, it does not print any errors, and it doesn't work


答:
Try this:</p>

```<code> import numpy as np

 NEWDATA = np.loadtxt('data.txt', dtype=str)
 np.savetxt('data_reshaped.txt', NEWDATA.reshape(-1, 2), fmt='%s')
</code>```

Title: data reading from text file and writing

Body:
Try this:

 import numpy as np

 NEWDATA = np.loadtxt('data.txt', dtype=str)
 np.savetxt('data_reshaped.txt', NEWDATA.reshape(-1, 2), fmt='%s')


问:
Finding closest number index from a vector
If there is a reference vector, for example:

```<code>ref = np.array([1., 3., 5.])
</code>```

And a random vector:

```<code>r = np.array([3.1, 4.7, 0.1, 5.5])
</code>```

Is there a fast way to find the index of the closes number in 'ref' for each number in 'r'?

Expected result is:

```<code>[2, 3, 1, 3]
</code>```

3.1 is closest to 3 so the answer is index 2.

4.7 is closest to 5 so the answer is index 3.

0.1 is closest to 1 so the answer is index 1.

5.5 is closest to 5 so the answer is index 3.

答:
You can do a broadcasting:

```<code>np.abs(r[:,None]-ref).argmin(-1)
</code>```

Output (remember python is 0-indexed):

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

Body:
If there is a reference vector, for example:

ref = np.array([1., 3., 5.])

And a random vector:

r = np.array([3.1, 4.7, 0.1, 5.5])

Is there a fast way to find the index of the closes number in 'ref' for each number in 'r'?

Expected result is:

[2, 3, 1, 3]

3.1 is closest to 3 so the answer is index 2.

4.7 is closest to 5 so the answer is index 3.

0.1 is closest to 1 so the answer is index 1.

5.5 is closest to 5 so the answer is index 3.

Body:
You can do a broadcasting:

np.abs(r[:,None]-ref).argmin(-1)

Output (remember python is 0-indexed):

array([1, 2, 0, 2])


问:
what does [undefined reference to `SetLastError@4'] mean?
I use mingw-w64 to deploy C++ on windows, everything is normal except when I use the library function, the following problems will be reported at runtime

```<code>d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(mbrscan.o):(.text+0xb6): undefined reference to `SetLastError@4'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(wcharmap.o):(.text+0x208): undefined reference to `WideCharToMultiByte@32'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0xbe): undefined reference to `GetCPInfo@8'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0x143): undefined reference to `GetCPInfo@8'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_key_create':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:590: undefined reference to `TlsAlloc@0'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: /home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:597: undefined reference to `__mingwthr_key_dtor'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_getspecific':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:621: undefined reference to `SetLastError@4'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_setspecific':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:629: undefined reference to `TlsSetValue@8'
collect2.exe: error: ld returned 1 exit status
</code>```

What caused this？Can u help me solve it?

--

A minimal example that reproduces what I believe is the problem:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
  cout << to_string(42) << endl;
  return 0;
}
```

<p>Link with MinGW GCC 9.2.0</p>

```C:\Users\dash\repos\link-error>g++ --version
g++ (MinGW.org GCC Build-20200227-1) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\Users\dash\repos\link-error>g++ main.cpp -o main
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(mbrscan.o):(.text+0xb6): undefined reference to `SetLastError@4'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(wcharmap.o):(.text+0x208): undefined reference to `WideCharToMultiByte@32'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0xbe): undefined reference to `GetCPInfo@8'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0x143): undefined reference to `GetCPInfo@8'
collect2.exe: error: ld returned 1 exit status
```

答:
While you tag your question gcc, the error is actually from ld, which is the linker.

You compile something (which you didn't show the command) and the linker complains for SetLastError@4. My bet is there is a function SetLastError() being used in the code (mbrscan.c?) but you didn't include the relevant object code or library for your linker.

Please check if you missed any library (-l flag in gcc), or any *.o file in your compile command.

Body:
I use mingw-w64 to deploy C++ on windows, everything is normal except when I use the library function, the following problems will be reported at runtime

d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(mbrscan.o):(.text+0xb6): undefined reference to `SetLastError@4'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(wcharmap.o):(.text+0x208): undefined reference to `WideCharToMultiByte@32'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0xbe): undefined reference to `GetCPInfo@8'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0x143): undefined reference to `GetCPInfo@8'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_key_create':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:590: undefined reference to `TlsAlloc@0'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: /home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:597: undefined reference to `__mingwthr_key_dtor'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_getspecific':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:621: undefined reference to `SetLastError@4'
d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: d:/mingw-w64/bin/../lib/gcc/mingw32/9.2.0/libgcc_eh.a(emutls.o): in function `_gthread_setspecific':
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libgcc/./gthr-default.h:629: undefined reference to `TlsSetValue@8'
collect2.exe: error: ld returned 1 exit status

What caused this？Can u help me solve it?

--

A minimal example that reproduces what I believe is the problem:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
  cout << to_string(42) << endl;
  return 0;
}

Link with MinGW GCC 9.2.0

C:\Users\dash\repos\link-error>g++ --version
g++ (MinGW.org GCC Build-20200227-1) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\Users\dash\repos\link-error>g++ main.cpp -o main
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(mbrscan.o):(.text+0xb6): undefined reference to `SetLastError@4'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingw32.a(wcharmap.o):(.text+0x208): undefined reference to `WideCharToMultiByte@32'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0xbe): undefined reference to `GetCPInfo@8'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../libmingwex.a(codeset.o):(.text+0x143): undefined reference to `GetCPInfo@8'
collect2.exe: error: ld returned 1 exit status


问:
FailedPreconditionError: Attempting to use uninitialized in Tensorflow
I am working through the TensorFlow tutorial, which uses a "weird" format to upload the data. I would like to use the NumPy or pandas format for the data, so that I can compare it with scikit-learn results.

I get the digit recognition data from Kaggle: https://www.kaggle.com/c/digit-recognizer/data.

Here the code from the TensorFlow tutorial (which works fine):

```<code># Stuff from tensorflow tutorial
import tensorflow as tf

sess = tf.InteractiveSession()

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
</code>```

Here I read the data, strip out the target variables and split the data into testing and training datasets (this all works fine):

```<code># Read dataframe from training data
csvfile='train.csv'
from pandas import DataFrame, read_csv
df = read_csv(csvfile)

# Strip off the target data and make it a separate dataframe.
Target = df.label
del df["label"]

# Split data into training and testing sets
msk = np.random.rand(len(df)) < 0.8
dfTest = df[~msk]
TargetTest = Target[~msk]
df = df[msk]
Target = Target[msk]

# One hot encode the target
OHTarget=pd.get_dummies(Target)
OHTargetTest=pd.get_dummies(TargetTest)
</code>```

Now, when I try to run the training step, I get a FailedPreconditionError:

```<code>for i in range(100):
    batch = np.array(df[i*50:i*50+50].values)
    batch = np.multiply(batch, 1.0 / 255.0)
    Target_batch = np.array(OHTarget[i*50:i*50+50].values)
    Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
    train_step.run(feed_dict={x: batch, y_: Target_batch})
</code>```

Here's the full error:

```<code>---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-82-967faab7d494> in <module>()
      4     Target_batch = np.array(OHTarget[i*50:i*50+50].values)
      5     Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
----> 6     train_step.run(feed_dict={x: batch, y_: Target_batch})

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in run(self, feed_dict, session)
   1265         none, the default session will be used.
   1266     """
-> 1267     _run_using_default_session(self, feed_dict, self.graph, session)
   1268
   1269

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in _run_using_default_session(operation, feed_dict, graph, session)
   2761                        "the operation's graph is different from the session's "
   2762                        "graph.")
-> 2763   session.run(operation, feed_dict)
   2764
   2765

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict)
    343
    344     # Run request and get response.
--> 345     results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
    346
    347     # User may have fetched the same tensor multiple times, but we

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, target_list, fetch_list, feed_dict)
    417         # pylint: disable=protected-access
    418         raise errors._make_specific_exception(node_def, op, e.error_message,
--> 419                                               e.code)
    420         # pylint: enable=protected-access
    421       raise e_type, e_value, e_traceback

FailedPreconditionError: Attempting to use uninitialized value Variable_1
     [[Node: gradients/add_grad/Shape_1 = Shape[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_1)]]
Caused by op u'gradients/add_grad/Shape_1', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    ...........

...which was originally created as op u'add', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
[elided 17 identical lines from previous traceback]
  File "/Users/user32/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3066, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-45-59183d86e462>", line 1, in <module>
    y = tf.nn.softmax(tf.matmul(x,W) + b)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 403, in binary_op_wrapper
    return func(x, y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 44, in add
    return _op_def_lib.apply_op("Add", x=x, y=y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback = _extract_stack()
</code>```

Any ideas as to how I can fix this?

答:
With tensorflow version >3.2 you may use this command:

```<code>x1 = tf.Variable(5)
y1 = tf.Variable(3)

z1 = x1 + y1

init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    init.run()
    print(sess.run(z1))
</code>```

The output: 8
will be displayed.

Body:
I am working through the TensorFlow tutorial, which uses a "weird" format to upload the data. I would like to use the NumPy or pandas format for the data, so that I can compare it with scikit-learn results.

I get the digit recognition data from Kaggle: https://www.kaggle.com/c/digit-recognizer/data.

Here the code from the TensorFlow tutorial (which works fine):

# Stuff from tensorflow tutorial
import tensorflow as tf

sess = tf.InteractiveSession()

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

Here I read the data, strip out the target variables and split the data into testing and training datasets (this all works fine):

# Read dataframe from training data
csvfile='train.csv'
from pandas import DataFrame, read_csv
df = read_csv(csvfile)

# Strip off the target data and make it a separate dataframe.
Target = df.label
del df["label"]

# Split data into training and testing sets
msk = np.random.rand(len(df)) < 0.8
dfTest = df[~msk]
TargetTest = Target[~msk]
df = df[msk]
Target = Target[msk]

# One hot encode the target
OHTarget=pd.get_dummies(Target)
OHTargetTest=pd.get_dummies(TargetTest)

Now, when I try to run the training step, I get a FailedPreconditionError:

for i in range(100):
    batch = np.array(df[i*50:i*50+50].values)
    batch = np.multiply(batch, 1.0 / 255.0)
    Target_batch = np.array(OHTarget[i*50:i*50+50].values)
    Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
    train_step.run(feed_dict={x: batch, y_: Target_batch})

Here's the full error:

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-82-967faab7d494> in <module>()
      4     Target_batch = np.array(OHTarget[i*50:i*50+50].values)
      5     Target_batch = np.multiply(Target_batch, 1.0 / 255.0)
----> 6     train_step.run(feed_dict={x: batch, y_: Target_batch})

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in run(self, feed_dict, session)
   1265         none, the default session will be used.
   1266     """
-> 1267     _run_using_default_session(self, feed_dict, self.graph, session)
   1268
   1269

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in _run_using_default_session(operation, feed_dict, graph, session)
   2761                        "the operation's graph is different from the session's "
   2762                        "graph.")
-> 2763   session.run(operation, feed_dict)
   2764
   2765

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict)
    343
    344     # Run request and get response.
--> 345     results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
    346
    347     # User may have fetched the same tensor multiple times, but we

/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, target_list, fetch_list, feed_dict)
    417         # pylint: disable=protected-access
    418         raise errors._make_specific_exception(node_def, op, e.error_message,
--> 419                                               e.code)
    420         # pylint: enable=protected-access
    421       raise e_type, e_value, e_traceback

FailedPreconditionError: Attempting to use uninitialized value Variable_1
     [[Node: gradients/add_grad/Shape_1 = Shape[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_1)]]
Caused by op u'gradients/add_grad/Shape_1', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    ...........

...which was originally created as op u'add', defined at:
  File "/Users/user32/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
[elided 17 identical lines from previous traceback]
  File "/Users/user32/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3066, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-45-59183d86e462>", line 1, in <module>
    y = tf.nn.softmax(tf.matmul(x,W) + b)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 403, in binary_op_wrapper
    return func(x, y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 44, in add
    return _op_def_lib.apply_op("Add", x=x, y=y, name=name)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/user32/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback = _extract_stack()

Any ideas as to how I can fix this?

Body:
With tensorflow version >3.2 you may use this command:

x1 = tf.Variable(5)
y1 = tf.Variable(3)

z1 = x1 + y1

init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    init.run()
    print(sess.run(z1))

The output: 8
will be displayed.


问:
Image Conversion when manipulating the filebytes
I have a problem. When images are saved in my database they are saved with the filebytes and there is a reference ID to this record. There is a .ashx file that will take this reference ID number and get the file info/file bytes and display the image or allow for the downloading of the image.

```<code>img src="/download.ashx?id=THEREFID
</code>```

This above would display the image in on the page. If I just put a link to the .ashx page it would download the image. This is fine. However some of my images are saved as .TIF and I need to convert them to .jpeg.

I have a class called FileData

```<code>public string FileName;
public byte[] theData;
public long FileSizeBytes;
public string MIME;
public string Extension;
</code>```

On my .ashx page I have a method that loads the above FileData class. Then the FileData class along with the HttpContext class gets sent to a method:

```<code>private void Process(HttpContext context, FileData file)
{
    context.Response.ContentTYpe = file.MIME;
    context.Response.AddHeader("Content-Disposition", "attachment; filename="
        + file.FileName.Replace(' ', '_')
        + file.FileExtension);
    context.Response.AddHeader("Content-Length", file.FileSizeBytes.ToString());
    context.Response.Expires = 0;
    context.Response.BinaryWrite(file.Data);
    context.ApplicationInstance.CompleteRequest();
}
</code>```

I need to find a way to convert this info to a jpeg. I am thinking maybe a temporary bitmap, convert it to .jpeg, then get the file bytes from this?

答:
i would do it as you intended...

more or less like that:

```<code>                System.Drawing.Bitmap tiffImage;
                using(BinaryWriter  baseWriter = new BinaryWriter(new MemoryStream()))
                {
                    baseWriter.Write(tiffData);
                    baseWriter.BaseStream.Position = 0;
                    tiffImage = new System.Drawing.Bitmap(baseWriter.BaseStream);
                }

                MemoryStream jpgStream = new MemoryStream();

                tiffImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                jpgStream.Position = 0;
                using (BinaryReader br = new BinaryReader(jpgStream))
                {
                    context.Response.BinaryWrite(br.ReadBytes(jpgStream.Length));
                }
</code>```

Body:
I have a problem. When images are saved in my database they are saved with the filebytes and there is a reference ID to this record. There is a .ashx file that will take this reference ID number and get the file info/file bytes and display the image or allow for the downloading of the image.

img src="/download.ashx?id=THEREFID

This above would display the image in on the page. If I just put a link to the .ashx page it would download the image. This is fine. However some of my images are saved as .TIF and I need to convert them to .jpeg.

I have a class called FileData

public string FileName;
public byte[] theData;
public long FileSizeBytes;
public string MIME;
public string Extension;

On my .ashx page I have a method that loads the above FileData class. Then the FileData class along with the HttpContext class gets sent to a method:

private void Process(HttpContext context, FileData file)
{
    context.Response.ContentTYpe = file.MIME;
    context.Response.AddHeader("Content-Disposition", "attachment; filename="
        + file.FileName.Replace(' ', '_')
        + file.FileExtension);
    context.Response.AddHeader("Content-Length", file.FileSizeBytes.ToString());
    context.Response.Expires = 0;
    context.Response.BinaryWrite(file.Data);
    context.ApplicationInstance.CompleteRequest();
}

I need to find a way to convert this info to a jpeg. I am thinking maybe a temporary bitmap, convert it to .jpeg, then get the file bytes from this?

Body:
i would do it as you intended...

more or less like that:

                System.Drawing.Bitmap tiffImage;
                using(BinaryWriter  baseWriter = new BinaryWriter(new MemoryStream()))
                {
                    baseWriter.Write(tiffData);
                    baseWriter.BaseStream.Position = 0;
                    tiffImage = new System.Drawing.Bitmap(baseWriter.BaseStream);
                }

                MemoryStream jpgStream = new MemoryStream();

                tiffImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                jpgStream.Position = 0;
                using (BinaryReader br = new BinaryReader(jpgStream))
                {
                    context.Response.BinaryWrite(br.ReadBytes(jpgStream.Length));
                }


问:
GraphQL query does not update on react router v4 history push
I would like to implement a basic filtering option in my React web app. I have three components

```<code>VideoList
--------------------------

Filter    Result
--------  ----------------
category
</code>```

the Filter component and the Result component are both children of the VideoList component. In the filter component when a user clicks on the category, I am pushing a new url, like this this.props.history.push(/videos/${category.name}). It seems like my react-router settings works correctly and the VideoList component gets new category name and successfully passes it to the Result component.

```<code><Route exact path="/videos" component={VideoList}/>,
<Route exact path="/videos/:category" render={props => <VideoList {...props} />} />,
</code>```

In VideoLIst component

<Result category={category} />

The Result component makes usage of a new category name in its own GraphQL query as follow:

```<code>export default compose(
  graphql(VIDEOS_QUERY, {
    options: props => {
      return {
        variables: {
          filterByCategory: props.category ? props.category : null,
        }
      };
    },
...
</code>```

But, by some unknown to me reasons when pushing new url for the first time props.data.VideoQuery (this is return values from graphql server) in the Result component gets undefined. However, when a user clicks on the category second time, the Result components renders correctly.

答:
Update your integration part of the apollo client with the below code.</p>

```<code>const client = new ApolloClient({
  cache,
  link: newLink,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: "network-only",
    },
    query: {
      fetchPolicy: "network-only",
    },
  },
});
</code>```

Body:
I would like to implement a basic filtering option in my React web app. I have three components

VideoList
--------------------------

Filter    Result
--------  ----------------
category

the Filter component and the Result component are both children of the VideoList component. In the filter component when a user clicks on the category, I am pushing a new url, like this this.props.history.push(/videos/${category.name}). It seems like my react-router settings works correctly and the VideoList component gets new category name and successfully passes it to the Result component.

<Route exact path="/videos" component={VideoList}/>,
<Route exact path="/videos/:category" render={props => <VideoList {...props} />} />,

In VideoLIst component

<Result category={category} />

The Result component makes usage of a new category name in its own GraphQL query as follow:

export default compose(
  graphql(VIDEOS_QUERY, {
    options: props => {
      return {
        variables: {
          filterByCategory: props.category ? props.category : null,
        }
      };
    },
...

But, by some unknown to me reasons when pushing new url for the first time props.data.VideoQuery (this is return values from graphql server) in the Result component gets undefined. However, when a user clicks on the category second time, the Result components renders correctly.

Body:
Update your integration part of the apollo client with the below code.

const client = new ApolloClient({
  cache,
  link: newLink,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: "network-only",
    },
    query: {
      fetchPolicy: "network-only",
    },
  },
});


问:
Collection initializers inside object initializers with default values
I just stumbled upon the following issue:

```<code>class Settings
{
    // Let's set some default value: { 1 }
    public ICollection<int> AllowedIds = new List<int>() { 1 };
}

static void Main(string[] args)
{
    var s = new Settings
    {
        AllowedIds = { 1, 2 }
    };

    Console.WriteLine(string.Join(", ", s.AllowedIds)); // prints 1, 1, 2
}
</code>```

I understand why this happens: AllowedIds = { 1, 2 } is not an assignment but a collection initializer inside an object initializer, i.e., it's an implicit call of AllowedIds.Add(1); AllowedIds.Add(2).

Still, for me it was a gotcha, since it looks like an assignment (since it uses =).

As an API/library developer (let's say I'm the one developing the Settings class) who wants to adhere to the principle of least surprise, is there anything I can do to prevent the consumers of my library from falling into that trap?

Footnotes:

In that particular case, I could use an ISet/HashSet<int> instead of ICollection/List (since duplicates do not make sense for AllowedIds), which would yield the expected result of 1, 2. Still, initializing AllowedIds = { 2 } would yield the counter-intuitive result of 1, 2.

I found a related discussion on the C# github repo, which basically concluded that, yes, this syntax is confusing, but it's an old feature (introduced in 2006), and we can't change it without breaking backwards compatibility.

答:
If you are not expecting the user of the Settings class to add to AllowedIds, why expose it as an ICollection<int> (which contains an Add method and signifies the intention to be added into)?

The reason why AllowedIds = { 1, 2 } works in your code is because C# uses duck typing to call the Add method on the collection. If you eliminate the possibility of the compiler finding an Add method, there will be a compile error on the line AllowedIds = { 1, 2 }, thus preventing the trap.

You can do something like:

class Settings
{
    // Let's set some default value: { 1 }
    public IEnumerable<int> AllowedIds { get; set; } = new List<int> { 1 };
}

static void Main(string[] args)
{
    var s = new Settings
    {
        AllowedIds = new List<int> { 1, 2 }
    };

    Console.WriteLine(string.Join(", ", s.AllowedIds)); // prints 1, 2
}
```

This way you are still allowing the caller to set a new collection using the setter, while preventing the trap you mentioned.

Body:
I just stumbled upon the following issue:

class Settings
{
    // Let's set some default value: { 1 }
    public ICollection<int> AllowedIds = new List<int>() { 1 };
}

static void Main(string[] args)
{
    var s = new Settings
    {
        AllowedIds = { 1, 2 }
    };

    Console.WriteLine(string.Join(", ", s.AllowedIds)); // prints 1, 1, 2
}

I understand why this happens: AllowedIds = { 1, 2 } is not an assignment but a collection initializer inside an object initializer, i.e., it's an implicit call of AllowedIds.Add(1); AllowedIds.Add(2).

Still, for me it was a gotcha, since it looks like an assignment (since it uses =).

As an API/library developer (let's say I'm the one developing the Settings class) who wants to adhere to the principle of least surprise, is there anything I can do to prevent the consumers of my library from falling into that trap?

Footnotes:

In that particular case, I could use an ISet/HashSet<int> instead of ICollection/List (since duplicates do not make sense for AllowedIds), which would yield the expected result of 1, 2. Still, initializing AllowedIds = { 2 } would yield the counter-intuitive result of 1, 2.

I found a related discussion on the C# github repo, which basically concluded that, yes, this syntax is confusing, but it's an old feature (introduced in 2006), and we can't change it without breaking backwards compatibility.

Body:
If you are not expecting the user of the Settings class to add to AllowedIds, why expose it as an ICollection<int> (which contains an Add method and signifies the intention to be added into)?

The reason why AllowedIds = { 1, 2 } works in your code is because C# uses duck typing to call the Add method on the collection. If you eliminate the possibility of the compiler finding an Add method, there will be a compile error on the line AllowedIds = { 1, 2 }, thus preventing the trap.

You can do something like:

class Settings
{
    // Let's set some default value: { 1 }
    public IEnumerable<int> AllowedIds { get; set; } = new List<int> { 1 };
}

static void Main(string[] args)
{
    var s = new Settings
    {
        AllowedIds = new List<int> { 1, 2 }
    };

    Console.WriteLine(string.Join(", ", s.AllowedIds)); // prints 1, 2
}

This way you are still allowing the caller to set a new collection using the setter, while preventing the trap you mentioned.


问:
How to make a partially un-editable table cell?
This might be kind of a weird question, but is it possible to build table cells that are partially editable, but also partially un-editable? By this I mean, I want to use JavaScript to make a majority of the cell editable by setting .contentEditable = true in JavaScript (already done). However, I also want a portion (preferably on the right side) to be text that cannot be written over or edited.

What I'm trying to do here is make most of the table cell editable to put in raw data, i.e. numbers. But to leave an stagnate section with a unit, so that the unit doesn't actually get taken as input (it's more just like decoration).

I've drawn a mock-up of what I'm imagining, if this helps:

So far, I've tried adding a <input> element after the initial input following , then style the input to set point-events: none. But this does not look good and ends up creating an input form inside of a content editable cell, which isn't really what I want, and ends up looking like this:

I think it would have to use some CSS overlay and not actually be apart of the table HTML. Either way, how would I go about this?

答:
You could just use two span elements, make one of them contenteditable. Example:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
}

.input {
  display: flex;
  justify-content: space-between
}

span {
  padding: 0.5em;
}

.value {
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Heading 1</th>
      <th>Heading 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">10</span><span class="unit">kg</span></td>
    </tr>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">20</span><span class="unit">kg</span></td>
    </tr>
  </tbody>
</table></code>```

Alternatively, you could use the after pseudo-selector to add the unit. Example:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
}

.value::after {
  content: " kg";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>
      <th>Heading 1</th>
      <th>Heading 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">10</span></td>
    </tr>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">20</span></td>
    </tr>
  </tbody>
</table></code>```

Body:
You could just use two span elements, make one of them contenteditable. Example:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
}

.input {
  display: flex;
  justify-content: space-between
}

span {
  padding: 0.5em;
}

.value {
  flex-grow: 1;
}

<table>
  <thead>
    <tr>
      <th>Heading 1</th>
      <th>Heading 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">10</span><span class="unit">kg</span></td>
    </tr>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">20</span><span class="unit">kg</span></td>
    </tr>
  </tbody>
</table>

Alternatively, you could use the after pseudo-selector to add the unit. Example:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
}

.value::after {
  content: " kg";
}

<table>
  <thead>
    <tr>
      <th>Heading 1</th>
      <th>Heading 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">10</span></td>
    </tr>
    <tr>
      <td>Entry 1</td>
      <td class="input"><span class="value" contenteditable="">20</span></td>
    </tr>
  </tbody>
</table>


问:
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

```<code>            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }
</code>```

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)
```

<p>First three lines of my input file:</p>

```Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360
```

答:
Thanks for your anwsers. Eventually, it turns out that UTF-16 caused the problem.
My input file was originally an excel file, then I saved it as UTF-16 txt, which caused this problem. I tried to save the input file as tab-delimited text file and it worked as expected.

This is a weird cause of the NumberFormatException. Hope it helps others come across the same problem.

Body:
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)

First three lines of my input file:

Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360


问:
Why are there two plus operators in OCaml?
In OCaml operators as < do support int and float.
Why + cannot?

答:
Because the < operator can support any type and not just int and float.

You couldn't do that with + as it wouldn't make sense, say, to add custom-designed types that represent complex data.

On the other hand, having a universal total comparison is extremely useful, as a lot of algorithms and data structure relies on it existing.


问:
Syntax error when merging pattern matching cases
I coded the following function to compute the cartesian product of two lists.

let rec descartes a = function
| _ when a = [] -> []
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
```

<p>But when I want to simplify the function</p>

<pre class="lang-ml prettyprint-override"><code>let rec descartes a = function
| _ when a = [] | [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
</code>```

I get a syntax error.

答:
According to this the syntax of pattern matching is:

```<code>pattern-matching ::=  [ | ] pattern  [when expr] ->  expr  { | pattern  [when
                          expr] ->  expr }
</code>```

And you can find the syntax of pattern here. So as you can see when is not a part of pattern, which explains the syntax error.

But in any case, your code is redundant, once you have [] -> [] you don't need _ when a = [] -> [] anymore. So you can simply write:

```<code>let rec descartes a = function
    | [] -> []
    | t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
</code>```

Body:
I coded the following function to compute the cartesian product of two lists.

let rec descartes a = function
| _ when a = [] -> []
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;

But when I want to simplify the function

let rec descartes a = function
| _ when a = [] | [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;

I get a syntax error.

Body:
According to this the syntax of pattern matching is:

pattern-matching ::=  [ | ] pattern  [when expr] ->  expr  { | pattern  [when
                          expr] ->  expr }

And you can find the syntax of pattern here. So as you can see when is not a part of pattern, which explains the syntax error.

But in any case, your code is redundant, once you have [] -> [] you don't need _ when a = [] -> [] anymore. So you can simply write:

let rec descartes a = function
    | [] -> []
    | t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;


问:
Update interests values in postgresql by days
I need some help here, at least a hint, in how to write this query that works in Firebird to PostgreSQL. It's about interests auto-update per day. Always worked that way, but now we are migrating and I can't find the solution although I tried many different ways.</p>

```<code>execute block as
declare variable id Integer;
begin
for select BILL_ID from BILLS into :id do update BILLS set BILL_INTEREST_VALUE =
TRUNC(replace(((((BILL_VALUE * BILL_PERCENT) / 100) / 30) * datediff(day, BILL_INTEREST_DATE, current_date)),',','.'), 2)where BILL_ID = :id and BILL_CLIENT_ID="+id+"
and datediff(day, BILL_INTEREST_DATE, current_date) >=  BILL_DAYS_INTEREST and
BILL_VALUE > 0.00;
end;
</code>```

答:
I don't understand why that used a procedural language, as far as I can tell, this can be replaced with a single UPDATE statement without a loop:

```<code>UPDATE BILLS
  SET bill_interest_value = trunc( (((BILL_VALUE * BILL_PERCENT) / 100) / 30) * (current_date - bill_interest_date))
WHERE bill_id IN (SELECT bill_id FROM bills) --<< essentially useless
  AND bill_client_id = ?
  AND current_date - bill_interest_date >=  bill_days_interest
  AND bill_value > 0.00;
</code>```

The above assumes that bill_interest_date is a date column (not a timestamp)

Body:
I need some help here, at least a hint, in how to write this query that works in Firebird to PostgreSQL. It's about interests auto-update per day. Always worked that way, but now we are migrating and I can't find the solution although I tried many different ways.

execute block as
declare variable id Integer;
begin
for select BILL_ID from BILLS into :id do update BILLS set BILL_INTEREST_VALUE =
TRUNC(replace(((((BILL_VALUE * BILL_PERCENT) / 100) / 30) * datediff(day, BILL_INTEREST_DATE, current_date)),',','.'), 2)where BILL_ID = :id and BILL_CLIENT_ID="+id+"
and datediff(day, BILL_INTEREST_DATE, current_date) >=  BILL_DAYS_INTEREST and
BILL_VALUE > 0.00;
end;

Body:
I don't understand why that used a procedural language, as far as I can tell, this can be replaced with a single UPDATE statement without a loop:

UPDATE BILLS
  SET bill_interest_value = trunc( (((BILL_VALUE * BILL_PERCENT) / 100) / 30) * (current_date - bill_interest_date))
WHERE bill_id IN (SELECT bill_id FROM bills) --<< essentially useless
  AND bill_client_id = ?
  AND current_date - bill_interest_date >=  bill_days_interest
  AND bill_value > 0.00;

The above assumes that bill_interest_date is a date column (not a timestamp)


问:
Installing PCL python on Windows using PIP
How to install Point cloud library on python on Windows?

I am working on Anaconda which is python distribution.

So what is the way to install PCL using pip?

If you know any other method please let me know.

答:
if you have some problems with installing PCL on windows you can always use docker on windows, which is very helpful, and in particular my image based on PCL and jupyter:

```<code>docker pull vadikalp/jupyter-pcl

docker run -p 8888:8888 vadikalp/jypyter-pcl

</code>```

Go to server, create new ipython and  import pcl!

Body:
if you have some problems with installing PCL on windows you can always use docker on windows, which is very helpful, and in particular my image based on PCL and jupyter:

docker pull vadikalp/jupyter-pcl

docker run -p 8888:8888 vadikalp/jypyter-pcl

Go to server, create new ipython and  import pcl!


问:
Why is Lombok in a Scala case class inaccessible in a Java class when using Mixed project?
I have a simple Spring boot app with a Scala class...

```<code>case class TestThing(val name: String ){
  @Getter
  @Setter
  var value = null
  def getMap = {
    val list: List[Item] = List(Item("1", "Foo"), Item("2", "Bar"))
    val map = list.map(item => item.key -> item).toMap
    map("1")
  }
}
</code>```

Now I am trying to access the getter and setter function from a java class like this...

```<code>@GetMapping("/other")
public String index(){
    TestThing thing = new TestThing("My Name");
    thing.setValue("Test");
    return "Hello World from me "+thing.getMap().value()+"||"+thing.getValue();
}
</code>```

The thing.getMap() works fine but I get the following compile error for the getters and setters...

```<code>  error: cannot find symbol
        return "Hello World from me "+thing.getMap().value()+"||"+thing.getValue();
                                                                       ^
  symbol:   method getValue()
  location: variable thing of type TestThing
</code>```

What am I missing? I found this question (Error compiling Java/Scala mixed project and Lombok) but it is the reverse and doesn't seem to help.

答:
Lombok doesn't work with Scala. Simple as that. (It is even described why in the issue you linked). The @Getter and @Setter annotations in Scala classes are never processed and the accessors are never generated.

It is also completely unneeded as case classes generate: toString, equals, hashcode getters and setter. If you want to have Java Bean accessors you can use @BeanProperty annotation.

```<code>import scala.beans.BeanProperty

case class TestThing(val name: String ){
  @BeanProperty
  var value: String = null
}
</code>```

```<code>val test = TestThing("test")
test.getValue // null
test.setValue("test")
test.getValue // "test"
</code>```

Body:
I have a simple Spring boot app with a Scala class...

case class TestThing(val name: String ){
  @Getter
  @Setter
  var value = null
  def getMap = {
    val list: List[Item] = List(Item("1", "Foo"), Item("2", "Bar"))
    val map = list.map(item => item.key -> item).toMap
    map("1")
  }
}

Now I am trying to access the getter and setter function from a java class like this...

@GetMapping("/other")
public String index(){
    TestThing thing = new TestThing("My Name");
    thing.setValue("Test");
    return "Hello World from me "+thing.getMap().value()+"||"+thing.getValue();
}

The thing.getMap() works fine but I get the following compile error for the getters and setters...

  error: cannot find symbol
        return "Hello World from me "+thing.getMap().value()+"||"+thing.getValue();
                                                                       ^
  symbol:   method getValue()
  location: variable thing of type TestThing

What am I missing? I found this question (Error compiling Java/Scala mixed project and Lombok) but it is the reverse and doesn't seem to help.

Body:
Lombok doesn't work with Scala. Simple as that. (It is even described why in the issue you linked). The @Getter and @Setter annotations in Scala classes are never processed and the accessors are never generated.

It is also completely unneeded as case classes generate: toString, equals, hashcode getters and setter. If you want to have Java Bean accessors you can use @BeanProperty annotation.

import scala.beans.BeanProperty

case class TestThing(val name: String ){
  @BeanProperty
  var value: String = null
}

val test = TestThing("test")
test.getValue // null
test.setValue("test")
test.getValue // "test"


问:
Gson api parsing issue Kotlin
I'm trying to parse the JSON returned by the following API call (recipe and ingredientLines only):

```<code>https://api.edamam.com/search?q=khachapuri&app_id=xxx&app_key=yyy
</code>```

My model for GSON looks like this:

```<code>class FoodModel {
    var label:String = "Yummy"
    var image:String = "https://agenda.ge/files/khachapuri.jpg"
    var ingredientLines = ""
}
</code>```

After launching the app, I'm facing the following error:

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
</code>```

I think I'm writing the model class incorrectly, because the structure of a json is not clear for me. This is how I'm trying to use Gson: val foodItems = Gson().fromJson(response, Array<FoodModel>::class.java) can anyone help?

答:
The JSON object returned by the API has a slightly different structure compared to your model.

In particular the API is returning a complex object that you need to traverse in order to extract the information you are interest into. A high-level example (I'm not able to test it, but hopefully you'll get the gist of it):

```<code>data class Response(
        val hits: List<Hit>
)

data class Hit(
        val recipe: Recipe
)

data class Recipe(
        val label: String,
        val image: String
)

val foodItems = Gson().fromJson(response, Response::class.java)
</code>```

Just be aware that Gson may create instances in an unsafe manner, which means you may experience NullPointerExceptions thrown apparently with no reason. If you want to prove it, just rename image to anything else (you can also try with other fields, it doesn't matter), and you'll see its value is null even if the type is non-nullable.

Title: Gson api parsing issue Kotlin

Body:
I'm trying to parse the JSON returned by the following API call (recipe and ingredientLines only):

https://api.edamam.com/search?q=khachapuri&app_id=xxx&app_key=yyy

My model for GSON looks like this:

class FoodModel {
    var label:String = "Yummy"
    var image:String = "https://agenda.ge/files/khachapuri.jpg"
    var ingredientLines = ""
}

After launching the app, I'm facing the following error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I think I'm writing the model class incorrectly, because the structure of a json is not clear for me. This is how I'm trying to use Gson: val foodItems = Gson().fromJson(response, Array<FoodModel>::class.java) can anyone help?

Body:
The JSON object returned by the API has a slightly different structure compared to your model.

In particular the API is returning a complex object that you need to traverse in order to extract the information you are interest into. A high-level example (I'm not able to test it, but hopefully you'll get the gist of it):

data class Response(
        val hits: List<Hit>
)

data class Hit(
        val recipe: Recipe
)

data class Recipe(
        val label: String,
        val image: String
)

val foodItems = Gson().fromJson(response, Response::class.java)

Just be aware that Gson may create instances in an unsafe manner, which means you may experience NullPointerExceptions thrown apparently with no reason. If you want to prove it, just rename image to anything else (you can also try with other fields, it doesn't matter), and you'll see its value is null even if the type is non-nullable.


问:
.net web app displays differently after adding search column
Trying to get columns to sort.  In my index.cshtml, I changed this:

```<code>    <th>
        @Html.DisplayNameFor(model => model.Date)
    </th>
</code>```

to this:

```<code>    <th>
        <a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]">@Html.DisplayNameFor(model => model.Date)</a>
    </th>
</code>```

When I run it in Visual Studio it displays fine, centered, etc.  When I deploy to IIS, the fonts are tiny, and everything is left justified.  Before I made the change, it displayed correctly on IIS as well.  I'm assuming it is tucking it into a frame or something.  Is there a better way to add sortable columns?

答: NVM.  It is apparently something else.  </p>

Body:
Trying to get columns to sort.  In my index.cshtml, I changed this:

        @Html.DisplayNameFor(model => model.Date)

to this:

        @Html.DisplayNameFor(model => model.Date)

When I run it in Visual Studio it displays fine, centered, etc.  When I deploy to IIS, the fonts are tiny, and everything is left justified.  Before I made the change, it displayed correctly on IIS as well.  I'm assuming it is tucking it into a frame or something.  Is there a better way to add sortable columns?

Body: NVM.  It is apparently something else.


问:
ClickOnce custom prerequisite problem with installation
I have created custom prerequisite setup project for ClickOnce and it is among the other prerequisites in publish tab of the project. But when i try to install my app via ClickOnce(with setup button) it runs prerequisite setup, and asks if i want to install it. I click "install" and the following error appears:

The following package files could not
  be found:
  C:\Users\..\AppData\Local\Microsoft\Windows\Temporary
  Internet
  Files\Content.IE5\U2R49322\FontPrerequisite\setupfont.msi

When i launch the application-it installs it, but without prerequisite. What can cause the problem?

答:
This is a wild guess, but I would assume that you've specified that the user should download the prerequisite from the vendors site.  Open the Prerequisites dialog and select your prerequisite.  Click on the option that states Download prerequisite from the same location as my application.  (See the screen shot below)

This should bundle your prereq with your application deployment.  Hope that helps.