问:
TypeError: string indices must be integers - Cleaning my text
Trying to clean the tweets with this function:

```<code>class PreProcessTweets:
    def __init__(self):
        self._stopwords = set(stopwords.words('english') + list(punctuation) + ['AT_USER','URL'])

    def processTweets(self, list_of_tweets):
        processedTweets=[]
        for tweet in list_of_tweets:
            processedTweets.append((self._processTweet(tweet["Text"])))
        return processedTweets

    def _processTweet(self, tweet):
        tweet = tweet.lower() # convert text to lower-case
        tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))', 'URL', tweet) # remove URLs
        tweet = re.sub('@[^\s]+', 'AT_USER', tweet) # remove usernames
        tweet = re.sub(r'#([^\s]+)', r'\1', tweet) # remove the # in #hashtag
        tweet = word_tokenize(tweet) # remove repeated characters (helloooooooo into hello)
        return [word for word in tweet if word not in self._stopwords]
</code>```

And when I want to use it:

```<code>preprocessedTestSet = tweetProcessor.processTweets(tweet)
</code>```

I received this output

TypeError: string indices must be integers

What is wrong? How can I fix it?

答:
Assuming tweet is a string. You should pass it as is. You've used tweet["Text"] which is an illegal operation on a string since the index must be an integer.

```<code>def processTweets(self, list_of_tweets):
    processedTweets=[]
    for tweet in list_of_tweets:
        processedTweets.append(self._processTweet(tweet))
    return processedTweets
</code>```

Or more Pythonic:

```<code>def processTweets(self, list_of_tweets):
    return [self._processTweet(tweet) for tweet in list_of_tweets]
</code>```

Notes:

You probably forgot to use raw strings (r"") in some of your regex.

Body:
Trying to clean the tweets with this function:

class PreProcessTweets:
    def __init__(self):
        self._stopwords = set(stopwords.words('english') + list(punctuation) + ['AT_USER','URL'])

    def processTweets(self, list_of_tweets):
        processedTweets=[]
        for tweet in list_of_tweets:
            processedTweets.append((self._processTweet(tweet["Text"])))
        return processedTweets

    def _processTweet(self, tweet):
        tweet = tweet.lower() # convert text to lower-case
        tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))', 'URL', tweet) # remove URLs
        tweet = re.sub('@[^\s]+', 'AT_USER', tweet) # remove usernames
        tweet = re.sub(r'#([^\s]+)', r'\1', tweet) # remove the # in #hashtag
        tweet = word_tokenize(tweet) # remove repeated characters (helloooooooo into hello)
        return [word for word in tweet if word not in self._stopwords]

And when I want to use it:

preprocessedTestSet = tweetProcessor.processTweets(tweet)

I received this output

TypeError: string indices must be integers

What is wrong? How can I fix it?

Body:
Assuming tweet is a string. You should pass it as is. You've used tweet["Text"] which is an illegal operation on a string since the index must be an integer.

def processTweets(self, list_of_tweets):
    processedTweets=[]
    for tweet in list_of_tweets:
        processedTweets.append(self._processTweet(tweet))
    return processedTweets

Or more Pythonic:

def processTweets(self, list_of_tweets):
    return [self._processTweet(tweet) for tweet in list_of_tweets]

Notes:

You probably forgot to use raw strings (r"") in some of your regex.


来源: stackexchange

问:
Change the node names in an XML file using C#
I have a huge bunch of XML files with the following structure:

```<code><Stuff1>
  <Content>someContent</name>
  <type>someType</type>
</Stuff1>
<Stuff2>
  <Content>someContent</name>
  <type>someType</type>
</Stuff2>
<Stuff3>
  <Content>someContent</name>
  <type>someType</type>
</Stuff3>
...
...
</code>```

I need to change the each of the "Content" node names to StuffxContent; basically prepend the parent node name to the content node's name.

I planned to use the XMLDocument class and figure out a way, but thought I would ask if there were any better ways to do this.

答:
I used this method to rename the node:</p>

```<code>/// <summary>
/// Rename Node
/// </summary>
/// <param name="parentnode"></param>
/// <param name="oldname"></param>
/// <param name="newname"></param>
private static void RenameNode(XmlNode parentnode, string oldChildName, string newChildName)
{
    var newnode = parentnode.OwnerDocument.CreateNode(XmlNodeType.Element, newChildName, "");
    var oldNode = parentnode.SelectSingleNode(oldChildName);

    foreach (XmlAttribute att in oldNode.Attributes)
        newnode.Attributes.Append(att);
    foreach (XmlNode child in oldNode.ChildNodes)
        newnode.AppendChild(child);

    parentnode.ReplaceChild(newnode, oldNode);
}
</code>```

OwnerDisplayName: sundeep

ContentLicense: CC BY-SA 2.5

Body:
I have a huge bunch of XML files with the following structure:

<Stuff1>
  <Content>someContent</name>
  <type>someType</type>
</Stuff1>
<Stuff2>
  <Content>someContent</name>
  <type>someType</type>
</Stuff2>
<Stuff3>
  <Content>someContent</name>
  <type>someType</type>
</Stuff3>
...
...

I need to change the each of the "Content" node names to StuffxContent; basically prepend the parent node name to the content node's name.

I planned to use the XMLDocument class and figure out a way, but thought I would ask if there were any better ways to do this.

Body:
I used this method to rename the node:

/// <summary>
/// Rename Node
/// </summary>
/// <param name="parentnode"></param>
/// <param name="oldname"></param>
/// <param name="newname"></param>
private static void RenameNode(XmlNode parentnode, string oldChildName, string newChildName)
{
    var newnode = parentnode.OwnerDocument.CreateNode(XmlNodeType.Element, newChildName, "");
    var oldNode = parentnode.SelectSingleNode(oldChildName);

    foreach (XmlAttribute att in oldNode.Attributes)
        newnode.Attributes.Append(att);
    foreach (XmlNode child in oldNode.ChildNodes)
        newnode.AppendChild(child);

    parentnode.ReplaceChild(newnode, oldNode);
}

ContentLicense: CC BY-SA 4.0


问:
Code to Prevent Form repetition based on Name & DOB
I'm a joomla Developer, want a PHP code to avoid user from filling the form more than once. i.e., as he/she enters the name & DOB, if there is already a record in DB of same name & DOB an automatic message should be generated preventing the user from filling the form twice</p>

答:
If you mean that the user is not logged in, then starts entering the form data, then the only way to accomplish what you want is to use AJAX to validate the name and DOB as soon as they are entered. There is a registration extension that has AJAX validation that you could probably modify to suit your needs.

http://extensions.joomla.org/extensions/access-a-security/authentication/7361

ContentLicense: CC BY-SA 3.0


问:
How to capture data within dataframe when using st_rasterize?
I have a polygon:

```<code>p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
</code>```

I create a simple feature polygon object:

```<code>library(sf)
poly_sfc <- st_sfc(st_polygon(p1))
</code>```

and now add a simple dataframe to it:

```<code>data <- data.frame(name = "Los Angeles", language = "English", weather ="sunny")
df <- st_sf(data, geometry = poly_sfc)
</code>```

I can see that it's added the data to the overall sfc.

```<code>Simple feature collection with 1 feature and 3 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: -180 ymin: -60 xmax: 10 ymax: 55
epsg (SRID):    NA
proj4string:    NA
         name language weather                       geometry
1 Los Angeles  English   sunny POLYGON ((-180 -20, -140 55...
</code>```

Now I'd like to rasterise this, which I can using:

```<code>library(star)
r <- st_rasterize(df, options = "ALL_TOUCHED=TRUE")
</code>```

However, when I look at the raster r the data from df has been dropped.

```<code>stars object with 2 dimensions and 1 attribute
attribute(s):
      ID
 Min.   :1
 1st Qu.:1
 Median :1
 Mean   :1
 3rd Qu.:1
 Max.   :1
 NA's   :34597
dimension(s):
  from  to offset     delta refsys point values
x    1 328   -180  0.580682     NA    NA   NULL [x]
y    1 199     55 -0.580682     NA    NA   NULL [y]
</code>```

How can I make sure that the data from df is passed into the raster? Is there a way to do it via st_rasterize ??

答:
so you start with df made. So to make a raster:

```<code>library(raster)
r <- raster(ncol = 180, nrow = 180) # create a base of the raster
extent(r) <- extent(df) # extent the raster to your df
rp <- rasterize(df, r)
</code>```

And this is the result

Body:
I have a polygon:

p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)

I create a simple feature polygon object:

library(sf)
poly_sfc <- st_sfc(st_polygon(p1))

and now add a simple dataframe to it:

data <- data.frame(name = "Los Angeles", language = "English", weather ="sunny")
df <- st_sf(data, geometry = poly_sfc)

I can see that it's added the data to the overall sfc.

Simple feature collection with 1 feature and 3 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: -180 ymin: -60 xmax: 10 ymax: 55
epsg (SRID):    NA
proj4string:    NA
         name language weather                       geometry
