问:
Rails: NameError: uninitialized constant
I have a simple model called PhoneNumber:

```<code>class PhoneNumber < ActiveRecord::Base
  validates :pnumber, presence: true, on: :create #=> { :message => " cannot be blank" }
  validates :pnumber, numericality: true, on: :create
end
</code>```

I go to the root folder of the application (the one containing the app sub-folder) and start the console:

```<code>rails console --sandbox
</code>```

When I try to create an empty PhoneNumber (I want to get an error message as the validation shall fail) I am getting the following error message:

```<code>2.0.0-p451 :001 > PhoneNumber.new
NameError: uninitialized constant PhoneNumber
from (irb):1
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/console.rb:90:in `start'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/console.rb:9:in `start'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands.rb:17:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:43:in `require'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:43:in `block in exec_app_rails'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:32:in `loop'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:32:in `exec_app_rails'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/cli.rb:5:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/bin/rails:9:in `require'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/bin/rails:9:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/rails:23:in `load'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/rails:23:in `<main>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/ruby_executable_hooks:15:in `eval'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/2.2.2.02.02.02.0.2.2.02.222222.2.02.02.0.2.2.022222222222222
</code>```

It seems the console is not aware of the model. In plain ruby you need to 'require' the file containing the class but I thought that the rails console shall automatically load all models. What is going on here?

答:
I had this problem because I changed the name of the class in a model, and it did not match the name of the file.

"Model class names use CamelCase. These are singular, and will map automatically to the plural database table name.

Model files go in app/models/#{singular_model_name}.rb."

https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e#model

Body:
I have a simple model called PhoneNumber:

class PhoneNumber < ActiveRecord::Base
  validates :pnumber, presence: true, on: :create #=> { :message => " cannot be blank" }
  validates :pnumber, numericality: true, on: :create
end

I go to the root folder of the application (the one containing the app sub-folder) and start the console:

rails console --sandbox

When I try to create an empty PhoneNumber (I want to get an error message as the validation shall fail) I am getting the following error message:

2.0.0-p451 :001 > PhoneNumber.new
NameError: uninitialized constant PhoneNumber
from (irb):1
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/console.rb:90:in `start'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/console.rb:9:in `start'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/commands.rb:17:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:43:in `require'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:43:in `block in exec_app_rails'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:32:in `loop'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/app_rails_loader.rb:32:in `exec_app_rails'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/lib/rails/cli.rb:5:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/bin/rails:9:in `require'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/railties-4.1.5/bin/rails:9:in `<top (required)>'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/rails:23:in `load'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/rails:23:in `'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/ruby_executable_hooks:15:in `eval'
from /Users/nnikolo/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/bin/2.2.2.02.02.02.0.2.2.02.222222.2.02.02.0.2.2.022222222222222

It seems the console is not aware of the model. In plain ruby you need to 'require' the file containing the class but I thought that the rails console shall automatically load all models. What is going on here?


来源: stackexchange

问:
How to count rows between 2 non empty cells with their intermediary empty cells in Google Sheets?
I'm trying to count each rows of empty cells between two non-empy cells and adding the upper non empty-cell count (or the lower non-empty cells count)  to the result when the empty cells/rows numbers are variable and irregular in this manner:

```<code>A1 Empty
A2 Non-empty
A3 Empty
A4 Empty
A5 Empty
A6 Empty
A7 Non-empty
</code>```

(with A2 to A5 being irregular — could be any number of intermediary empty rows/cells — i.e. 10, 2, 30, 5, etc., and variable — could be located in any location within Column A)

The result should return as follow:

```<code>=IFS(

AND(A2="",A3=""),"",

AND(A2="",A3<>""),"",

AND(A2<>"",A3<>""),ROWS(A2),

AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))
</code>```

How do we program Google Sheets to count rows "UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next ono empty row(-1)) when the emppty intermediary rows' count is variable/unknown for each occurence and irregular/can be any number of intremediary rows?

I have this data as example:

So far, I've come up with this partial solution:

```<code>=IFS(AND(A2="",A3=""),"", AND(A2="",A3<>""),"", AND(A2<>"",A3<>""),ROWS(A2), AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))))
</code>```

The expected result should return as follows:

The Sheet copy:
https://docs.google.com/spreadsheets/d/1eLXdFINKVtS5Fxon8mIQDmBUTZokyY_Fb6tfWJRDOVI/edit?usp=sharing

答:
Well I think you can do it a bit more elegantly using a reverse lookup. The idea is to sort the data on descending order of row number, then use a match with -1 as the last parameter, which is equivalent to searching from the end of the data for the next non-blank.

```<code>=ArrayFormula(iferror(if(A2:A="","",rows(A2:A)+2-match(row(A2:A)+1,
query(SORT({IF(A2:A<>"",row(A2:A),""),row(A2:A)},2,false),"select Col1"),-1)-row(A2:A)),1))
</code>```

If you wanted to keep it simple and just use a pull-down formula, an ordinary match is enough:

```<code>=ArrayFormula(iferror(if(A2="","",match(true,A3:A<>"",0)),1))
</code>```

(it still has to be entered as an array formula because A3:A<>"" is an array of True and False)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to count each rows of empty cells between two non-empy cells and adding the upper non empty-cell count (or the lower non-empty cells count)  to the result when the empty cells/rows numbers are variable and irregular in this manner:

A1 Empty
A2 Non-empty
A3 Empty
A4 Empty
A5 Empty
A6 Empty
A7 Non-empty

(with A2 to A5 being irregular — could be any number of intermediary empty rows/cells — i.e. 10, 2, 30, 5, etc., and variable — could be located in any location within Column A)

The result should return as follow:

=IFS(

AND(A2="",A3=""),"",

AND(A2="",A3<>""),"",

AND(A2<>"",A3<>""),ROWS(A2),

AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))

How do we program Google Sheets to count rows "UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next ono empty row(-1)) when the emppty intermediary rows' count is variable/unknown for each occurence and irregular/can be any number of intremediary rows?

I have this data as example:

So far, I've come up with this partial solution:

=IFS(AND(A2="",A3=""),"", AND(A2="",A3<>""),"", AND(A2<>"",A3<>""),ROWS(A2), AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))))

The expected result should return as follows:

The Sheet copy:
https://docs.google.com/spreadsheets/d/1eLXdFINKVtS5Fxon8mIQDmBUTZokyY_Fb6tfWJRDOVI/edit?usp=sharing

Body:
Well I think you can do it a bit more elegantly using a reverse lookup. The idea is to sort the data on descending order of row number, then use a match with -1 as the last parameter, which is equivalent to searching from the end of the data for the next non-blank.

=ArrayFormula(iferror(if(A2:A="","",rows(A2:A)+2-match(row(A2:A)+1,
query(SORT({IF(A2:A<>"",row(A2:A),""),row(A2:A)},2,false),"select Col1"),-1)-row(A2:A)),1))

If you wanted to keep it simple and just use a pull-down formula, an ordinary match is enough:

=ArrayFormula(iferror(if(A2="","",match(true,A3:A<>"",0)),1))

(it still has to be entered as an array formula because A3:A<>"" is an array of True and False)


问:
Operator overload for compound dereference and assignment
With C++ operator overloads, it is possible to create a class which emulates a pointer type, so I was experimenting with abstracting FILE read operations with this approach.

```<code>class FilePointer
{
    FILE* file;
    size_t position;
    FilePointer (FILE* file, size_t position)
    {
        this->file = file;
        this->position = position;
    };
    public:
    FilePointer (FILE* file)
    {
        this->file = file;
        this->position = 0;
    };
    FilePointer operator+ (size_t offset)
    {
        return FilePointer(file,position + offset);
    };
    FilePointer operator++ () // Prefix : ++FilePointer
    {
        position++;
        return *this;
    };
    FilePointer operator++ (int) // Postfix : FilePointer++
    {
        FilePointer before = *this;
        position++;
        return before;
    };
    FilePointer operator+= (size_t offset)
    {
        position += offset;
        return *this;
    };
    uint8_t operator* ()
    {
        fseek(file,position,SEEK_SET);
        Uint8 out;
        fread(&out,1,1,file);
        return out;
    };
    uint8_t operator[] (size_t offset)
    {
        return *(*this + offset);
    };

};
</code>```

As can be seen in the above code snippet I was able to find out how to differentiate between the variations of increment operator so that given FilePointer f; f++ and ++f would behave intuitively.

What if I want to use this class for file writes, though? Currently I can grab a byte uint8_t something = f[0]; and it works, but if I want to "set" something, i.e. f[0] = 100;, the overloads as they are will not work for this.