1 Los Angeles  English   sunny POLYGON ((-180 -20, -140 55...

Now I'd like to rasterise this, which I can using:

library(star)
r <- st_rasterize(df, options = "ALL_TOUCHED=TRUE")

However, when I look at the raster r the data from df has been dropped.

stars object with 2 dimensions and 1 attribute
attribute(s):
      ID
 Min.   :1
 1st Qu.:1
 Median :1
 Mean   :1
 3rd Qu.:1
 Max.   :1
 NA's   :34597
dimension(s):
  from  to offset     delta refsys point values
x    1 328   -180  0.580682     NA    NA   NULL [x]
y    1 199     55 -0.580682     NA    NA   NULL [y]

How can I make sure that the data from df is passed into the raster? Is there a way to do it via st_rasterize ??

Body:
so you start with df made. So to make a raster:

library(raster)
r <- raster(ncol = 180, nrow = 180) # create a base of the raster
extent(r) <- extent(df) # extent the raster to your df
rp <- rasterize(df, r)

And this is the result


问:
Do optional dependencies get enabled by default?
If I define a dependency like foo = { version = "1.0.0", optional = true },
will it be available when I do "cargo run"? Can I check if it is enabled in the code?

```<code>if cfg!(feature = "foo") {}
</code>```

Doesn't seem to be working, like the feature is missing all the time.

答:
Moving answer to 60258216 here:

Optional dependencies do double as features: https://stackoverflow.com/a/39759592/8182118

They will not be enabled by default unless they're listed in the default feature, though you can enable the feature using cargo run --features foo.

For clarity and forward compatibility you may want to create an actual feature which enables the dependency though, that way if you need to "fluff up" the feature in the future and that requires new optional dependencies it's much easier.

In the code, both #[cfg] and cfg! should work depending whether you want to check for it at compile-time or runtime.

It's not hard to test either:

```<code>[package]
name = "testx"
version = "0.1.0"
edition = "2018"

[features]
default = ["boolinator"]
magic = ["boolinator"]
empty = []

[dependencies]
boolinator = { version = "*", optional = true }
</code>```

and a main.rs of:

fn main() {
    # macro and attributes would work the same here
    if cfg!(feature = "boolinator") {
        println!("Hello, bool!");
    } else {
        println!("Hello, world!");
    }
}
```

<p>you get</p>

<pre class="lang-sh prettyprint-override"><code>$ cargo run -q
Hello, bool!
$ cargo run -q --no-default-features
Hello, world!
$ cargo run -q --no-default-features --features boolinator
Hello, bool!
$ cargo run -q --no-default-features --features magic
Hello, bool!
$ cargo run -q --no-default-features --features empty
Hello, world!
</code>```

See also https://github.com/rust-lang/edition-guide/issues/96

Body:
If I define a dependency like foo = { version = "1.0.0", optional = true },
will it be available when I do "cargo run"? Can I check if it is enabled in the code?

if cfg!(feature = "foo") {}

Doesn't seem to be working, like the feature is missing all the time.

Body:
Moving answer to 60258216 here:

Optional dependencies do double as features: https://stackoverflow.com/a/39759592/8182118

They will not be enabled by default unless they're listed in the default feature, though you can enable the feature using cargo run --features foo.

For clarity and forward compatibility you may want to create an actual feature which enables the dependency though, that way if you need to "fluff up" the feature in the future and that requires new optional dependencies it's much easier.

In the code, both #[cfg] and cfg! should work depending whether you want to check for it at compile-time or runtime.

It's not hard to test either:

[package]
name = "testx"
version = "0.1.0"
edition = "2018"

[features]
default = ["boolinator"]
magic = ["boolinator"]
empty = []

[dependencies]
boolinator = { version = "*", optional = true }

and a main.rs of:

fn main() {
    # macro and attributes would work the same here
    if cfg!(feature = "boolinator") {
        println!("Hello, bool!");
    } else {
        println!("Hello, world!");
    }
}

you get

$ cargo run -q
Hello, bool!
$ cargo run -q --no-default-features
Hello, world!
$ cargo run -q --no-default-features --features boolinator
Hello, bool!
$ cargo run -q --no-default-features --features magic
Hello, bool!
$ cargo run -q --no-default-features --features empty
Hello, world!

See also https://github.com/rust-lang/edition-guide/issues/96


问:
Is there a way to run parallel cucumber tests providing different users to each process
Problem to solve: We want to be able to run multiple ruby cucumber tests in parallel with different users. Since we have user collision in the app, we are not able to use the same user simultaneously.
We tried looking into parallel_test gem to use parallel_cucumber but did not find any way to pass a different user for each process. One option I read online was to have user info in the DB and make a call to get a free user before each test. This was not feasible for us.

Does anyone know any way to make parallel_cucumber or any other ruby gem work to run parallel cucumber tests with a different user for each process

答: If you are running parallel tests you should be able to use a separate db for each stream. This should avoid the issue of user collisions.</p>


问:
apache beam python and airflow reading from GCS results in TypeError("__init__() got an unexpected keyword argument \'response_encoding\'"
accessing a GCS bucket from Google Cloud Composer results in a type error:

```<code>DEBUG:apache_beam.io.filesystem:Listing files in 'gs://BUCKET_NAME/FILENAME.2019-01-20'
DEBUG:apache_beam.io.filesystem:translate_pattern: 'gs://BUCKET_NAME/FILENAME.2019-01-20*' -> 'gs\\:\\/\\/BUCKET_NAME\\/FILENAME\\.2019\\-01\\-20[^/\\\\]*'
DEBUG:root:Connecting using Google Application Default Credentials.
File "/usr/local/lib/python2.7/site-packages/apache_beam/io/textio.py", line 524, in __init__
INFO - skip_header_lines=skip_header_lines)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/textio.py", line 119, in __init__
INFO - validate=validate)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filebasedsource.py", line 121, in __init__
INFO - self._validate()
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/options/value_provider.py", line 137, in _f
INFO - return fnc(self, *args, **kwargs)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filebasedsource.py", line 178, in _validate
INFO - match_result = FileSystems.match([pattern], limits=[1])[0]
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filesystems.py", line 187, in match
INFO - return filesystem.match(patterns, limits)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filesystem.py", line 705, in match
raise BeamIOError("Match operation failed", exceptions)
apache_beam.io.filesystem.BeamIOError: Match operation failed with exceptions {'gs://BUCKET_NAME/FILENAME.2019-01-20*': BeamIOError('List operation failed with exceptions {\'gs://BUCKET_NAME/FILENAME..2019-01-20\': TypeError("__init__() got an unexpected keyword argument \'response_encoding\'",)}',)}
Command exited with return code 1
</code>```

The bucket is located in a different gcp project and composer is running using a standard service account with right as compute-engine editor, which also has "storage object viewer" rights in the bucket.
I do not have any idea, how this error can be fixed, or if it even is an access right problem. Maybe someone can help out or point me into the right direction?

Thanks

答:
If you are facing this issue with Google Cloud Composer then go to Cloud Composer Environment. And follow the below steps

Step1: Open respective Cloud Composer Environment.

Step2: Click on your respective Composer Name.

Step3: Go to "PYPI PACKAGES" tab and click on "EDIT" button.

Step4: In "Package name" side type "apache-beam" and In "Extras and version" type "[gcp]==2.9.0"

Step5: Click on "SAVE" button.

After this, it will take some time to update your composer configuration.
When Composer is ready you can restart your dataflow task.

For more details, please refer below screenshot,

Body:
accessing a GCS bucket from Google Cloud Composer results in a type error:

DEBUG:apache_beam.io.filesystem:Listing files in 'gs://BUCKET_NAME/FILENAME.2019-01-20'
DEBUG:apache_beam.io.filesystem:translate_pattern: 'gs://BUCKET_NAME/FILENAME.2019-01-20*' -> 'gs\\:\\/\\/BUCKET_NAME\\/FILENAME\\.2019\\-01\\-20[^/\\\\]*'
DEBUG:root:Connecting using Google Application Default Credentials.
File "/usr/local/lib/python2.7/site-packages/apache_beam/io/textio.py", line 524, in __init__
INFO - skip_header_lines=skip_header_lines)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/textio.py", line 119, in __init__
INFO - validate=validate)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filebasedsource.py", line 121, in __init__
INFO - self._validate()
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/options/value_provider.py", line 137, in _f
INFO - return fnc(self, *args, **kwargs)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filebasedsource.py", line 178, in _validate
INFO - match_result = FileSystems.match([pattern], limits=[1])[0]
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filesystems.py", line 187, in match
INFO - return filesystem.match(patterns, limits)
INFO - File "/usr/local/lib/python2.7/site-packages/apache_beam/io/filesystem.py", line 705, in match
raise BeamIOError("Match operation failed", exceptions)
apache_beam.io.filesystem.BeamIOError: Match operation failed with exceptions {'gs://BUCKET_NAME/FILENAME.2019-01-20*': BeamIOError('List operation failed with exceptions {\'gs://BUCKET_NAME/FILENAME..2019-01-20\': TypeError("__init__() got an unexpected keyword argument \'response_encoding\'",)}',)}
Command exited with return code 1

The bucket is located in a different gcp project and composer is running using a standard service account with right as compute-engine editor, which also has "storage object viewer" rights in the bucket.
I do not have any idea, how this error can be fixed, or if it even is an access right problem. Maybe someone can help out or point me into the right direction?

Thanks


问:
How do i differentiate different subclasses in a array of the superclass?
My setup is the following.
I have a superclass called "bottles" and 2 different subclasses, "water" and "soda". There's an array filled with countless of both of these and my goal is to write a method that returns the total liter values of only one of these subclasses. What would be the best way to accomplish that? As far as i understand 'instanceof' has no use here.

To clarify i only want to know what operator/method is used to compare:

```<code>if (bottles[0]==soda){
      ...
}
</code>```

答:
IIRC, instanceof still works. </p>

<p>However, how about you put the logic of your counting-liter-criteria in your subclass method? So that, if you want to count the liter of sweet drink in your bottles, your water should return 0 but your soda should return real liter. Since the subclasses know the best of itself, it is better you let them give you the answer directly. Don’t break encapsulation. </p>

Body:
My setup is the following.
I have a superclass called "bottles" and 2 different subclasses, "water" and "soda". There's an array filled with countless of both of these and my goal is to write a method that returns the total liter values of only one of these subclasses. What would be the best way to accomplish that? As far as i understand 'instanceof' has no use here.

To clarify i only want to know what operator/method is used to compare:

if (bottles[0]==soda){
      ...
}

Body:
IIRC, instanceof still works.

However, how about you put the logic of your counting-liter-criteria in your subclass method? So that, if you want to count the liter of sweet drink in your bottles, your water should return 0 but your soda should return real liter. Since the subclasses know the best of itself, it is better you let them give you the answer directly. Don’t break encapsulation.


问:
Typescript: Mapped type to make every property readonly except chosen properties
I ran into a challenge where I didn't want to keep rewriting multiple interfaces.

I need one interface to be fully writable, and also have a "copy" of that interface where all fields are readonly except those that I select to be writeable.

Typescript has mapped types which may allow this.

答:
We can achieve that by using some utility types or mapped types directly. Consider following:

```<code>type MakeSomePropsReadonly<A, K extends keyof A> = Readonly<Pick<A, K>> & Omit<A, K>

type Original = {
    a: string,
    b: number,
    c: boolean
}
type Example = MakeSomePropsReadonly<Original, 'a'>
const example: Example  = {
    a: 'a',
    b: 1,
    c: true
}

example.a = 'b'; // error a property is readonly
example.b = 2; // ok it is not readonly
</code>```

What our type Readonly<Pick> & Omit does is :

Readonly<Pick> - creates a type which has only keys picked by K and all all readonly. In result we get only part of the type which has only these keys we pick

& Omit we intersect the previous mapped typed with only readonly properties with the second part, so Omit will create object which will have all fields which have different key then K

So we create a type by joining one type with all readonly properties with another with writable ones.

We can also do it another way around, so we have readonly interface as you describe and pick which fields are writable:

```<code>type MakeSomePropsWritable<A, K extends keyof A> = {
    -readonly [Key in K]: A[Key]
} & Omit<A, K>

type Original = {
    readonly a: string,
    readonly b: number,
    readonly c: boolean
}
type Example = MakeSomePropsWritable<Original, 'a'>
const example: Example  = {
    a: 'a',
    b: 1,
    c: true
}

example.a = 'b'; // this is now ok as we left it writable
example.b = 2; // this is an error as expected
</code>```

Nothing different in this implementation except of:

-readonly [Key in K]: A[Key] - we say we remove readonly from those fields by - prefix

Body:
We can achieve that by using some utility types or mapped types directly. Consider following:

type MakeSomePropsReadonly<A, K extends keyof A> = Readonly<Pick<A, K>> & Omit<A, K>

type Original = {
    a: string,
    b: number,
    c: boolean
}
type Example = MakeSomePropsReadonly<Original, 'a'>
const example: Example  = {
    a: 'a',
    b: 1,
    c: true
}

example.a = 'b'; // error a property is readonly
example.b = 2; // ok it is not readonly

What our type Readonly<Pick<A, K>> & Omit<A, K> does is :

Readonly<Pick<A, K>> - creates a type which has only keys picked by K and all all readonly. In result we get only part of the type which has only these keys we pick

& Omit<A, K> we intersect the previous mapped typed with only readonly properties with the second part, so Omit<A, K> will create object which will have all fields which have different key then K

So we create a type by joining one type with all readonly properties with another with writable ones.

We can also do it another way around, so we have readonly interface as you describe and pick which fields are writable:

type MakeSomePropsWritable<A, K extends keyof A> = {
    -readonly [Key in K]: A[Key]
} & Omit<A, K>

type Original = {
    readonly a: string,
    readonly b: number,
    readonly c: boolean
}
type Example = MakeSomePropsWritable<Original, 'a'>
const example: Example  = {
    a: 'a',
    b: 1,
    c: true
}

example.a = 'b'; // this is now ok as we left it writable
example.b = 2; // this is an error as expected

Nothing different in this implementation except of:

-readonly [Key in K]: A[Key] - we say we remove readonly from those fields by - prefix


问:
MySQL SELECT IFNULL then compare it numerically with other column
I've tried numerous methods to translate NULL to the number 0 upon selection:

```<code>SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)
</code>```

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

```<code>CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

then f_salary

```<code>CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )
</code>```

hope this helps those who needs to understand the table structure

答:
the selection didn't even list those with NULL values

because you have a LEFT JOIN that is turned to an INNER JOIN by the WHERE clause.

Move the condition to the ON clause.

Also in the left joined query you select the column staff_id although it is not included in the GROUP BY clause as it should.

Change to this:

```<code>SELECT ss.id AS staff_id, u.realname AS realname, ss.amount AS salary_amount,
COALESCE(s.paid_amount, 0) AS paid_amount,
ss.amount - COALESCE(s.paid_amount, 0)
FROM f_salary_staff ss
INNER JOIN user u ON (u.id=ss.user_id)
LEFT JOIN (
  SELECT staff_id, ref_date, SUM(amount) AS paid_amount
  FROM f_salary
  WHERE month_year='2020-02-29'
  GROUP BY staff_id, ref_date
) s ON (ss.id=s.staff_id) AND s.paid_amount > ss.amount
</code>```

Body:
I've tried numerous methods to translate NULL to the number 0 upon selection:

SELECT
  ss.id AS staff_id,
  u.realname AS realname,
  ss.amount AS salary_amount,
  IF(s.paid_amount IS NOT NULL, s.paid_amount,0.00) AS paid_amount,
  (ss.amount-s.paid_amount)
FROM f_salary_staff ss
  JOIN user u ON (u.id=ss.user_id)
  LEFT JOIN (
    SELECT staff_id,
      month_year,
      SUM(amount) AS paid_amount
    FROM f_salary
    WHERE month_year='2020-02-29'
    GROUP BY staff_id,month_year
  ) s ON (ss.id=s.staff_id)

I've used IFNULL but that doesn't turn the 0 into any numeric at all hence the selection didn't even list those with NULL values. Is there a way at all to turn NULL values into numerical upon selection and compare it against other columns numerically?

BTW .. down here is the create table statements for both tables.

f_salary_staff

CREATE TABLE `f_salary_staff` (  `id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL,  `user_id` int(11) NOT NULL,  `date_enter` date DEFAULT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `last_activated` datetime DEFAULT NULL,  `last_inactivated` datetime DEFAULT NULL,  `status` varchar(16) DEFAULT NULL,  PRIMARY KEY (`id`), KEY `store_id` (`store_id`),  KEY `user_id` (`user_id`),  CONSTRAINT `f_salary_staff_ibfk_1` FOREIGN KEY (`store_id`) REFERENCES `store` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,  CONSTRAINT `f_salary_staff_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

then f_salary

CREATE TABLE `f_salary` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `staff_id` int(11) NOT NULL,  `amount` decimal(12,2) DEFAULT NULL,  `note` tinytext,  `ref_date` date DEFAULT NULL,  `month_year` date DEFAULT NULL,  `created` datetime DEFAULT NULL,  `created_by` int(11) DEFAULT NULL,  `updated` datetime DEFAULT NULL,  `updated_by` int(11) DEFAULT NULL,  `approved` datetime DEFAULT NULL,  `approved_by` int(11) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `staff_id` (`staff_id`),  CONSTRAINT `f_salary_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `f_salary_staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE )

hope this helps those who needs to understand the table structure

Body:
the selection didn't even list those with NULL values

because you have a LEFT JOIN that is turned to an INNER JOIN by the WHERE clause.

Move the condition to the ON clause.

Also in the left joined query you select the column staff_id although it is not included in the GROUP BY clause as it should.

Change to this:

SELECT ss.id AS staff_id, u.realname AS realname, ss.amount AS salary_amount,
COALESCE(s.paid_amount, 0) AS paid_amount,
ss.amount - COALESCE(s.paid_amount, 0)
FROM f_salary_staff ss
INNER JOIN user u ON (u.id=ss.user_id)
LEFT JOIN (
  SELECT staff_id, ref_date, SUM(amount) AS paid_amount
  FROM f_salary
  WHERE month_year='2020-02-29'
  GROUP BY staff_id, ref_date
) s ON (ss.id=s.staff_id) AND s.paid_amount > ss.amount


问:
Using () (and other zero-sized types) in FFI
What's the equivalent of () (or any other zero-sized type) when doing FFI in Rust? Specifically, I'm curious what the most reasonable equivalent of () as a function argument when writing an extern "C" function.

My understanding is that zero-sized types are not valid in C, but Rust seems to allow them in extern "C" functions, for example:

#[no_mangle]
pub extern "C" fn test_ffi(input: ()) -> () {
}
```

In this case, returning () is the same as declaring a void function in C#. However, it's not clear to me how you would declare the input argument when generating the binding from C. I was under the impression that ZSTs aren't representable in C, and so shouldn't be FFI-safe. It seems like the nomicon confirms this, saying:

And to avoid warning around using () in FFI, we instead use an empty array ([u8; 0]), which works just as well as an empty type but is FFI-compatible.

Which seems to imply that () isn't FFI-compatible, but that [u8; 0] is (even though I'd expect it to also be zero-size)?

答:
Void has overloaded meaning in C/C++. It can mean a function takes no arguments or returns nothing, or it can be a void*, a pointer to some data but without saying what that data is.

For the former case, for functions that return nothing or take no arguments, just omit them in your function description. A function that returns nothing is technically returning (), but it doesn't need to be explicitly written. The unit type serves the same purpose as void in this case even though unit is something rather than nothing.

For the latter case of void*, the winapi-rs crate defines a c_void to be an empty enum and then uses mut *c_void or const *c_void as the type for arguments and structs which use a void pointer.

Body:
What's the equivalent of () (or any other zero-sized type) when doing FFI in Rust? Specifically, I'm curious what the most reasonable equivalent of () as a function argument when writing an extern "C" function.

My understanding is that zero-sized types are not valid in C, but Rust seems to allow them in extern "C" functions, for example:

#[no_mangle]
pub extern "C" fn test_ffi(input: ()) -> () {
}

In this case, returning () is the same as declaring a void function in C#. However, it's not clear to me how you would declare the input argument when generating the binding from C. I was under the impression that ZSTs aren't representable in C, and so shouldn't be FFI-safe. It seems like the nomicon confirms this, saying:

And to avoid warning around using () in FFI, we instead use an empty array ([u8; 0]), which works just as well as an empty type but is FFI-compatible.

Which seems to imply that () isn't FFI-compatible, but that [u8; 0] is (even though I'd expect it to also be zero-size)?


问:
How to Swap a Table from Vertical to horizontal in javascript?
What I want is exactly the same attributes but in horizontal view instead of vertical one.

Here I am just providing few json objects to add inside the table, just to see if it will be possible or not. In actual code, I have over 100 json objects for the table.

I tried the Swap method for this issue but I don't know how to use the swap method for Json objects.

My code for vertical table is given below:

var attributes = [{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]

var key = [];

document.write("

");
for (key in attributes[0]) {
  document.write('' + '' + key + '' + '	');
}
document.write("
");
for (var i = 0; i < attributes.length; i++) {
  document.write('
');
  for (key in attributes[i]) {
    document.write('' + attributes[i][key] + '	');
  }
  document.write('
');
}
document.write("
");```

答:
That can be achieved by playing with display: flex in the css code:

var attributes = [{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]

var key = [];

document.write("

");
for (key in attributes[0]) {
  document.write('' + '' + key + '' + '	');
}
document.write("
");
for (var i = 0; i < attributes.length; i++) {
  document.write('
');
  for (key in attributes[i]) {
    document.write('' + attributes[i][key] + '	');
  }
  document.write('
');
}
document.write("
");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
tbody {
  display: flex;
  width: 800px;
  position: relative;
  align-items: stretch;
  border: 1px solid black;

}
tr {
  flex-basis: 33.33333333%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  padding: 5px 10px;
}
tr + tr {
  border-left: 1px solid black;
}
th, td {
  flex-basis: 100%;
  text-align: left;
  display: flex;
  padding: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
th {
  font-weight: bold;
}</code>```

Body:
That can be achieved by playing with display: flex in the css code:

var attributes = [{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]

var key = [];

document.write("<table border==\"1\"><tr>");
for (key in attributes[0]) {
  document.write('<td>' + '<b>' + key + '</b>' + '</td>');
}
document.write("</tr>");
for (var i = 0; i < attributes.length; i++) {
  document.write('<tr>');
  for (key in attributes[i]) {
    document.write('<td>' + attributes[i][key] + '</td>');
  }
  document.write('</tr>');
}
document.write("</table>");

table {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
tbody {
  display: flex;
  width: 800px;
  position: relative;
  align-items: stretch;
  border: 1px solid black;

}
tr {
  flex-basis: 33.33333333%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  padding: 5px 10px;
}
tr + tr {
  border-left: 1px solid black;
}
th, td {
  flex-basis: 100%;
  text-align: left;
  display: flex;
  padding: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
th {
  font-weight: bold;
}


问:
Create a JSON list from database entity framework
So I looked around but can't seem to find quite what I'm looking for.

I want to fetch a list of all my users in the database.
I know that I can create a new User object, but I want the object to be created from the database, and return in a JSON format. I'm using entityframework.

```<code>    TimeFlowDbContext db = new TimeFlowDbContext();

    private List<User> _users = new List<User>
    {
        new User {
            UserId = 1,
            Firstname = "Test",
            Lastname = "Man",
            Username = "test",
            Password = "test"
        }
    };
</code>```

I've tried a lot of different things, but I don't really understand how to list them from my database and return JSON..

Thanks in advance if anyone can link me some documentations or explain the right answer.

答:
Something like this should do the trick (using newtonsoft)</p>

```<code>var users = db.users.select(a => new { a.UserId, a.Firstname, a.Lastname, a.Username });
var json = JsonConvert.SerializeObject(users);
</code>```

Body:
So I looked around but can't seem to find quite what I'm looking for.

I want to fetch a list of all my users in the database.
I know that I can create a new User object, but I want the object to be created from the database, and return in a JSON format. I'm using entityframework.

    TimeFlowDbContext db = new TimeFlowDbContext();

    private List<User> _users = new List<User>
    {
        new User {
            UserId = 1,
            Firstname = "Test",
            Lastname = "Man",
            Username = "test",
            Password = "test"
        }
    };

I've tried a lot of different things, but I don't really understand how to list them from my database and return JSON..

Thanks in advance if anyone can link me some documentations or explain the right answer.

Body:
Something like this should do the trick (using newtonsoft)

var users = db.users.select(a => new { a.UserId, a.Firstname, a.Lastname, a.Username });
var json = JsonConvert.SerializeObject(users);


问:
Regex to split camel case
I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):

"MyCamelCaseString"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); })
```

<p>Thus that returns:</p>

<pre class="lang-js prettyprint-override"><code>"My Camel Case String"
</code>```

Which is good. However, I want to step this up a notch. Could someone help me with a regex which will split if, and only if, the former character is lower-case and the latter is upper-case.

Thus, the above example will be the result I expect, but if I do:

"ExampleID"
```

<p>Then I get returned:</p>

<pre class="lang-js prettyprint-override"><code>"Example ID"
</code>```

Instead of

"Example I D"
```

Since it's splitting at each upper-case and ignoring anything before it.

Hope that makes sense! And thanks :).

答:
You can use a combination of regEx, replace, and trim.

```<code>"ABCMyCamelCaseSTR".replace(/([A-Z][a-z0-9]+)/g, ' $1 ')
                   .replace(/\s{2}/g," ").trim()

// ABC My Camel Case STR
</code>```

Title: Regex to split camel case

Body:
I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here):

"MyCamelCaseString"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); })

Thus that returns:

"My Camel Case String"

Which is good. However, I want to step this up a notch. Could someone help me with a regex which will split if, and only if, the former character is lower-case and the latter is upper-case.

Thus, the above example will be the result I expect, but if I do:

"ExampleID"

Then I get returned:

"Example ID"

Instead of

"Example I D"

Since it's splitting at each upper-case and ignoring anything before it.

Hope that makes sense! And thanks :).

Body:
You can use a combination of regEx, replace, and trim.

"ABCMyCamelCaseSTR".replace(/([A-Z][a-z0-9]+)/g, ' $1 ')
                   .replace(/\s{2}/g," ").trim()

// ABC My Camel Case STR


问:
Grouping recursive cycle by common person
I am quite new to PL/SQL and I am struggling with quest that I get.

I have Legal and Natural entities. Each legal entity can have some natural entities and these natural entities can be tied to 1 or more entities.

Company A have disponent #1 and #2 and #3

Company B have disponent #2 and #4

Company C have disponent #4

Company D have disponent #5

Company E have disponent #6

Company F have disponent #6

The result should show which companies are tied through some disponent together. In real the relations are more "deep" and complicated.
On my example the result should be something like this:

Company A - Group 1

Company B - Group 1

Company C - Group 1

Company D - Group 2

Company E - Group 3

Company F - Group 3

Example table in excel:

I made 3 tables:

SNAPSHOT_FO - contains FO_CLUID (ID of natural entity)

SNAPSHOT_VAZBA - contains PO_cluid (ID of legal entity) and FO_cluid. This is the relations table.

ODLITE - contains FO_CLUID (ID of natural entity) and KOD (group ID) - empty at the beginning. Should be the final table which I can then join to PO_cluid and get the result.

CREATE GLOBAL TEMPORARY TABLE tbl_temp
(
   F_CL VARCHAR2(255) NULL,
   par NUMBER(5) NULL
)
ON COMMIT PRESERVE ROWS;

DECLARE
  party NUMBER := 1;
  r NUMBER := 1;

BEGIN
FOR CLUID IN (select FO_CLUID from snapshot_fo  WHERE ROWNUM =1)
LOOP
INSERT INTO tbl_temp (F_CL,par) VALUES (CLUID,party);

        WHILE  ( r> 0 )
        BEGIN

            MERGE INTO tbl_temp tg
            USING  ((SELECT distinct FO_CLUID from snapshot_vazba where PO_CLUID in (
                                                        SELECT distinct PO_CLUID
                                                        from snapshot_vazba
                                                        where FO_CLUID in (select f_cl from tbl_temp where kod=party)
                                                    ))
            ) src
                on (tg.FO_cluid =src.FO_cluid)
            WHEN NOT MATCHED THEN
                INSERT (F_CL, par)
                VALUES (src.FO_CLUID, party)
        SET r = SQL%ROWCOUNT
        END;
        INSERT INTO odlite (FO_CLUID, KOD) VALUES (tbl_temp.cluid,tbl_temp.party);
        delete from snapshot_fo where fo_cluid in (select fo_cluid from odlite);
        truncate table tbl_temp;
        party := party + 1;
        r := 1;
    END Loop;
end ;
/
```

Then I will just join the table odlite ON FO_cluid to my PO_cluid table.
But the code doesn't work at the moment... and I don't know any other way how to do it.
If there is any easier way how to do it, please let me know :)

PS: I am not allowed to make temporary table in declare part because of restrictions in our company.

Thanks in advance!

ORACLE SQL DEVELOPER  Version 19.2.1.247

答:
```<code>declare
  v_cluid varchar2(30 char);
  v_party integer;
  change_num integer;

  function get_party return integer is
    grp integer;
  begin
    select
      nvl(max(kod),0)
    into
      grp
    from
      snapshot_vazba;

    return grp;
  end;

  function get_cluid return varchar2 is
    v_cluid varchar2(30 char);
  begin
    select
      nvl(max(fo_cluid), 'XNA')
    into
      v_cluid
    from
      (
        select
          fo_cluid,
          row_number() over (partition by 1 order by count_f desc) as rn
        from
          (
            select count(1) as count_f, fo_cluid from snapshot_vazba where kod is null group by fo_cluid
          )
      )
    where
      rn = 1;

    return v_cluid;
  end;
begin
  v_party := get_party + 1;
  v_cluid := get_cluid;

  while (v_cluid <> 'XNA' )
  loop
    update
      snapshot_vazba
    set
      kod = v_party
    where
      po_cluid in (select po_cluid from snapshot_vazba where fo_cluid = v_cluid) and kod is null;

    update
      snapshot_vazba
    set
      kod = v_party
    where
      kod is null and
      fo_cluid in (select fo_cluid from snapshot_vazba where kod = v_party);

    change_num := sql%rowcount;

    while (change_num > 0)
    loop
      update
        snapshot_vazba
      set
        kod = v_party
      where
        po_cluid in (select po_cluid from snapshot_vazba where kod = v_party) and kod is null;

      update
        snapshot_vazba
      set
        kod = v_party
      where
        kod is null and
        fo_cluid in (select fo_cluid from snapshot_vazba where kod = v_party);

      change_num := sql%rowcount;

    end loop;

    commit;

    v_party := v_party + 1;
    v_cluid := get_cluid;
  end loop;
end;
/
</code>```

<p>This works :) </p>

Body:
I am quite new to PL/SQL and I am struggling with quest that I get.

I have Legal and Natural entities. Each legal entity can have some natural entities and these natural entities can be tied to 1 or more entities.

Company A have disponent #1 and #2 and #3

Company B have disponent #2 and #4

Company C have disponent #4

Company D have disponent #5

Company E have disponent #6

Company F have disponent #6

The result should show which companies are tied through some disponent together. In real the relations are more "deep" and complicated.
On my example the result should be something like this:

Company A - Group 1

Company B - Group 1

Company C - Group 1

Company D - Group 2

Company E - Group 3

Company F - Group 3

Example table in excel:

I made 3 tables:

SNAPSHOT_FO - contains FO_CLUID (ID of natural entity)

SNAPSHOT_VAZBA - contains PO_cluid (ID of legal entity) and FO_cluid. This is the relations table.

ODLITE - contains FO_CLUID (ID of natural entity) and KOD (group ID) - empty at the beginning. Should be the final table which I can then join to PO_cluid and get the result.

CREATE GLOBAL TEMPORARY TABLE tbl_temp
(
   F_CL VARCHAR2(255) NULL,
   par NUMBER(5) NULL
)
ON COMMIT PRESERVE ROWS;

DECLARE
  party NUMBER := 1;
  r NUMBER := 1;

BEGIN
FOR CLUID IN (select FO_CLUID from snapshot_fo  WHERE ROWNUM =1)
LOOP
INSERT INTO tbl_temp (F_CL,par) VALUES (CLUID,party);

        WHILE  ( r> 0 )
        BEGIN

            MERGE INTO tbl_temp tg
            USING  ((SELECT distinct FO_CLUID from snapshot_vazba where PO_CLUID in (
                                                        SELECT distinct PO_CLUID
                                                        from snapshot_vazba
                                                        where FO_CLUID in (select f_cl from tbl_temp where kod=party)
                                                    ))
            ) src
                on (tg.FO_cluid =src.FO_cluid)
            WHEN NOT MATCHED THEN
                INSERT (F_CL, par)
                VALUES (src.FO_CLUID, party)
        SET r = SQL%ROWCOUNT
        END;
        INSERT INTO odlite (FO_CLUID, KOD) VALUES (tbl_temp.cluid,tbl_temp.party);
        delete from snapshot_fo where fo_cluid in (select fo_cluid from odlite);
        truncate table tbl_temp;
        party := party + 1;
        r := 1;
    END Loop;
end ;
/

Then I will just join the table odlite ON FO_cluid to my PO_cluid table.
But the code doesn't work at the moment... and I don't know any other way how to do it.
If there is any easier way how to do it, please let me know :)

PS: I am not allowed to make temporary table in declare part because of restrictions in our company.

Thanks in advance!

ORACLE SQL DEVELOPER  Version 19.2.1.247

Body:
declare
  v_cluid varchar2(30 char);
  v_party integer;
  change_num integer;

  function get_party return integer is
    grp integer;
  begin
    select
      nvl(max(kod),0)
    into
      grp
    from
      snapshot_vazba;

    return grp;
  end;

  function get_cluid return varchar2 is
    v_cluid varchar2(30 char);
  begin
    select
      nvl(max(fo_cluid), 'XNA')
    into
      v_cluid
    from
      (
        select
          fo_cluid,
          row_number() over (partition by 1 order by count_f desc) as rn
        from
          (
            select count(1) as count_f, fo_cluid from snapshot_vazba where kod is null group by fo_cluid
          )
      )
    where
      rn = 1;

    return v_cluid;
  end;
begin
  v_party := get_party + 1;
  v_cluid := get_cluid;

  while (v_cluid <> 'XNA' )
  loop
    update
      snapshot_vazba
    set
      kod = v_party
    where
      po_cluid in (select po_cluid from snapshot_vazba where fo_cluid = v_cluid) and kod is null;

    update
      snapshot_vazba
    set
      kod = v_party
    where
      kod is null and
      fo_cluid in (select fo_cluid from snapshot_vazba where kod = v_party);

    change_num := sql%rowcount;

    while (change_num > 0)
    loop
      update
        snapshot_vazba
      set
        kod = v_party
      where
        po_cluid in (select po_cluid from snapshot_vazba where kod = v_party) and kod is null;

      update
        snapshot_vazba
      set
        kod = v_party
      where
        kod is null and
        fo_cluid in (select fo_cluid from snapshot_vazba where kod = v_party);

      change_num := sql%rowcount;

    end loop;

    commit;

    v_party := v_party + 1;
    v_cluid := get_cluid;
  end loop;
end;
/

This works :)


问:
Using EF 6.4 with Core 3.1 (blazor) - does it work?
I have an old solution using EF, and I would like to upgrade my presentation project to core 3.1 in order to use blazor. I would like to keep using EF, so I have upgraded to 6.4.

I did read some news about EF 6.4 being supported in .NET Core, but I'm struggling to make it work.

All my projects are standard 2.1, except my .NET Core 3.1 project. I am able to build the projects, but I'm not able to add the context to startup.

I've tried the following:

```<code>public class MyCustomDbContext : DbContext
{
    public MyCustomDbContext(string connString) : base(connString)
    {
    }

    public DbSet<NewsItem> NewsItems { get; set; }
}
</code>```

Startup:

```<code>services.AddScoped<MyCustomDbContext>(_ => new MyCustomDbContext(Configuration.GetConnectionString("DefaultConnection")));
</code>```

Error:

No DbContext was found in assembly 'Core.Entities'. Ensure that you're
  using the correct assembly and that the type is neither abstract nor
  generic.

答:
You project configuration is all good.

The error you are seeing is caused by trying to (automatically) run migrations om a project that does not have a DbContext.

The startup project runs the migrations, but the DbContext is in another project.

To configure EF to target the project containing the DbContext, add a migration like this:

Add-Migration EmptyMigration -ProjectName "Core.Entities" -StartUpProjectName "Core.Presentation"

Where Core.Entities is the project containing the DbContext, and Core.Presentation is your startup project.

Body:
I have an old solution using EF, and I would like to upgrade my presentation project to core 3.1 in order to use blazor. I would like to keep using EF, so I have upgraded to 6.4.

I did read some news about EF 6.4 being supported in .NET Core, but I'm struggling to make it work.

All my projects are standard 2.1, except my .NET Core 3.1 project. I am able to build the projects, but I'm not able to add the context to startup.

I've tried the following:

public class MyCustomDbContext : DbContext
{
    public MyCustomDbContext(string connString) : base(connString)
    {
    }

    public DbSet<NewsItem> NewsItems { get; set; }
}

Startup:

services.AddScoped<MyCustomDbContext>(_ => new MyCustomDbContext(Configuration.GetConnectionString("DefaultConnection")));

Error:

No DbContext was found in assembly 'Core.Entities'. Ensure that you're
  using the correct assembly and that the type is neither abstract nor
  generic.


问:
Using a sub query in column list
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

```<code>7Days  14Days  28Days
21     35      56
</code>```

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

```<code>select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())
</code>```

答:
```<code>select
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-8, getdate())
) as [7Days],
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-15, getdate())
) as [14Days],
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-29, getdate())
) as [28Days]
</code>```

Title: Using a sub query in column list

Body:
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

7Days  14Days  28Days
21     35      56

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())


问:
Hiding span under div in CSS
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

```<code><div class="blog-stats">
    <span class="clock">
        <i class="fa fa-calendar stats-item"></i>
        <span class="text-center text-light stats-item">February 15, 2020</span>
    </span>
    <span class="comment">
        <i class="fa fa-comment stats-item"></i>
        <span class="text-center text-light stats-item">no comments</span>
    </span>
    <span class="user">
        <i class="fa fa-user stats-item"></i>
        <span class="text-content text-light stats-item">Wayne John</span>
    </span>