Aside from whether or not this is "good practice" (though feel free to weigh in about that too), is there a way to implement this behavior in operator overloads for a class?

```<code>uint8_t n = f[0];
n++;
f[0] = n;
</code>```

Or, getting even fancier, something like this:

```<code>f[1]++;
</code>```

One way I imagine it could be done is by implementing yet another class which represents a "dereferenced FilePointer", but was curious if it is possible to do with only the overloads in the FilePointer class itself.

答:
Another approach to improve the performance of 1 character writes might be that your proxy file pointer is actually a buffer that collects a number of assignments somehow, and then spools them all to the file on destruction.

One thing to be aware of with the proxy approach is the caller could keep hold of a number of your proxy objects using auto or auto&, and attempt to update them out of order. I don't think there is an efficient way to resolve this issue.

Also, what about operator --? Though the c++ library does have the concept of one-way iterators. perhaps iterators are the better metaphor?

Body:
With C++ operator overloads, it is possible to create a class which emulates a pointer type, so I was experimenting with abstracting FILE read operations with this approach.

class FilePointer
{
    FILE* file;
    size_t position;
    FilePointer (FILE* file, size_t position)
    {
        this->file = file;
        this->position = position;
    };
    public:
    FilePointer (FILE* file)
    {
        this->file = file;
        this->position = 0;
    };
    FilePointer operator+ (size_t offset)
    {
        return FilePointer(file,position + offset);
    };
    FilePointer operator++ () // Prefix : ++FilePointer
    {
        position++;
        return *this;
    };
    FilePointer operator++ (int) // Postfix : FilePointer++
    {
        FilePointer before = *this;
        position++;
        return before;
    };
    FilePointer operator+= (size_t offset)
    {
        position += offset;
        return *this;
    };
    uint8_t operator* ()
    {
        fseek(file,position,SEEK_SET);
        Uint8 out;
        fread(&out,1,1,file);
        return out;
    };
    uint8_t operator[] (size_t offset)
    {
        return *(*this + offset);
    };

};

As can be seen in the above code snippet I was able to find out how to differentiate between the variations of increment operator so that given FilePointer f; f++ and ++f would behave intuitively.

What if I want to use this class for file writes, though? Currently I can grab a byte uint8_t something = f[0]; and it works, but if I want to "set" something, i.e. f[0] = 100;, the overloads as they are will not work for this.

Aside from whether or not this is "good practice" (though feel free to weigh in about that too), is there a way to implement this behavior in operator overloads for a class?

uint8_t n = f[0];
n++;
f[0] = n;

Or, getting even fancier, something like this:

f[1]++;

One way I imagine it could be done is by implementing yet another class which represents a "dereferenced FilePointer", but was curious if it is possible to do with only the overloads in the FilePointer class itself.


问:
In a max heap H of n elements, the top 2 powerk -1 elements are in the first k levels. How to prove this as false?
Prove the above statement as false.

n and k are positive integers such that 2 powerk -1<=n.

In a max heap of n elements, the top 2 powerk -1 elements are in the first k levels.

答:
I think you mean:

The top 2k-1 elements are in the top k levels.

We can prove this by contradiction. Here is a max heap of 15 items.

```<code>         F
       /   \
     E       7
    / \     / \
   D   A   6   5
  / \ / \ / \ / \
  C B 9 8 4 3 2 1
</code>```

This is a valid heap. Every item is smaller than its parent.

So let's assume your assertion is correct, that the top 2k-1 elements are in the top k levels. So the top 4 (23-1) elements should be in the top 3 levels. In this case, that would be F, E, D, and C. But C is in the 4th level. That contradicts the assertion.

Or do you mean that the top 2k-1 items must be in the top k levels? In that case, the top 3 (22-1) must be in the top 2 levels. But again, the item D, which is the 3rd largest, is in the 3rd level. Again, that contradicts the assertion.

Body:
I think you mean:

The top 2k-1 elements are in the top k levels.

We can prove this by contradiction. Here is a max heap of 15 items.

         F
       /   \
     E       7
    / \     / \
   D   A   6   5
  / \ / \ / \ / \
  C B 9 8 4 3 2 1

This is a valid heap. Every item is smaller than its parent.

So let's assume your assertion is correct, that the top 2k-1 elements are in the top k levels. So the top 4 (23-1) elements should be in the top 3 levels. In this case, that would be F, E, D, and C. But C is in the 4th level. That contradicts the assertion.

Or do you mean that the top 2k-1 items must be in the top k levels? In that case, the top 3 (22-1) must be in the top 2 levels. But again, the item D, which is the 3rd largest, is in the 3rd level. Again, that contradicts the assertion.


问:
Read specific value of an object
I'm using an api that return this object:

```<code>   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }
</code>```

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks

答:
You can try this:

const data = {
  "0155894402285712": {
    "type": "GBUserFieldText",
    "value": "A0242",
    "name": "Codice+tessera"
  },
  "0155894402283800": {
    "type": "GBUserFieldText",
    "value": "LZZMRN55L53C003Z",
    "name": "Codice+Fiscale"
  }
};

// get an array of all the values of this data.
const arrayOfValues = Object.values(data);
// filter this array in order to find the one which the name you want
const selectedObj = arrayOfValues.find(obj => obj.name === 'Codice+tessera');
// get the value of this object.
const selectedValue = selectedObj.value;
console.log(selectedValue);```
</div>
</div>
</p>

```// You can also make a function findValueOf(name):
const findValueOf = name =>
    arrayOfValues.find(obj => obj.name === name) &&
    arrayOfValues.find(obj => obj.name === name).value;

// and use it for example:
console.log(findValueOf('Codice+tessera')); // "A0242"
console.log(findValueOf('Codice+Fiscale')); // "LZZMRN55L53C003Z"
```

Title: Read specific value of an object

Body:
I'm using an api that return this object:

   {
        "0155894402285712": { "type": "GBUserFieldText", "value": "A0242", "name": "Codice+tessera" },
        "0155894402283800": { "type": "GBUserFieldText", "value": "LZZMRN55L53C003Z", "name": "Codice+Fiscale" }
    }

I need to extract the value A0242 and LZZMRN55L53C003Z but the only things that I know are the name "Codice+tessera" and "Codice+fiscale". How can I read these values? Maybe my question is stupid but really I'm losing my brain today...

Thanks

Body:
You can try this:

const data = {
  "0155894402285712": {
    "type": "GBUserFieldText",
    "value": "A0242",
    "name": "Codice+tessera"
  },
  "0155894402283800": {
    "type": "GBUserFieldText",
    "value": "LZZMRN55L53C003Z",
    "name": "Codice+Fiscale"
  }
};

// get an array of all the values of this data.
const arrayOfValues = Object.values(data);
// filter this array in order to find the one which the name you want
const selectedObj = arrayOfValues.find(obj => obj.name === 'Codice+tessera');
// get the value of this object.
const selectedValue = selectedObj.value;
console.log(selectedValue);

// You can also make a function findValueOf(name):
const findValueOf = name =>
    arrayOfValues.find(obj => obj.name === name) &&
    arrayOfValues.find(obj => obj.name === name).value;

// and use it for example:
console.log(findValueOf('Codice+tessera')); // "A0242"
console.log(findValueOf('Codice+Fiscale')); // "LZZMRN55L53C003Z"


问:
How to make dynamic content change in infinite scroll
I'm using a package called react-infinite-scroller (https://www.npmjs.com/package/react-infinite-scroller). I'm having header with dynamic topics if i click on any topic i need to show the data belongs to that topic.
hasLoadMore() is a function in that package that will give the next page that i need to send API to get the next set of data. If I change the topic, hasLoadMore() function giving the page, not starting from 0 instead it gives me the page number where the page previously loaded.
How can I implement that.

<InfiniteScroll
  pageStart={0}
  loadMore={this.getPaymentPendingInvoices}
  hasMore={this.state.hasMorePaymentPendingItems}
  loader={this.renderSkeletonLoader()}
  threshold={50}
>
  <>
    {data &&
    data.map((item, index) => {
    return (

      <InvoiceCard
      invoice={item}
      showModal={this.showModal}
      closeModal={this.closeModal}
      />

    );
    })}
  </>
</InfiniteScroll>```

答:
You should create a state variable and set pageStart equal to that. Conditionally render that variable by using a boolean to check whether not you need it to start at zero.

<InfiniteScroll
  pageStart={this.state.shouldStartAtZero ? 0 : this.state.pageStart}
  loadMore={this.getPaymentPendingInvoices}
  hasMore={this.state.hasMorePaymentPendingItems}
  loader={this.renderSkeletonLoader()}
  threshold={50}