</div>
</code>```

I tried a few below and it didn't work.

```<code>.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}
</code>```

Any idea how to fix it?

答:
Please put this code in your css

.blog-stats span.comment{display: none;}```

Title: Hiding span under div in CSS

Body:
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

        February 15, 2020

        no comments

        Wayne John

I tried a few below and it didn't work.

.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}

Any idea how to fix it?


问:
build.gradle.kts unresolved reference: npm
I am trying to learn kotlin and I was following tutorial Building Web Applications with React and Kotlin/JS from official kotlin site, but I have a problem with build.gradle.kts file, it says:

unresolved reference

every time npm appears in this file.

I did everything like in the tutorial and honestly don't know what's a problem here. Do I need to include something else? I have npm installed on my computer so I believe this is another problem.

答: Ok, so the problem was with Intellij. If it shows you that you have up-to-date version of Kotlin and it's not 3.70 then you need to update Intellij, because it's Intellij issue. After updating intellij, kotlin and changing plugin version in build.gradle.kts everything works fine. Maybe this answer will help someone with same issue.</p>


问:
MvvmLight : How to unsubscribe "RaisePropertychanged" Event
I have a problem in my WPF application with MvvmLight.

My application :

I have a MainView with a menu, each MenuItem will open a new view (different for each menuitem).