>
```


问:
Why does the Rust documentation say that a while loop over an array is slower than a for loop?
As I was reading the rust documentation, I stumbled upon this code that iterates the array a using a while loop (with an index):

```<code>fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}
</code>```

The documentation says:

... this approach is error prone; we could cause the program to panic if the index length is incorrect. It’s also slow, because the compiler adds runtime code to perform the conditional check on every element on every iteration through the loop.

The first reason was self-explanatory. The second reason was where I got confused.

Furthermore, they suggested to use a for-loop for this.

```<code>fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }
}
</code>```

I just can't seem to wrap my head around this. Is there some kind of behavior that the Rust compiler does?

答:
The two parts are complementary:

we could cause the program to panic if the index length is incorrect.

Every time you write some_slice[some_index], the standard library does the equivalent of:

```<code>if some_index < some_slice.len() {
    some_slice.get_the_value_without_checks(some_index)
} else {
    panic!("Hey, stop that");
}
</code>```

the compiler adds runtime code to perform the conditional check on every element

In a loop, this works out to be something like:

```<code>while some_index < limit {
    if some_index < some_slice.len() {
        some_slice.get_the_value_without_checks(some_index)
    } else {
        panic!("Hey, stop that");
    }
    some_index += 1;
}
</code>```

Those repeated conditionals aren't the most efficient code.

The implementations of Iterator for slices utilize unsafe code to be more efficient at the expense of more complicated code. The iterators contain raw pointers to the data but ensure that you can never misuse them to cause memory unsafety. Without needing to perform that conditional at each step, the iterator solution is often faster1. It's more-or-less equivalent to:

```<code>while some_index < limit {
    some_slice.get_the_value_without_checks(some_index)
    some_index += 1;
}
</code>```

See also:

Does Rust's array bounds checking affect performance?

Does Rust optimize for loops over calculated ranges?

1 — as Matthieu M. points out:

It should be noted that the optimizer may (or may not) be able to remove the bounds check in the while case. If it succeeds, then performance is equivalent; if it fails, suddenly your code is slower. In microbenchmarks, with simple code, changes are it will succeed... but this may not carry to your production code, or it may carry now, and the next change in the loop body will prevent the optimization, etc... In short, a while loop can be a performance ticking bomb.

See also:

Why does my code run slower when I remove bounds checks?

Body:
As I was reading the rust documentation, I stumbled upon this code that iterates the array a using a while loop (with an index):

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}

The documentation says:

... this approach is error prone; we could cause the program to panic if the index length is incorrect. It’s also slow, because the compiler adds runtime code to perform the conditional check on every element on every iteration through the loop.

The first reason was self-explanatory. The second reason was where I got confused.

Furthermore, they suggested to use a for-loop for this.

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }
}

I just can't seem to wrap my head around this. Is there some kind of behavior that the Rust compiler does?

Body:
The two parts are complementary:

we could cause the program to panic if the index length is incorrect.

Every time you write some_slice[some_index], the standard library does the equivalent of:

if some_index < some_slice.len() {
    some_slice.get_the_value_without_checks(some_index)
} else {
    panic!("Hey, stop that");
}

the compiler adds runtime code to perform the conditional check on every element

In a loop, this works out to be something like:

while some_index < limit {
    if some_index < some_slice.len() {
        some_slice.get_the_value_without_checks(some_index)
    } else {
        panic!("Hey, stop that");
    }
    some_index += 1;
}

Those repeated conditionals aren't the most efficient code.

The implementations of Iterator for slices utilize unsafe code to be more efficient at the expense of more complicated code. The iterators contain raw pointers to the data but ensure that you can never misuse them to cause memory unsafety. Without needing to perform that conditional at each step, the iterator solution is often faster1. It's more-or-less equivalent to:

while some_index < limit {
    some_slice.get_the_value_without_checks(some_index)
    some_index += 1;
}

See also:

Does Rust's array bounds checking affect performance?

Does Rust optimize for loops over calculated ranges?

1 — as Matthieu M. points out:

It should be noted that the optimizer may (or may not) be able to remove the bounds check in the while case. If it succeeds, then performance is equivalent; if it fails, suddenly your code is slower. In microbenchmarks, with simple code, changes are it will succeed... but this may not carry to your production code, or it may carry now, and the next change in the loop body will prevent the optimization, etc... In short, a while loop can be a performance ticking bomb.

See also:

Why does my code run slower when I remove bounds checks?


问:
Adding dictonary into the dictonary using 'for' loop
Below are the lists :

```<code>text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]
</code>```

And using below code I am updating this list item in value of dictonary verb.

```<code>verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