Each MenuItem is bound to a RelayCommand of my MainViewModel

In my MainViewModel, the RelayCommand just do Messenger.Default.Send(this, "ShowMyView") to the MainView.

In my MainView, I'm registered on the message "ShowMyView" and actions are :

var v = new MyView();
v.Owner = this;
v.ShowDialog();
Messenger.Default.Unregister(v);

This new view (MyView) is bound on a viewmodel (MyViewModel) that contains properties.
Elements of this view (textbox, radiobutton, etc) are bound to these properties.

When I close "MyView", It's disposed and I come back to my mainview but the "MyViewModel" still exist.

Problem :

When I first open "MyView", binding works properly, if "MyViewModel" set a property, the RaisePropertyChanged is called, then the "get" of this property is call once.

But If I open and close my view 20 times, at the 20th times, when a RaisePropertyChanged is called, the get of this property is call 20 times !

Question :

So how can I unsubscribe these "RaisePropertyChanged" when I close a view ?

Hopping it's clear for you, and sorry for my bad english.

EDIT : With code

EDIT BIS

Instead of putting some part of code, please found on my github a complete project where the problem occured.

https://github.com/damgot/MvvmLightProblemExample

When I run the application, the MainWindow start :

You can see in Debug Output :

```<code>Starting
Creating NewViewModel
</code>```

Then, when I click on NewView Menu, the newview open :

And you can see in Debug output :

```<code>Initialize NewViewModel and set MyBool to true
MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
</code>```

Seems Ok as I have 2 radio button bound on "MyBool"

Now if I select the "MyBool is false" Radio button :

and in output :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
</code>```

Still good.

Now, If I close the NewView, and open it again, and select "MyBool is false" Radio button, the output is :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

Then once again, output is  :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

and once again :

```<code>MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
</code>```

And so on...

As You can see, "Get" call on my property, increase each team I re-open the view

答:
I've found another solution, a prettier one than the first solution I've posted.

In my ViewModelLocator, I've removed every viewmodel properties.
And I've create this static function instead :

```<code>public static T GetViewModelInstance<T>(Window w)
{
    var uniqueKey = System.Guid.NewGuid().ToString();
    T VMInstance = ServiceLocator.Current.GetInstance<T>(uniqueKey);
    w.Closed += (sender, args) => SimpleIoc.Default.Unregister(uniqueKey);
    return VMInstance;
}
</code>```

So, as you can see, I do not return the ViewModel but a new instance of it (with the uniqueKey Token).
And I'm registered on the calling view Closed event to unregister the created VM instance.

I no longer define the DataContext in the xaml but xaml.cs, in the constructor, I set the DataContext as follow :

```<code>DataContext = ViewModelLocator.GetViewModelInstance<NewViewModel>(this);
</code>```

And It works pretty well.

Body:
I have a problem in my WPF application with MvvmLight.

My application :

I have a MainView with a menu, each MenuItem will open a new view (different for each menuitem).

Each MenuItem is bound to a RelayCommand of my MainViewModel

In my MainViewModel, the RelayCommand just do Messenger.Default.Send(this, "ShowMyView") to the MainView.

In my MainView, I'm registered on the message "ShowMyView" and actions are :

var v = new MyView();
v.Owner = this;
v.ShowDialog();
Messenger.Default.Unregister(v);

This new view (MyView) is bound on a viewmodel (MyViewModel) that contains properties.
Elements of this view (textbox, radiobutton, etc) are bound to these properties.

When I close "MyView", It's disposed and I come back to my mainview but the "MyViewModel" still exist.

Problem :

When I first open "MyView", binding works properly, if "MyViewModel" set a property, the RaisePropertyChanged is called, then the "get" of this property is call once.

But If I open and close my view 20 times, at the 20th times, when a RaisePropertyChanged is called, the get of this property is call 20 times !

Question :

So how can I unsubscribe these "RaisePropertyChanged" when I close a view ?

Hopping it's clear for you, and sorry for my bad english.

EDIT : With code

EDIT BIS

Instead of putting some part of code, please found on my github a complete project where the problem occured.

https://github.com/damgot/MvvmLightProblemExample

When I run the application, the MainWindow start :

You can see in Debug Output :

Starting
Creating NewViewModel

Then, when I click on NewView Menu, the newview open :

And you can see in Debug output :

Initialize NewViewModel and set MyBool to true
MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call

Seems Ok as I have 2 radio button bound on "MyBool"

Now if I select the "MyBool is false" Radio button :

and in output :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call

Still good.

Now, If I close the NewView, and open it again, and select "MyBool is false" Radio button, the output is :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

Then once again, output is  :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

and once again :

MyBool Set call + RaiseProperty
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call
MyBool Get call

And so on...

As You can see, "Get" call on my property, increase each team I re-open the view

Body:
I've found another solution, a prettier one than the first solution I've posted.

In my ViewModelLocator, I've removed every viewmodel properties.
And I've create this static function instead :

public static T GetViewModelInstance<T>(Window w)
{
    var uniqueKey = System.Guid.NewGuid().ToString();
    T VMInstance = ServiceLocator.Current.GetInstance<T>(uniqueKey);
    w.Closed += (sender, args) => SimpleIoc.Default.Unregister(uniqueKey);
    return VMInstance;
}

So, as you can see, I do not return the ViewModel but a new instance of it (with the uniqueKey Token).
And I'm registered on the calling view Closed event to unregister the created VM instance.

I no longer define the DataContext in the xaml but xaml.cs, in the constructor, I set the DataContext as follow :

DataContext = ViewModelLocator.GetViewModelInstance<NewViewModel>(this);

And It works pretty well.


问:
Unnecessary multiple method call upon displaying angular modal dialog
In my angular (version 9) project I have a component that represents a modal dialog. In the component template there is the following line of code, that is responsible for the dialog title representation.

```<code><p mat-dialog-title>{{ generateDialogTitle() }}</p>
</code>```

In the component typescript file, there is a method generateDialogTitle():string that returns generated dialog title (it depends on the dialog data).

The modal dialog is being called via code and this code is being called once when I click on a button.

```<code>var dialogRef = this.dialog.open(QuestionDetailsComponent, dialogConfig);
dialogRef.afterClosed().subscribe(result => {
  if (result) {
    // if dialog has been accepted
    ... some code here
  }
});
</code>```

What is strange, upon displaying the modal dialog, the method generateDialogTitle() is being called multiple times when it is being used in the component template (it is the only place where it is being used).

It somehow called implicitly multiple times and I don't understand why.

I noticed it in the console upon debugging.

Then I removed binding to generateDialogTitle() method from the template, added new property dialogTitle to the class, and the dialog title looked like that:

```<code><p mat-dialog-title>{{ dialogTitle }}</p>
</code>```

I marked generateDialogTitle() as private method and called it explicitly in the constructor, to assign its value to dialogTitle property.

And in this case it called only once.

I don't understand, why this method when it is used directly in html-template is being called (implicitly) multiple times. Why does it happen? Is it normal behavior?

答:
According to the @ritaj comments, it is the expected Angular behavior.

Angular calls functions called from template on every change detection run.

It is better to use properties instead of methods in your html-templates. Explicitly assign your properties and bind them to the html-template parts.

Body:
In my angular (version 9) project I have a component that represents a modal dialog. In the component template there is the following line of code, that is responsible for the dialog title representation.

{{ generateDialogTitle() }}

In the component typescript file, there is a method generateDialogTitle():string that returns generated dialog title (it depends on the dialog data).

The modal dialog is being called via code and this code is being called once when I click on a button.

var dialogRef = this.dialog.open(QuestionDetailsComponent, dialogConfig);
dialogRef.afterClosed().subscribe(result => {
  if (result) {
    // if dialog has been accepted
    ... some code here
  }
});

What is strange, upon displaying the modal dialog, the method generateDialogTitle() is being called multiple times when it is being used in the component template (it is the only place where it is being used).

It somehow called implicitly multiple times and I don't understand why.

I noticed it in the console upon debugging.

Then I removed binding to generateDialogTitle() method from the template, added new property dialogTitle to the class, and the dialog title looked like that:

{{ dialogTitle }}

I marked generateDialogTitle() as private method and called it explicitly in the constructor, to assign its value to dialogTitle property.

And in this case it called only once.

I don't understand, why this method when it is used directly in html-template is being called (implicitly) multiple times. Why does it happen? Is it normal behavior?


问:
Swift: Auto-Login user with Firebase
I want to auto-login the user if he is already signed and just head to the main view but the code is running twice and you can see the transistion instead of the view just showing. How do I fix it?

AppDelegate.swift

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.slideMenuController
    FIRApp.configure()
    FIRAuth.auth()?.addAuthStateDidChangeListener {
        auth, user in
        if user != nil {
            // User is signed in.
            print("Automatic Sign In: \(user?.email)")

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewControllerWithIdentifier("EmployeeRevealViewController")
            self.window!.rootViewController = initialViewController

        } else {
            // No user is signed in.
        }
    }

    return true
}
</code>```