verb.update(verb [i])
verb
</code>```

And I am getting an output as follow:

```<code>{0: {'Verb Text': 'is',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': []},
 1: {'Verb Text': 'ramping',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['Cola',
   'is',
   'up',
   'launches',
   'brings',
   'drink',
   '.']},
 2: {'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['as', 'it', 'mineral']},
 'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']}
</code>```

In the output the issue is its creating below key value pair two times

```<code>'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']
</code>```

Any comments will be appreciated..!!

答:
You are updating the dictionary at the end outside the loop and that caused duplication of the last value. Remove the dict.update outside loop:

```<code>verb = {}
for i in range(0 , len(text)):
    verb[i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

#verb.update(verb [i])  <- Remove this line

print(verb)
</code>```

A better way would be using the built-in zip and enumerate like:

```<code>verb = {}
for i, (x, y, z) in enumerate(zip(text, head, childWord)):
    verb[i] =  {'Verb Text': x, 'Text Head of the verb': y, 'Child Word of the verb': z}

print(verb)
</code>```

which again using dictionary-comprehension:

```<code>verb = {i: {'Verb Text': x, 'Text Head of the verb': y, 'Child Word of the verb': z} for i, (x, y, z) in enumerate(zip(text, head, childWord))}
</code>```

Body:
Below are the lists :

text = ['is', 'ramping', 'brings']
head = ['ramping', 'ramping', 'ramping']
childWord = [[],
 ['Cola', 'is', 'up', 'launches', 'brings', 'drink', '.'],
 ['as', 'it', 'mineral']]

And using below code I am updating this list item in value of dictonary verb.

verb = {}
for i in range(0 , len(text)):

    verb [i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

verb.update(verb [i])
verb

And I am getting an output as follow:

{0: {'Verb Text': 'is',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': []},
 1: {'Verb Text': 'ramping',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['Cola',
   'is',
   'up',
   'launches',
   'brings',
   'drink',
   '.']},
 2: {'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': ['as', 'it', 'mineral']},
 'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']}

In the output the issue is its creating below key value pair two times

'Verb Text': 'brings',
 'Text Head of the verb': 'ramping',
 'Child Word of the verb': ['as', 'it', 'mineral']

Any comments will be appreciated..!!

Body:
You are updating the dictionary at the end outside the loop and that caused duplication of the last value. Remove the dict.update outside loop:

verb = {}
for i in range(0 , len(text)):
    verb[i] = {'Verb Text': text[i], 'Text Head of the verb' : head[i], 'Child Word of the verb' : childWord[i]}

#verb.update(verb [i])  <- Remove this line

print(verb)

A better way would be using the built-in zip and enumerate like:

verb = {}
for i, (x, y, z) in enumerate(zip(text, head, childWord)):
    verb[i] =  {'Verb Text': x, 'Text Head of the verb': y, 'Child Word of the verb': z}

print(verb)

which again using dictionary-comprehension:

verb = {i: {'Verb Text': x, 'Text Head of the verb': y, 'Child Word of the verb': z} for i, (x, y, z) in enumerate(zip(text, head, childWord))}


问:
If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?
I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.

```<code>import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
</code>```

Based on feedback from the answers, I have constructed another, shorter example:

```<code>Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.
</code>```

What causes this cast to fail?

答:
Can you try executing this:

```<code>package classtest;

import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;

public class A {

    public static void main(String[] args) {
        testCast(new DERSequence());
    }

    private static void testCast(Object o) {
        DERSequence o2 = (DERSequence) o;
        ASN1Sequence o3 = o2;
        ASN1Object o4 = o3;

        ASN1Object o5 = (ASN1Object) o;
    }

}
</code>```

(for me, this does not throw any exception)

If this does not work, you should check the answer of vickirk

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.

import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
...

ASN1InputStream ais = ...;
Object o = ais.readObject();
// Eclipse's debugger now says o is a DERSequence, as expected.

DERSequence o2 = (DERSequence)o;
ASN1Sequence o3 = o2;
ASN1Object o4 = o3;
// And o4 is now exactly what I want.

ASN1Object o5 = (ASN1Object)o;
// But this throws:
///    java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence

Based on feedback from the answers, I have constructed another, shorter example:

Object o = new DERSequence();
ASN1Object o1 = new DERSequence(); // This behaves fine.
ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException.

What causes this cast to fail?

Body:
Can you try executing this:

package classtest;

import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;

public class A {

    public static void main(String[] args) {
        testCast(new DERSequence());
    }

    private static void testCast(Object o) {
        DERSequence o2 = (DERSequence) o;
        ASN1Sequence o3 = o2;
        ASN1Object o4 = o3;

        ASN1Object o5 = (ASN1Object) o;
    }

}

(for me, this does not throw any exception)

If this does not work, you should check the answer of vickirk


问:
Create AWS Athena view programmatically
Can you create views in Amazon Athena? outlines how to create a view using the User Interface.

I'd like to create an AWS Athena View programatically, ideally using Terraform (which calls CloudFormation).

I followed the steps outlined here: https://ujjwalbhardwaj.me/post/create-virtual-views-with-aws-glue-and-query-them-using-athena, however I run into an issue with this in that the view goes stale quickly.

...._view' is stale; it must be re-created.

The terraform code looks like this:

```<code>resource "aws_glue_catalog_table" "adobe_session_view" {

  database_name = "${var.database_name}"
  name = "session_view"

  table_type = "VIRTUAL_VIEW"
  view_original_text = "/* Presto View: ${base64encode(data.template_file.query_file.rendered)} */"
  view_expanded_text = "/* Presto View */"

  parameters = {
    presto_view = "true"
    comment = "Presto View"
  }

  storage_descriptor {
    ser_de_info {
      name = "ParquetHiveSerDe"
      serialization_library = "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"
    }

    columns { name = "first_column" type = "string" }
    columns { name = "second_column" type = "int" }
    ...
    columns { name = "nth_column" type = "string" }
}
</code>```

An alternative I'd be happy to use is the AWS CLI, however aws athena [option] provides no option for this.

I've tried:

create-named-query which I have not been able to get working for a statement such as CREATE OR REPLACE VIEW as this doesn't seem to be the intended use case for this command.

start-query-execution which asks for an output location, which suggests that this is meant for querying the data and outputting the results, as opposed to making stateful changes/creations. It also seems to be paired with stop-query-execution.

答:
Creating views programmatically in Athena is not documented, and unsupported, but possible. What happens behind the scenes when you create a view using StartQueryExecution is that Athena lets Presto create the view and then extracts Presto's internal representation and puts it in the Glue catalog.

The staleness problem usually comes from the columns in the Presto metadata and the Glue metadata being out of sync. An Athena view really contains three descriptions of the view: the view SQL, the columns and their types in Glue format, and the columns and types in Presto format. If either of these get out of sync you will get the "… is stale; it must be re-created." error.

These are the requirements on a Glue table to work as an Athena view:

TableType must be VIRTUAL_VIEW

Parameters must contain presto_view: true

TableInput.ViewOriginalText must contain an encoded Presto view (see below)

StorageDescriptor.SerdeInfo must be an empty map

StorageDescriptor.Columns must contain all the columns that the view defines, with their types

The tricky part is the encoded Presto view. That structure is created by this code: https://github.com/prestosql/presto/blob/27a1b0e304be841055b461e2c00490dae4e30a4e/presto-hive/src/main/java/io/prestosql/plugin/hive/HiveUtil.java#L597-L600, and this is more or less what it does:

Adds a prefix /* Presto View: (with a space after :)

Adds a base 64 encoded JSON string that contains the view SQL, the columns and their types, and some catalog metadata (see below)

Adds a suffix */ (with a space before *)

The JSON that describes the view looks like this:

A catalog property that must have the value awsdatacatalog.

A schema property that must be the name of the database where the view is created (i.e. it must match the DatabaseName property of the surrounding Glue structure.

A list of columns, each with a name and type

A originalSql property with the actual view SQL (not including CREATE VIEW …, it should start with SELECT … or WITH …)

Here's an example:

```<code>{
  "catalog": "awsdatacatalog",
  "schema": "some_database",
  "columns": [
    {"name": "col1", "type": "varchar"},
    {"name": "col2", "type": "bigint"}
  ],
  "originalSql": "SELECT col1, col2 FROM some_other_table"
}
</code>```

One caveat here is that the types of the columns are almost, but not quite, the same as the names in Glue. If Athena/Glue would have string the value in this JSON must be varchar. If the Athena/Glue uses array<string> the value in this JSON must be array(varchar), and struct<foo:int> becomes row(foo int).

This is pretty messy, and putting it all together requires some fiddling and testing. The easiest way to get it working is to create a few views and decoding working the instructions above backwards to see how they look, and then try doing it yourself.

Title: Create AWS Athena view programmatically

Body:
Can you create views in Amazon Athena? outlines how to create a view using the User Interface.

I'd like to create an AWS Athena View programatically, ideally using Terraform (which calls CloudFormation).

I followed the steps outlined here: https://ujjwalbhardwaj.me/post/create-virtual-views-with-aws-glue-and-query-them-using-athena, however I run into an issue with this in that the view goes stale quickly.

...._view' is stale; it must be re-created.

The terraform code looks like this:

resource "aws_glue_catalog_table" "adobe_session_view" {

  database_name = "${var.database_name}"
  name = "session_view"

  table_type = "VIRTUAL_VIEW"
  view_original_text = "/* Presto View: ${base64encode(data.template_file.query_file.rendered)} */"
  view_expanded_text = "/* Presto View */"

  parameters = {
    presto_view = "true"
    comment = "Presto View"
  }

  storage_descriptor {
    ser_de_info {
      name = "ParquetHiveSerDe"
      serialization_library = "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"
    }

    columns { name = "first_column" type = "string" }
    columns { name = "second_column" type = "int" }
    ...
    columns { name = "nth_column" type = "string" }
}

An alternative I'd be happy to use is the AWS CLI, however aws athena [option] provides no option for this.

I've tried:

create-named-query which I have not been able to get working for a statement such as CREATE OR REPLACE VIEW as this doesn't seem to be the intended use case for this command.

start-query-execution which asks for an output location, which suggests that this is meant for querying the data and outputting the results, as opposed to making stateful changes/creations. It also seems to be paired with stop-query-execution.

Body:
Creating views programmatically in Athena is not documented, and unsupported, but possible. What happens behind the scenes when you create a view using StartQueryExecution is that Athena lets Presto create the view and then extracts Presto's internal representation and puts it in the Glue catalog.

The staleness problem usually comes from the columns in the Presto metadata and the Glue metadata being out of sync. An Athena view really contains three descriptions of the view: the view SQL, the columns and their types in Glue format, and the columns and types in Presto format. If either of these get out of sync you will get the "… is stale; it must be re-created." error.

These are the requirements on a Glue table to work as an Athena view:

TableType must be VIRTUAL_VIEW

Parameters must contain presto_view: true

TableInput.ViewOriginalText must contain an encoded Presto view (see below)

StorageDescriptor.SerdeInfo must be an empty map

StorageDescriptor.Columns must contain all the columns that the view defines, with their types

The tricky part is the encoded Presto view. That structure is created by this code: https://github.com/prestosql/presto/blob/27a1b0e304be841055b461e2c00490dae4e30a4e/presto-hive/src/main/java/io/prestosql/plugin/hive/HiveUtil.java#L597-L600, and this is more or less what it does:

Adds a prefix /* Presto View: (with a space after :)

Adds a base 64 encoded JSON string that contains the view SQL, the columns and their types, and some catalog metadata (see below)

Adds a suffix */ (with a space before *)

The JSON that describes the view looks like this:

A catalog property that must have the value awsdatacatalog.

A schema property that must be the name of the database where the view is created (i.e. it must match the DatabaseName property of the surrounding Glue structure.

A list of columns, each with a name and type

A originalSql property with the actual view SQL (not including CREATE VIEW …, it should start with SELECT … or WITH …)

Here's an example:

{
  "catalog": "awsdatacatalog",
  "schema": "some_database",
  "columns": [
    {"name": "col1", "type": "varchar"},
    {"name": "col2", "type": "bigint"}
  ],
  "originalSql": "SELECT col1, col2 FROM some_other_table"
}

One caveat here is that the types of the columns are almost, but not quite, the same as the names in Glue. If Athena/Glue would have string the value in this JSON must be varchar. If the Athena/Glue uses array<string> the value in this JSON must be array(varchar), and struct<foo:int> becomes row(foo int).

This is pretty messy, and putting it all together requires some fiddling and testing. The easiest way to get it working is to create a few views and decoding working the instructions above backwards to see how they look, and then try doing it yourself.


问:
How to know if a some item or object is using a Model in rails
I have the following situation:

A model called State with some info:

```<code>pry(main)> State.last
</code>```

```<code> id: 35,
 region_id: 6,
 name: "São Paulo",
 abbreviation: "SP",
 created_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 updated_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 deleted_at: nil>
</code>```

I want to know which Cities or another models and objects, is using this determined id.

This is the schema.rb to Cities

```<code>  create_table "cities", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.integer  "state_id",   null: false
    t.string   "name",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.datetime "deleted_at"
    t.index ["deleted_at"], name: "index_cities_on_deleted_at", using: :btree
    t.index ["state_id"], name: "index_cities_on_state_id", using: :btree
  end
</code>```

Obs: "I tried to find some answer related to this topic, but I didn't found", If exists, please, report me and I will delete this question.

Thanks a lot

答:
First, you need to define the relationship between City and State.

# app/models/city.rb

class City < ApplicationRecord
  belongs_to :state
end
```

<pre class="lang-rb prettyprint-override"><code># app/models/state.rb

class State < ApplicationRecord
  has_many :cities
end
</code>```

Now in the console you can call:

```<code>State.last.cities
</code>```

Body:
I have the following situation:

A model called State with some info:

pry(main)> State.last

 id: 35,
 region_id: 6,
 name: "São Paulo",
 abbreviation: "SP",
 created_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 updated_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 deleted_at: nil>

I want to know which Cities or another models and objects, is using this determined id.

This is the schema.rb to Cities

  create_table "cities", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.integer  "state_id",   null: false
    t.string   "name",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.datetime "deleted_at"
    t.index ["deleted_at"], name: "index_cities_on_deleted_at", using: :btree
    t.index ["state_id"], name: "index_cities_on_state_id", using: :btree
  end

Obs: "I tried to find some answer related to this topic, but I didn't found", If exists, please, report me and I will delete this question.

Thanks a lot

Body:
First, you need to define the relationship between City and State.

# app/models/city.rb

class City < ApplicationRecord
  belongs_to :state
end

# app/models/state.rb

class State < ApplicationRecord
  has_many :cities
end

Now in the console you can call:

State.last.cities


问:
Nifi: Cannot import pyspark in ExecuteScript processor
I need to implement ExecuteScript in Nifi in order to do column transposition, and I am using pyspark as means to do that.

But the problem says
"failed to process due to javax.script.ScriptExeption: ImportError: No module named pyspark in  at line number 1:"

I set the path to spark and pyspark like this for module directory setting in ExecuteScript property.

```<code>C:\Users\username\Desktop\spark\spark-2.4.3-bin-hadoop2.7\hadoop,
C:\Users\username\Desktop\spark\spark-2.4.3-bin-hadoop2.7\bin\pyspark
</code>```

But it did not work.

I am afraid this is very fundamental issue, could not figure out half a day..

答:
This is likely because the pyspark module is a natively-compiled Python module, and Apache NiFi uses Jython in the ExecuteScript processor. This is a known issue, and the full explanation is here, as well as some work-arounds and details on options.

The simplest answer is to use ExecuteStreamCommand and pass the necessary flowfile attributes as arguments, and the content as STDIN. The output of the Python script will be returned via STDOUT and captured as the new flowfile content.

Body:
I need to implement ExecuteScript in Nifi in order to do column transposition, and I am using pyspark as means to do that.

But the problem says
"failed to process due to javax.script.ScriptExeption: ImportError: No module named pyspark in  at line number 1:"

I set the path to spark and pyspark like this for module directory setting in ExecuteScript property.

C:\Users\username\Desktop\spark\spark-2.4.3-bin-hadoop2.7\hadoop,
C:\Users\username\Desktop\spark\spark-2.4.3-bin-hadoop2.7\bin\pyspark

But it did not work.

I am afraid this is very fundamental issue, could not figure out half a day..


问:
Python: adding days to time epoch
I have a dataframe time series with a DateTime column. The DateTime was converted to epoch timestamp using:

```<code>df['Epoch'] = df['DateTime'].astype('int64')//1e9
</code>```

Now, I want to add to each row of Epoch:

```<code>year = 10
month 10
day = 29
hour = 15
minute = 0
second = 0
</code>```

Tried searching no result yet.

答:
Try add the offset before convert:</p>

```<code>offset = pd.DateOffset(years=10, months=10, days=29, hours=15)
df['Epoch'] = (df['DateTime'] + offset).astype('int64')//1e9
</code>```

Title: Python: adding days to time epoch

Body:
I have a dataframe time series with a DateTime column. The DateTime was converted to epoch timestamp using:

df['Epoch'] = df['DateTime'].astype('int64')//1e9

Now, I want to add to each row of Epoch:

year = 10
month 10
day = 29
hour = 15
minute = 0
second = 0

Tried searching no result yet.

Body:
Try add the offset before convert:

offset = pd.DateOffset(years=10, months=10, days=29, hours=15)
df['Epoch'] = (df['DateTime'] + offset).astype('int64')//1e9


问:
What is the difference between annotating EntityManager with @Autowired and @PersistenceContext? Which one should be preferred?
I am developing a Spring-Boot application using spring-boot-starter-data-jpa. I am not able to understand which annotation I should use for injecting EntityManager?
@Autowired or @PersistenceContext

I know @PersistenceContext is a JPA annotation whereas @Autowired belongs to Spring. But internally how do they make a difference?
I have already taken a look at this. But could not understand the exact reason.

答:
A datasource is source of data. This could be for example a database.

One option if you need multiple datasources is to define them in a persistence.xml file. Here you can define multiple and separate them by name.

@PersistenceContext will then give you more fine grain of what you want to inject. Here you can select which datasource by defined name. There are some other options too.
https://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html

If using @Autowire you are just injecting the available persistence context by bean name. If you have 2 or more persistence contexts this may fail because of ambiguity.


问:
Linq to Nhibernate Error
i am trying to implement a search method. which try to check if a string consist any element from the specified list of strings .

```<code> customers = GetSession().Linq<customer>();
 if (!searchFilter.Expertises.IsEmpty())
 {
     customers = customers.Where(x => searchFilter.Expertises.Any(s => x.Spec.Expertise.Contains(s)));
 }
 return customers.ToList();
</code>```

But this Throws an error, seems linq to nhibernate does not support "Any"

please help me implementing this

答:
You are right that it does not support any. I would look to rewrite this using something like PredicateBuilder :

http://www.albahari.com/nutshell/predicatebuilder.aspx

Hope this helps.

Title: Linq to Nhibernate Error

Body:
i am trying to implement a search method. which try to check if a string consist any element from the specified list of strings .

 customers = GetSession().Linq<customer>();
 if (!searchFilter.Expertises.IsEmpty())
 {
     customers = customers.Where(x => searchFilter.Expertises.Any(s => x.Spec.Expertise.Contains(s)));
 }
 return customers.ToList();

But this Throws an error, seems linq to nhibernate does not support "Any"

please help me implementing this


问:
Temporary failure in name resolution [Errno -3] with Docker
I'm following the docker tutorial and am on the part where I have to build the app using:

```<code>docker build -t friendlyhello .
</code>```

It reaches up to step 4, where after a pause I get this error:

```<code>Step 4/7 : RUN pip install -r requirements.txt
 ---> Running in 7f4635a7510a
Collecting Flask (from -r requirements.txt (line 1))

Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after
connection broken by
'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection
object at 0x7fe3984d9b10>: Failed to establish a new connection:
[Errno -3] Temporary failure in name resolution',)': /simple/flask/
</code>```

I'm not quite sure what this error means and how I can go about solving it.

Thanks for your help!

答: I had this problem on Windows 10 Pro and I solved it by right clicking on the docker icon in the tray and choosing "Restart...".  It took a few mins and then the network was running fine again.</p>

Body:
I'm following the docker tutorial and am on the part where I have to build the app using:

docker build -t friendlyhello .

It reaches up to step 4, where after a pause I get this error:

Step 4/7 : RUN pip install -r requirements.txt
 ---> Running in 7f4635a7510a
Collecting Flask (from -r requirements.txt (line 1))

Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after
connection broken by
'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection
object at 0x7fe3984d9b10>: Failed to establish a new connection:
[Errno -3] Temporary failure in name resolution',)': /simple/flask/

I'm not quite sure what this error means and how I can go about solving it.

Thanks for your help!


问:
ConnectException: Connection refused: connect
the problem is that despite having set the data I believe correctly I get the error in the title.

It is usually an error due to wrong input parameters, but both the host and the port are correct. I don't really understand where I'm wrong.

The code is as follows:

```<code>public void login(String host, String username, String password)
            throws Exception {
        URLName url = new URLName(protocol, host, 995, file, username, password);
        if (session == null) {
            Properties props = null;
            try {
                            props = System.getProperties();
                            props.setProperty("mail.store.protocol", "pop3s");
                            props.setProperty("mail.pop3s.ssl.enable", "true");
                            props.setProperty("mail.pop3s.localport", "995");
                            props.setProperty("mail.pop3s.host", "pop3s.pec.aruba.it");
            } catch (SecurityException sex) {
                            props = new Properties();
            }
            session = Session.getDefaultInstance(props
                                ,new javax.mail.Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(username,password);}}
);
        }
        store = session.getStore("pop3s");
        store.connect(host, username, password);
        folder = store.getFolder(url);
        folder.open(Folder.READ_ONLY);
    }
</code>```

I expected that the connection works.
instead I get the following error message:

```<code>GRAVE: null
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: pop3s.pec.aruba.it, 995; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:211)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at sorellecongiusnc.mavgestipan.EmailBox.login(EmailBox.java:64)
    at sorellecongiusnc.mavgestipan.JFrameStart.jButton5ActionPerformed(JFrameStart.java:1234)
    at sorellecongiusnc.mavgestipan.JFrameStart.access$200(JFrameStart.java:72)
    at sorellecongiusnc.mavgestipan.JFrameStart$3.actionPerformed(JFrameStart.java:641)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.pop3.Protocol.<init>(Protocol.java:112)
    at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:265)
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
    ... 42 more
</code>```

Any suggestions?

答: You are setting property mail.pop3s.localport to a value of 995. This is setting the port that the application binds to locally to create a connection to the server rather than selecting the port on the server to connect to. That is probably not what you want. Try changing it to mail.pop3s.port as that will be setting the port for the mail server you are connecting to.

Body:
the problem is that despite having set the data I believe correctly I get the error in the title.

It is usually an error due to wrong input parameters, but both the host and the port are correct. I don't really understand where I'm wrong.

The code is as follows:

public void login(String host, String username, String password)
            throws Exception {
        URLName url = new URLName(protocol, host, 995, file, username, password);
        if (session == null) {
            Properties props = null;
            try {
                            props = System.getProperties();
                            props.setProperty("mail.store.protocol", "pop3s");
                            props.setProperty("mail.pop3s.ssl.enable", "true");
                            props.setProperty("mail.pop3s.localport", "995");
                            props.setProperty("mail.pop3s.host", "pop3s.pec.aruba.it");
            } catch (SecurityException sex) {
                            props = new Properties();
            }
            session = Session.getDefaultInstance(props
                                ,new javax.mail.Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(username,password);}}
);
        }
        store = session.getStore("pop3s");
        store.connect(host, username, password);
        folder = store.getFolder(url);
        folder.open(Folder.READ_ONLY);
    }

I expected that the connection works.
instead I get the following error message:

GRAVE: null
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: pop3s.pec.aruba.it, 995; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:211)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at sorellecongiusnc.mavgestipan.EmailBox.login(EmailBox.java:64)
    at sorellecongiusnc.mavgestipan.JFrameStart.jButton5ActionPerformed(JFrameStart.java:1234)
    at sorellecongiusnc.mavgestipan.JFrameStart.access$200(JFrameStart.java:72)
    at sorellecongiusnc.mavgestipan.JFrameStart$3.actionPerformed(JFrameStart.java:641)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.pop3.Protocol.<init>(Protocol.java:112)
    at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:265)
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
    ... 42 more

Any suggestions?


问:
Prevent click event from firing when dblclick event fires
I'm handling both the click and dblclick event on a DOM element. Each one carries out a different command, but I find that when double clicking on the element, in addition to firing the double click event, the click event is also fired twice.  What is the best approach for preventing this behavior?</p>

答:
```<code>
  const toggle = () => {
      watchDouble += 1;
      setTimeout(()=>{
        if (watchDouble === 2) {
          console.log('double' + watchDouble)
        } else if (watchDouble === 1) {
          console.log("signle" + watchDouble)
        }
        watchDouble = 0
      },200);

  }