Log

```<code>2016-06-06 01:00:55.585 Untitled[13009:6258910] Configuring the default app.
2016-06-06 01:00:55.657 Untitled[13009:] <FIRAnalytics/INFO> Firebase Analytics v.3200000 started
2016-06-06 01:00:55.666 Untitled[13009:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2016-06-06 01:00:55.714 Untitled[13009:6258910] Firebase Crash Reporting: Successfully enabled
2016-06-06 01:00:55.739: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-06 01:00:55.739: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-06-06 01:00:55.760: <FIRMessaging/INFO> FIRMessaging library version 1.1.0
2016-06-06 01:00:55.781: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-06 01:00:55.788 Untitled[13009:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
Automatic Sign In: Optional("mohamed.mohd@hotmail.com")
2016-06-06 01:00:56.759: <FIRInstanceID/WARNING> APNS Environment in profile: development
Automatic Sign In: Optional("mohamed.mohd@hotmail.com")
2016-06-06 01:00:57.811 Untitled[13009:] <FIRAnalytics/INFO> Firebase Analytics enabled
</code>```

答:
Use the func "override func viewDidAppear" to instantly log in if user != nil. You also forgot to add "view", use self.view.window

```<code>override func viewDidAppear(_ animated: Bool) {
        if Auth.auth().currentUser != nil {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "homeTabBarVC")
            self.view.window!.rootViewController = initialViewController
        } else { return }
    }
</code>```

Title: Swift: Auto-Login user with Firebase

Body:
I want to auto-login the user if he is already signed and just head to the main view but the code is running twice and you can see the transistion instead of the view just showing. How do I fix it?

AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.slideMenuController
    FIRApp.configure()
    FIRAuth.auth()?.addAuthStateDidChangeListener {
        auth, user in
        if user != nil {
            // User is signed in.
            print("Automatic Sign In: \(user?.email)")

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewControllerWithIdentifier("EmployeeRevealViewController")
            self.window!.rootViewController = initialViewController

        } else {
            // No user is signed in.
        }
    }

    return true
}

Log

2016-06-06 01:00:55.585 Untitled[13009:6258910] Configuring the default app.
2016-06-06 01:00:55.657 Untitled[13009:] <FIRAnalytics/INFO> Firebase Analytics v.3200000 started
2016-06-06 01:00:55.666 Untitled[13009:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2016-06-06 01:00:55.714 Untitled[13009:6258910] Firebase Crash Reporting: Successfully enabled
2016-06-06 01:00:55.739: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-06 01:00:55.739: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-06-06 01:00:55.760: <FIRMessaging/INFO> FIRMessaging library version 1.1.0
2016-06-06 01:00:55.781: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-06 01:00:55.788 Untitled[13009:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
Automatic Sign In: Optional("mohamed.mohd@hotmail.com")
2016-06-06 01:00:56.759: <FIRInstanceID/WARNING> APNS Environment in profile: development
Automatic Sign In: Optional("mohamed.mohd@hotmail.com")
2016-06-06 01:00:57.811 Untitled[13009:] <FIRAnalytics/INFO> Firebase Analytics enabled

Body:
Use the func "override func viewDidAppear" to instantly log in if user != nil. You also forgot to add "view", use self.view.window

override func viewDidAppear(_ animated: Bool) {
        if Auth.auth().currentUser != nil {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "homeTabBarVC")
            self.view.window!.rootViewController = initialViewController
        } else { return }
    }


问:
Is mod_rewrite a valid option for caching dynamic pages with Apache?
I have read about a technique involving writing to disk a rendered dynamic page and using that when it exists using mod_rewrite. I was thinking about cleaning out the cached version every X minutes using a cron job.

I was wondering if this was a viable option or if there were better alternatives that I am not aware of.

(Note that I'm on a shared machine and mod_cache is not an option.)

答: I would use a cache on application level. Because the application knows best when the cached version is out of date and is more flexible and powerful in the matter of cache negotiation.</p>

OwnerDisplayName: Gumbo


问:
Single linked lists C++
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

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

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout << p->data << " ";
        p = p->next;
    }
    cout << p->data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}
</code>```

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

答:
```<code>node::node(int data) {
    data = data;
    next = NULL;
}
</code>```

The line data = data is a problem for you. Rename the parameter to be different from the member. This ought to give you a series of garbage values (not pointers) for the member variable data.

Note: this is one of the reasons for naming convention distinguishing members variables, being it traling or leading _, m_ or wherever the balance is b/w info and aesthetics.

Title: Single linked lists C++

Body:
Hey guys,
I'm studying for a midterm right now and am working on trying to create a simple program using single linked list.  All I want it to do is insert "1", "2", "3", "4" into the list and print it out.  Please take a look at the following code:

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

class node{
public:
    node(int data);
    friend class slist;
private:
    int data;
    node *next;
};

node::node(int data){
    data = data;
    next = NULL;
}

class slist{
public:
    slist(){
        head = NULL;
    }
    void insert(int item);
    void output();

private:
    node* head;
};

void slist::insert(int item){
    node* newnode = new node(item);
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        newnode->next = head;
        head = newnode;
    }
}

void slist::output(){
    node* p = head;
    while (p->next != NULL){
        cout <
data << " ";
        p = p->next;
    }
    cout <
data << " ";
}

int main(){
    slist FINAL;

    FINAL.insert(1);
    FINAL.insert(2);
    FINAL.insert(3);
    FINAL.insert(4);

    FINAL.output();

    return 0;
}

It compiles fine, but it prints out (I'm guessing) pointers instead of the actual numbers.  Can anyone tell me why?

Thanks so much!

Body:
node::node(int data) {
    data = data;
    next = NULL;
}

The line data = data is a problem for you. Rename the parameter to be different from the member. This ought to give you a series of garbage values (not pointers) for the member variable data.

Note: this is one of the reasons for naming convention distinguishing members variables, being it traling or leading _, m_ or wherever the balance is b/w info and aesthetics.


问:
createFile() and DeviceIoControl() equivalent for volume devices in Unix/Linux
I have opened volume USB device and locked using CreateFile() and DeviceIoControl() in Windows.

I want same functionality on Linux/Unix system. I am new to Unix So How to get it?

My code for Windows :

```<code>HANDLE handle = CreateFile(L"\\\\.\\F:",          // F: drive to open
    GENERIC_READ,                // no access to the drive
    FILE_SHARE_READ, // share mode
    NULL,             // default security attributes
    OPEN_EXISTING,    // disposition
    0x1,                // file attributes
    NULL);            // do not copy file attributes

DWORD lpBytesReturned;

if (DeviceIoControl(handle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &lpBytesReturned, (LPOVERLAPPED)NULL)){
        printf("\n  Lock SUCCESS !\n");
    }
else {
    printf("\n  Lock Failed !\n");
}
</code>```

Langage : c/c++

platform: Linux/Unix

Thanks in Advance.

答:
Consider using Linux namespaces, for instance, Docker containers. That way, you can grant or limit access to system resources such as network cards, storage devices, etc.

For example, you have a web server and database server. You can create two containers: one for the webserver, and the second one for the database. Each of the containers has its own filesystem, or to be precise, own view on the filesystem (namespace). Therefore, a security breach on the webserver cannot directly affect databases because they are not seen from the webserver's filesystem. Moreover, both containers have separate user permissions, so the web admin with root access still cannot mess up the databases.

The same way you can prevent access to a USB storage drive: on the host system, you can make backups from all Docker containers to a USB drive while the containers have no access to the backups as the USB storage doesn't exist for them at all.

Body:
I have opened volume USB device and locked using CreateFile() and DeviceIoControl() in Windows.

I want same functionality on Linux/Unix system. I am new to Unix So How to get it?

My code for Windows :

HANDLE handle = CreateFile(L"\\\\.\\F:",          // F: drive to open
    GENERIC_READ,                // no access to the drive
    FILE_SHARE_READ, // share mode
    NULL,             // default security attributes
    OPEN_EXISTING,    // disposition
    0x1,                // file attributes
    NULL);            // do not copy file attributes

DWORD lpBytesReturned;

if (DeviceIoControl(handle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &lpBytesReturned, (LPOVERLAPPED)NULL)){
        printf("\n  Lock SUCCESS !\n");
    }
else {
    printf("\n  Lock Failed !\n");
}

Langage : c/c++

platform: Linux/Unix

Thanks in Advance.


问:
How to resolve deprecated @CucumberOptions?
In the following code i was using @cucumber.options.But it says it is deprecated.

So i am trying to use @cucumberoptions which requires an import of "cucumber.api.CucumberOptions".
But when i checked in my maven dependencies , cucumber.api does not contain cucumberoptions.
And i am getting a red line for my import "import cucumber.api.CucumberOptions;"

My aim is to create a good report and set its path .

I could find a related question - How to resolve the deprecation of format option in @CucumberOptions? here but could not find an answer i am looking for.
I would really appreciate if any of you could find a resolution to this .

My Code is as follows:-

```<code>package featurefiles;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.*;
@RunWith(Cucumber.class)
@CucumberOptions(strict = false, features = "features", format = { "pretty",
    "html:target/site/cucumber-pretty",
    "json:target/cucumber.json" }, tags = { "~@ignore" })
public class CucumberTestRunner {
}
</code>```

答:
Instead of the legacy classes import them from io package:

import cucumber.api.CucumberOptions; >> import io.cucumber.junit.CucumberOptions;
and
import cucumber.api.junit.Cucumber >> import io.cucumber.junit.Cucumber;

Body:
In the following code i was using @cucumber.options.But it says it is deprecated.

So i am trying to use @cucumberoptions which requires an import of "cucumber.api.CucumberOptions".
But when i checked in my maven dependencies , cucumber.api does not contain cucumberoptions.
And i am getting a red line for my import "import cucumber.api.CucumberOptions;"

My aim is to create a good report and set its path .

I could find a related question - How to resolve the deprecation of format option in @CucumberOptions? here but could not find an answer i am looking for.
I would really appreciate if any of you could find a resolution to this .

My Code is as follows:-

package featurefiles;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.*;
@RunWith(Cucumber.class)
@CucumberOptions(strict = false, features = "features", format = { "pretty",
    "html:target/site/cucumber-pretty",
    "json:target/cucumber.json" }, tags = { "~@ignore" })
public class CucumberTestRunner {
}


问:
Linq 2 Sql - Repository isn't working unless query is done inside controller
I'm really struggling to understand an issue I'm facing.  I have a very simple repository with the following code:

```<code>public class ProductRepository : IProductRepository
{
    private Table<Product> productTable;

    public Product GetProductById(int id)
    {
         return productTable.Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()
    {
        return productTable;
    }
 }
</code>```

I have a controller called AddToCart().  The repository class above is passed into the controller via DI.  I pass a productId into this controller, and the repository method is called.  The problem is that a null value is returned when a Product does exist.

```<code>    public void AddToCart(int productId)
    {
        //Returns Null value
        Product product = productRepository.GetProductById(productId);
        ...
    }
</code>```

I thought the issue may be that I need the IQueryable<> around the class that I'm returning.  I also modified my AddToCart method in various ways to try to get it to work.

```<code>public IQueryable<Product> GetProductById(int id)
{
    return productTable.Where(p => p.ProductId == id);
}

public void AddToCart(int productId)
{
    //Throws error / Returns Null value
    Product product = productRepository.GetProductById(productId).Single();
    //Returns Null value
    Product product = productRepository.GetProductById(productId).FirstOrDefault();
}
</code>```

However, the following works and I have no reason why!  It's basically the same code, just being done in the controller.  Anyone have any ideas? :/

```<code>    public void AddToCart(int productId)
    {
        Product product = productRepository.GetProducts().FirstOrDefault(p => p.ProductId == productId);
    }
</code>```

答:
It's hard to see what the problem is without more information.

How is GetProductById() returning null? Single() does not allow nulls to be returned and will throw an InvalidOperationException if there are no items or more than one item returned.

What is GetProducts() doing differently? Looking at your code, there should not be any problem.

What happens when you try this?

```<code>public class ProductRepository : IProductRepository
  {
    private Table<Product> productTable;

    public Product GetProductById(int id)    {
        return GetProducts().Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()    {
      return productTable;
    }
}
</code>```

As a side note, you should avoid using Single() if your are positive that only one item exists in your collection. Single will always itterate through your entire collection. First() is more efficient in that regard.

Body:
I'm really struggling to understand an issue I'm facing.  I have a very simple repository with the following code:

public class ProductRepository : IProductRepository
{
    private Table<Product> productTable;

    public Product GetProductById(int id)
    {
         return productTable.Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()
    {
        return productTable;
    }
 }

I have a controller called AddToCart().  The repository class above is passed into the controller via DI.  I pass a productId into this controller, and the repository method is called.  The problem is that a null value is returned when a Product does exist.

    public void AddToCart(int productId)
    {
        //Returns Null value
        Product product = productRepository.GetProductById(productId);
        ...
    }

I thought the issue may be that I need the IQueryable<> around the class that I'm returning.  I also modified my AddToCart method in various ways to try to get it to work.

public IQueryable<Product> GetProductById(int id)
{
    return productTable.Where(p => p.ProductId == id);
}

public void AddToCart(int productId)
{
    //Throws error / Returns Null value
    Product product = productRepository.GetProductById(productId).Single();
    //Returns Null value
    Product product = productRepository.GetProductById(productId).FirstOrDefault();
}

However, the following works and I have no reason why!  It's basically the same code, just being done in the controller.  Anyone have any ideas? :/

    public void AddToCart(int productId)
    {
        Product product = productRepository.GetProducts().FirstOrDefault(p => p.ProductId == productId);
    }

Body:
It's hard to see what the problem is without more information.

How is GetProductById() returning null? Single() does not allow nulls to be returned and will throw an InvalidOperationException if there are no items or more than one item returned.

What is GetProducts() doing differently? Looking at your code, there should not be any problem.

What happens when you try this?

public class ProductRepository : IProductRepository
  {
    private Table<Product> productTable;

    public Product GetProductById(int id)    {
        return GetProducts().Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()    {
      return productTable;
    }
}

As a side note, you should avoid using Single() if your are positive that only one item exists in your collection. Single will always itterate through your entire collection. First() is more efficient in that regard.


问:
MQL4: How can we separate a class definition across files?
I would like to be able to split classes in MQL4 across files, i.e. into the definition in an include/.mqh file and an implementation in a library/.mq4 file. How do we do this - I keep getting compile errors ("'function_name' must have a body")?

E.g. I can take a subset of the code at https://docs.mql4.com/basis/oop/class_templates, and put the definition into a .mqh file:

```<code>#import "library.ex4"

//+------------------------------------------------------------------+
//| Class for a free access to an array element               |
//+------------------------------------------------------------------+
template<typename T>
class TSafeArray
  {
protected:
   T                 m_array[];
public:
   //--- operator for accessing the array element by index
   T                 operator[](int index);
  };

#import
</code>```

and put the implementation into a .mq4 file (called library.mq4):

```<code>#property library

//+------------------------------------------------------------------+
//| Receiving an element by index                           |
//+------------------------------------------------------------------+
template<typename T>
T TSafeArray::operator[](int index)
  {
   static T invalid_value;
//---
   int max=ArraySize(m_array)-1;
   if(index<0 || index>=ArraySize(m_array))
     {
      PrintFormat("%s index %d is not in range (0-%d)!",__FUNCTION__,index,max);
      return(invalid_value);
     }
//---
   return(m_array[index]);
  }
</code>```

This was asked previously, but the main answer put both definition and implementation into the .mqh file:
What is the correct way to define MQL4 "#import of static class methods"?. Is there any way around this?

答:
The best answer I found was pointed out by Ex Ovo Omnia at https://www.mql5.com/en/forum/157907#comment_3808727.

Details are in the second section ("2. Export of the Hidden Implementation of a Class) at https://www.mql5.com/en/articles/362#expclass. Note that the files there work in MQL4 too if you change the extensions to .mq4 and update the #include / #import statements.

In summary: define a base / parent class in the include file, then define and implement a derived / child class in the library file. In the expert file, a pointer to the base class can then be cast to a pointer of the derived class to make use of the hidden derived class methods.

Thanks to Daniel Kniaz for his suggestion of the CArrayObj class (https://www.mql5.com/en/docs/standardlibrary/datastructures/carrayobj). I found this is good if you wish to use arrays where all the elements are of the same type (e.g. an ArrayList-like object of integer elements) or if they follow certain predefined structures (e.g. CTrade) but not if your arrays have a custom structure of multiple different types.

Body:
I would like to be able to split classes in MQL4 across files, i.e. into the definition in an include/.mqh file and an implementation in a library/.mq4 file. How do we do this - I keep getting compile errors ("'function_name' must have a body")?

E.g. I can take a subset of the code at https://docs.mql4.com/basis/oop/class_templates, and put the definition into a .mqh file:

#import "library.ex4"

//+------------------------------------------------------------------+
//| Class for a free access to an array element               |
//+------------------------------------------------------------------+
template<typename T>
class TSafeArray
  {
protected:
   T                 m_array[];
public:
   //--- operator for accessing the array element by index
   T                 operator[](int index);
  };

#import

and put the implementation into a .mq4 file (called library.mq4):

#property library

//+------------------------------------------------------------------+
//| Receiving an element by index                           |
//+------------------------------------------------------------------+
template<typename T>
T TSafeArray::operator[](int index)
  {
   static T invalid_value;
//---
   int max=ArraySize(m_array)-1;
   if(index<0 || index>=ArraySize(m_array))
     {
      PrintFormat("%s index %d is not in range (0-%d)!",__FUNCTION__,index,max);
      return(invalid_value);
     }
//---
   return(m_array[index]);
  }

This was asked previously, but the main answer put both definition and implementation into the .mqh file:
What is the correct way to define MQL4 "#import of static class methods"?. Is there any way around this?