</code>```

ContentLicense: CC BY-SA 2.5


问:
Selecting from a database from Today onwards
Im trying to select a bunch of stuff from a database. Each have a date and i'd like to only display the ones whose date is equal to today onwards.

$sql="SELECT * FROM bs_events WHERE NOW() ORDER BY eventDate ";

I have tried looking everywhere and cannot find anything.

Thanks for any help guys

答:
```<code>WHERE eventDate >= CURDATE()";
</code>```

should fix you up

Body:
WHERE eventDate >= CURDATE()";

should fix you up


问:
Draw graph in NetworkX
I'm trying to draw any graph in NetworkX, but get nothing, not even errors:</p>

```<code>import networkx as nx
import matplotlib.pyplot as plt
g1=nx.petersen_graph()
nx.draw(g1)
</code>```

答:
It works fine by adding:

```<code>import matplotlib.pyplot as plt
plt.show()
</code>```

to your code. mine worked fine.

Title: Draw graph in NetworkX

Body:
I'm trying to draw any graph in NetworkX, but get nothing, not even errors:

import networkx as nx
import matplotlib.pyplot as plt
g1=nx.petersen_graph()
nx.draw(g1)

Body:
It works fine by adding:

import matplotlib.pyplot as plt
plt.show()

to your code. mine worked fine.


问:
Getting exception java.lang.IllegalStateException: EntityManagerFactory is closed while trying to save secound istance
I am learning hibernate. Everything is preaty clear at the beegining, however when I try to run my app and in main I have two operation connected with session I get exception:

```<code>java.lang.IllegalStateException: EntityManagerFactory is closed
</code>```

Below you can find my DBManager class where I habe methods for adding instances to DB:

```<code>import org.hibernate.Session;

public class DBManager
{
    public void addAutor(String name, String lastName, Book book)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Autor autor = new Autor(name,lastName,book);
        session.save(autor);
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }
    public Book addBook(int ISBN, String name, String autorName)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Book book = new Book(ISBN,name,autorName);
        session.save(book);
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
        return book;
    }
}
</code>```

Here is my HibernateUtil class for configuration of the session:

```<code>import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.addAnnotatedClass(Autor.class);
            configuration.addAnnotatedClass(Book.class);
            configuration.configure();

            StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
            standardServiceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();

            return configuration.buildSessionFactory(serviceRegistry);
        }
        catch(Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
</code>```

And finally the main class:

```<code>public class Test
{

    public static void main (String args[])
    {
        DBManager dbManager = new DBManager();
        Book book =  dbManager.addBook(1,"Hobbit","Tolkien");
        dbManager.addAutor("JRR","Tolkien",book);
    }
}
</code>```

As you can see I just put book, and than try to put Autor. What could be the reason for exception from secound method? I suppose that I do sth. wrong with closing and opening of the session, however I cannot figure out what is wrong.

答:
I found the sulution myself:

I have created the one sessionFactory object for whole class DBManager:

```<code>private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
</code>```

So in every method I open session, and than close at the end, eg:

```<code>    public void addAutor(String name, String lastName, Book book)
    {
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        Autor autor = new Autor(name,lastName,book);
        session.save(autor);
        session.getTransaction().commit();
        session.close();
    }
</code>```

Maybe someone will face the same problem.

Body:
I am learning hibernate. Everything is preaty clear at the beegining, however when I try to run my app and in main I have two operation connected with session I get exception:

java.lang.IllegalStateException: EntityManagerFactory is closed

Below you can find my DBManager class where I habe methods for adding instances to DB:

import org.hibernate.Session;

public class DBManager
{
    public void addAutor(String name, String lastName, Book book)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Autor autor = new Autor(name,lastName,book);
        session.save(autor);
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }
    public Book addBook(int ISBN, String name, String autorName)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Book book = new Book(ISBN,name,autorName);
        session.save(book);
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
        return book;
    }
}

Here is my HibernateUtil class for configuration of the session:

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.addAnnotatedClass(Autor.class);
            configuration.addAnnotatedClass(Book.class);
            configuration.configure();

            StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
            standardServiceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();

            return configuration.buildSessionFactory(serviceRegistry);
        }
        catch(Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

And finally the main class:

public class Test
{

    public static void main (String args[])
    {
        DBManager dbManager = new DBManager();
        Book book =  dbManager.addBook(1,"Hobbit","Tolkien");
        dbManager.addAutor("JRR","Tolkien",book);
    }
}

As you can see I just put book, and than try to put Autor. What could be the reason for exception from secound method? I suppose that I do sth. wrong with closing and opening of the session, however I cannot figure out what is wrong.

Body:
I found the sulution myself:

I have created the one sessionFactory object for whole class DBManager:

private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

So in every method I open session, and than close at the end, eg:

    public void addAutor(String name, String lastName, Book book)
    {
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        Autor autor = new Autor(name,lastName,book);
        session.save(autor);
        session.getTransaction().commit();
        session.close();
    }

Maybe someone will face the same problem.


问:
Is it possible to use Codable subclasses without explicitly decoding?
I've used struct MyThing:Codable { } to parse JSON a few times. Now I'd like to use a class instead of struct, because struct isn't really suited for the kind of work I need done (mutability, conformance etc.), and some subclassing. I tried this:

```<code>class Beverage:Codable{
    var name:String = ""
}
class Beer:Beverage{
    var alcoholPercent:Double = 0
}
</code>```

I don't necessarily receive a list of multiple different types of beverages in the same list, let's say I just want to decode a list of [Beer]. If I try this with a json with a single beer like {"name": "Hansa", "alcoholPercent": 5.4} and try to decode it to the Beer-class, like this:

```<code>let beer = try! JSONDecoder().decode(Beer.self, from: json.data(using: .utf8)!)
</code>```

the beer will have name: Hansa and alcoholPercent: 0.0. The name is correct, but the alcoholPercent is the default value in the class.

Is there a magic way to make subclasses automatically conform to Codable without explicitly setting the key/value of every variable?

This is working:

```<code>class Beverage:Codable{
    var name:String = ""
}
class Beer:Beverage{
    var alcoholPercent:Double = 0

    enum CodingKeys:String, CodingKey{
        case alcoholPercent
    }

    required init(from decoder: Decoder) throws {
        let values = try! decoder.container(keyedBy: CodingKeys.self)
        self.alcoholPercent = try! values.decode(Double.self, forKey: .alcoholPercent)
        try super.init(from: decoder)
    }
}
</code>```

With this code, I get "Hansa" and 5.4.
Why do I have to explicitly conform to Codable for subclasses, but not for the base class for this to work? Is there a way to do this without all the manual code? I feel like this should've worked out-of-the-box without needing the required init.

答:
What you are asking for is compiler synthesis of an override of init(from:) in Beer. Swift doesn't do that. This has been discussed on the Swift forum, for example in this thread. Itai Ferber is the primary Apple engineer responsible for the design and implementation of Codable so you can consider his response authoritative.

If you remove the Codable conformance from Beverage and add it to Beer directly (and to any other leaf subclasses of Beverage) then you might get the behavior you want. That will only work if you don't need the conformance on Beverage itself though.

Body:
I've used struct MyThing:Codable { } to parse JSON a few times. Now I'd like to use a class instead of struct, because struct isn't really suited for the kind of work I need done (mutability, conformance etc.), and some subclassing. I tried this:

class Beverage:Codable{
    var name:String = ""
}
class Beer:Beverage{
    var alcoholPercent:Double = 0
}

I don't necessarily receive a list of multiple different types of beverages in the same list, let's say I just want to decode a list of [Beer]. If I try this with a json with a single beer like {"name": "Hansa", "alcoholPercent": 5.4} and try to decode it to the Beer-class, like this:

let beer = try! JSONDecoder().decode(Beer.self, from: json.data(using: .utf8)!)

the beer will have name: Hansa and alcoholPercent: 0.0. The name is correct, but the alcoholPercent is the default value in the class.

Is there a magic way to make subclasses automatically conform to Codable without explicitly setting the key/value of every variable?

This is working:

class Beverage:Codable{
    var name:String = ""
}
class Beer:Beverage{
    var alcoholPercent:Double = 0

    enum CodingKeys:String, CodingKey{
        case alcoholPercent
    }

    required init(from decoder: Decoder) throws {
        let values = try! decoder.container(keyedBy: CodingKeys.self)
        self.alcoholPercent = try! values.decode(Double.self, forKey: .alcoholPercent)
        try super.init(from: decoder)
    }
}

With this code, I get "Hansa" and 5.4.
Why do I have to explicitly conform to Codable for subclasses, but not for the base class for this to work? Is there a way to do this without all the manual code? I feel like this should've worked out-of-the-box without needing the required init.


问:
How to convert a timestamp(yyyy-mm-dd-h-m-s to a date (yyyy-mm-dd)
I have a timestamp field that I need to drop the hrs,min,sec from so I can count by dates.

I've tried to_date, date_trunc, to_char

```<code>name.BIRTH_DT_TM = to_date(name.BIRTH_DT_TM,'DD mm YYYY HH24":"MI":"SS')
</code>```

I would like name.BIRTH_DT_TM to show as YYYY-DD-MM without the Hours Minutes and Seconds

答:
I had to use

cast(name.birth_dt_tm as date)

Body:
I have a timestamp field that I need to drop the hrs,min,sec from so I can count by dates.

I've tried to_date, date_trunc, to_char

name.BIRTH_DT_TM = to_date(name.BIRTH_DT_TM,'DD mm YYYY HH24":"MI":"SS')

I would like name.BIRTH_DT_TM to show as YYYY-DD-MM without the Hours Minutes and Seconds


问:
Activity indicator view in table cell
I have a table, I want to make it so that when I click on a cell, the activity indicator spins around it, and not somewhere in an incomprehensible place

It looks like this. In the code, I have the MainViewController module and the Presenter module which determines when to start the activity indicator. I have an outlet

```<code>@IBOutlet weak var activity: UIActivityIndicatorView! = UIActivityIndicatorView(style: .gray)
</code>```

I have two functions in the view controller that start the animation and stop

```<code>func startActivity() {
   activity.startAnimating()
}

func stopActivity() {
   activity.stopAnimating()
}
</code>```

there is a function that handles a click on a cell

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   tableView.deselectRow(at: indexPath, animated: true)
   output.callFromThePresenter(array: array[indexPath.row])

}
</code>```

This function is implemented in the presenter.

```<code>func callFromThePresenter(array: String) {

  let userInteractiveQueue = DispatchQueue.global(qos: .userInteractive)

  async {
    DispatchQueue.main.async  {
        self.view.startActivity()
    }
    userInteractiveQueue.async {
         self.interactor.functionFromInteractor(data: array)
    }
  }
}
</code>```

as I assumed, in the view controller, when you click on a cell, the callFromThePresenter () function will work, and the animation function and the data transfer function in the Interactor will start in it, as soon as the Interactor has completed this function, it will return the data to the Presenter and inside the call back function, I will run the stopActivity () function. And it worked until I decided to set the positioning

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   tableView.deselectRow(at: indexPath, animated: true)
   output.callFromThePresenter(array: array[indexPath.row])
   let cell = tableView.cellForRow(at: indexPath)
   cell?.accessoryView = self.activity
}
</code>```

as soon as i added these two lines

```<code>let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryView = self.activity
</code>```

I broke everything, as if I started up, I click on the table cell and the wheel turns where it is needed and everything works, but after receiving the result, I poke at some cell again, the whole program hangs, and I don’t know for what reason . At the same time, the functions work out how much I can understand it, because it comes to the console that the function was launched and got some result, but then the whole UI hangs tight and I can't do anything

答:
Simple example:

In Interface Builder set the Style of the table view cell to custom.

Drag a label and an activity indicator into the cell and set appropriate constraints if needed.

Select the activity indicator, press ⌘⌥4 (Attributes Inspector) and check Hides When Stopped.

Create a custom class, a subclass of UITableViewCell in the project

```<code>class TitleCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var activity: UIActivityIndicatorView!

    var isRunning : Bool = false {
        didSet {
            isRunning ? activity.startAnimating() : activity.stopAnimating()
        }
    }
}
</code>```

Set the class of the prototype cell in Interface Builder to TitleCell and connect the label and the indicator to the IBOutlets

Create a data model with at least a title and a isRunning property.

```<code>struct Model {
    let title: String
    var isRunning : Bool
}
</code>```

Declare a data source array

```<code>var items = [Model]()
</code>```

In cellForRow update the UI elements (replace the identifier with your real identifier)

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TitleCell
    let item = items[indexPath.row]
    cell.titleLabel!.text = item.title
    cell.isRunning = item.isRunning
    return cell
}
</code>```

To start and stop the indicator implement didSelectRow

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)
    items[indexPath.row].isRunning.toggle()
    tableView.reloadRows(at: [indexPath], with: .none)
}
</code>```

To change the state of the indicator use always the pattern to set isRunning in the model and reload the row.

Title: Activity indicator view in table cell

Body:
I have a table, I want to make it so that when I click on a cell, the activity indicator spins around it, and not somewhere in an incomprehensible place

It looks like this. In the code, I have the MainViewController module and the Presenter module which determines when to start the activity indicator. I have an outlet

@IBOutlet weak var activity: UIActivityIndicatorView! = UIActivityIndicatorView(style: .gray)

I have two functions in the view controller that start the animation and stop

func startActivity() {
   activity.startAnimating()
}

func stopActivity() {
   activity.stopAnimating()
}

there is a function that handles a click on a cell

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   tableView.deselectRow(at: indexPath, animated: true)
   output.callFromThePresenter(array: array[indexPath.row])

}

This function is implemented in the presenter.

func callFromThePresenter(array: String) {

  let userInteractiveQueue = DispatchQueue.global(qos: .userInteractive)

  async {
    DispatchQueue.main.async  {
        self.view.startActivity()
    }
    userInteractiveQueue.async {
         self.interactor.functionFromInteractor(data: array)
    }
  }
}

as I assumed, in the view controller, when you click on a cell, the callFromThePresenter () function will work, and the animation function and the data transfer function in the Interactor will start in it, as soon as the Interactor has completed this function, it will return the data to the Presenter and inside the call back function, I will run the stopActivity () function. And it worked until I decided to set the positioning

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   tableView.deselectRow(at: indexPath, animated: true)
   output.callFromThePresenter(array: array[indexPath.row])
   let cell = tableView.cellForRow(at: indexPath)
   cell?.accessoryView = self.activity
}

as soon as i added these two lines

let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryView = self.activity

I broke everything, as if I started up, I click on the table cell and the wheel turns where it is needed and everything works, but after receiving the result, I poke at some cell again, the whole program hangs, and I don’t know for what reason . At the same time, the functions work out how much I can understand it, because it comes to the console that the function was launched and got some result, but then the whole UI hangs tight and I can't do anything

Body:
Simple example:

In Interface Builder set the Style of the table view cell to custom.

Drag a label and an activity indicator into the cell and set appropriate constraints if needed.

Select the activity indicator, press ⌘⌥4 (Attributes Inspector) and check Hides When Stopped.

Create a custom class, a subclass of UITableViewCell in the project

class TitleCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var activity: UIActivityIndicatorView!

    var isRunning : Bool = false {
        didSet {
            isRunning ? activity.startAnimating() : activity.stopAnimating()
        }
    }
}

Set the class of the prototype cell in Interface Builder to TitleCell and connect the label and the indicator to the IBOutlets

Create a data model with at least a title and a isRunning property.

struct Model {
    let title: String
    var isRunning : Bool
}

Declare a data source array

var items = [Model]()

In cellForRow update the UI elements (replace the identifier with your real identifier)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TitleCell
    let item = items[indexPath.row]
    cell.titleLabel!.text = item.title
    cell.isRunning = item.isRunning
    return cell
}

To start and stop the indicator implement didSelectRow

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: false)
    items[indexPath.row].isRunning.toggle()
    tableView.reloadRows(at: [indexPath], with: .none)
}

To change the state of the indicator use always the pattern to set isRunning in the model and reload the row.


问:
ASP.NET losing connection to SQL Server Express after being published to IIS
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

```<code><connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>
</code>```

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?

答:
You muss allow user for iis in security. Here is oné video:
https://youtu.be/rmVtxLKmkDU

I hope thats help you.

Body:
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

<connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?


问:
Why can't I resolve nodejs default modules when using preset-env node?
I am writing a plugin for an app that runs Chromium Embedded Framework (CEF) with an older version of Node.

I threw webpack & babel into the app. When I run webpack, it fails on a file that has const fs = require('fs');, or any other default node package. This is happening both for my code and dependencies:

Module not found: Error: Can't resolve 'fs' in '/Users/me/repositories/myrepo/node_modules/chokidar'

My .babelrc is the following:

```<code>{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true
        }
      }
    ]
  ]
}
</code>```

My webpack config is essentially:

```<code>module.exports = {
  entry: './src/main.jsx',
  mode: process.env.NODE_ENV,
  devtool: isDev ? 'eval-source-map' : false,
  output: {
    path: PLUGINDIR,
    filename: 'main.js',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: ['transform-react-jsx']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.css']
  }
};
</code>```

答: webpack config also needs target: 'node'. Doing it just in .babelrc was not enough.

Body:
I am writing a plugin for an app that runs Chromium Embedded Framework (CEF) with an older version of Node.

I threw webpack & babel into the app. When I run webpack, it fails on a file that has const fs = require('fs');, or any other default node package. This is happening both for my code and dependencies:

Module not found: Error: Can't resolve 'fs' in '/Users/me/repositories/myrepo/node_modules/chokidar'

My .babelrc is the following:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": true
        }
      }
    ]
  ]
}

My webpack config is essentially:

module.exports = {
  entry: './src/main.jsx',
  mode: process.env.NODE_ENV,
  devtool: isDev ? 'eval-source-map' : false,
  output: {
    path: PLUGINDIR,
    filename: 'main.js',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: ['transform-react-jsx']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },

  resolve: {
    extensions: ['.js', '.jsx', '.css']
  }
};


问:
Selenium 2.0b3 IE WebDriver, Click not firing
When using the IE driver with IE9, occasionally the Click method will only select a button, it wont do the action of the Click(). Note this only happens occasionally, so i don't think it is the code that is the problem. Using the Firefox driver with Firefox4 has no problems. I am also having an issue where elements are not being found occasionally too, but only in IE again, not Firefox.

```<code>if (Driver.FindElement(By.Name("username")) == null) {
    //sometimes gets here in IE, never gets here in Firefox
}
Driver.FindElement(By.Name("username")).SendKeys(username);
Driver.FindElement(By.Name("surname")).SendKeys(surname);
Driver.FindElement(By.Name("firstname")).SendKeys(firstname);
string url = Driver.Url;
Driver.FindElement(By.Name("cmd")).Click();
if (Driver.Url == url) {
    //if the page didnt change, click the link again
    Driver.FindElement(By.Name("cmd")).Click();
}
</code>```

I have seen this similar questions (http://stackoverflow.com/questions/4737205/selenium-webdriver-ie-button-issue), but i do not have dynamicly generated ids.

答: Got the same problem, click does not work with my IE. I found a workaround where I do a Driver.FindElement(By.Name("...")).sendKeys("\n") to perform the click (basically I just press enter on the button). Not very clean but it works until the problem is fixed!</p>

Body:
When using the IE driver with IE9, occasionally the Click method will only select a button, it wont do the action of the Click(). Note this only happens occasionally, so i don't think it is the code that is the problem. Using the Firefox driver with Firefox4 has no problems. I am also having an issue where elements are not being found occasionally too, but only in IE again, not Firefox.

if (Driver.FindElement(By.Name("username")) == null) {
    //sometimes gets here in IE, never gets here in Firefox
}
Driver.FindElement(By.Name("username")).SendKeys(username);
Driver.FindElement(By.Name("surname")).SendKeys(surname);
Driver.FindElement(By.Name("firstname")).SendKeys(firstname);
string url = Driver.Url;
Driver.FindElement(By.Name("cmd")).Click();
if (Driver.Url == url) {
    //if the page didnt change, click the link again
    Driver.FindElement(By.Name("cmd")).Click();
}

I have seen this similar questions (http://stackoverflow.com/questions/4737205/selenium-webdriver-ie-button-issue), but i do not have dynamicly generated ids.


问:
Unresolved reference: viewModelScope - Android KTX
I'm trying to use the new viewModelScope() function provided by the new android ktx library.

In the gradle file, I've added:

```<code>implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
implementation 'androidx.core:core-ktx:1.0.2'
</code>```

but when I tied to access the viewModelScope(), I got Unresolved reference: viewModelScope error:

```<code>class MainViewModel(application: Application): AndroidViewModel(application) {

    fun fetchData(){
        viewModelScope.launch{

        }
    }
}
</code>```

I don't understand what the problem is. Any idea? Thanks.

答:
Check the release notes https://developer.android.com/jetpack/androidx/releases/lifecycle#declaring_dependencies

viewModelScope is available from v2.1.x

So you need to bump your version in your gradle file.

Body:
I'm trying to use the new viewModelScope() function provided by the new android ktx library.

In the gradle file, I've added:

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
implementation 'androidx.core:core-ktx:1.0.2'

but when I tied to access the viewModelScope(), I got Unresolved reference: viewModelScope error:

class MainViewModel(application: Application): AndroidViewModel(application) {

    fun fetchData(){
        viewModelScope.launch{

        }
    }
}

I don't understand what the problem is. Any idea? Thanks.