问:
Unable to provision k8s from gcloud: "Account does not exist"
I am trying to provision a k8s cluster on Google Cloud Platform using gcloud

```<code>$ gcloud container clusters create my-cluster

ERROR: (gcloud.container.clusters.create) ResponseError: code=400,
message=service account "xxxxxx-compute@developer.gserviceaccount.com" does not exist.
</code>```

Any idea as to why this is error is occurring? I have been able to provision in the past w/o any issue until now.

答:
I got the same error while creating a cluster using GKE. Earlier I was getting this error because I did not attach the service account (which needs to be created and assigned with a role having Kubernetes specific permissions).

Now, the further question you might have where to attach the service account, for this you need to go the Create Cluster --> Node Pool Section --> More Options --> (a new window will popup) --> security section --> In-Service account dropdown Choose the Service account.

Once you do it, then save and say create a cluster, hopefully you will not get the same error.

Body:
I am trying to provision a k8s cluster on Google Cloud Platform using gcloud

$ gcloud container clusters create my-cluster

ERROR: (gcloud.container.clusters.create) ResponseError: code=400,
message=service account "xxxxxx-compute@developer.gserviceaccount.com" does not exist.

Any idea as to why this is error is occurring? I have been able to provision in the past w/o any issue until now.


来源: stackexchange

问:
Why does pandas.cut categories the first element as NaN?
I was trying to first cut and then categorize an array of numerical values with labels with np.linspace and pd.cut. My code is shown below. </p>

```<code>import numpy as np
import pandas as pd

n=4 #number of edges to group 'a' to three categories.
a = np.arange(2.0,5.0,0.1)
dfa = pd.DataFrame(a, columns=['a'])
edges, step = np.linspace(np.floor(a.min()), np.ceil(a.max()), num = n, retstep=True)
dfa['a_label'] = pd.cut(x=dfa['a'], bins=list(edges), labels=range(n-1))
print(edges)
print(dfa.head())
</code>```

<p>However, I got a NaN for the first element in the array when I ran it as shown in the results below. By right, the first element 2.0 should be included in the first category. Please help me figure out what went wrong. Thanks in advance. </p>

```<code>[2. 3. 4. 5.]
     a a_label
0  2.0     NaN
1  2.1     0.0
2  2.2     0.0
3  2.3     0.0
4  2.4     0.0
</code>```

答:
Add parameter include_lowest-True to cut:

include_lowest bool, default False

  Whether the first interval should be left-inclusive or not.

```<code>dfa['a_label'] = pd.cut(x=dfa['a'], bins=list(edges), labels=range(n-1), include_lowest=True)
print(dfa.head())
     a a_label
0  2.0       0
1  2.1       0
2  2.2       0
3  2.3       0
4  2.4       0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was trying to first cut and then categorize an array of numerical values with labels with np.linspace and pd.cut. My code is shown below.

import numpy as np
import pandas as pd

n=4 #number of edges to group 'a' to three categories.
a = np.arange(2.0,5.0,0.1)
dfa = pd.DataFrame(a, columns=['a'])
edges, step = np.linspace(np.floor(a.min()), np.ceil(a.max()), num = n, retstep=True)
dfa['a_label'] = pd.cut(x=dfa['a'], bins=list(edges), labels=range(n-1))
print(edges)
print(dfa.head())

However, I got a NaN for the first element in the array when I ran it as shown in the results below. By right, the first element 2.0 should be included in the first category. Please help me figure out what went wrong. Thanks in advance.

[2. 3. 4. 5.]
     a a_label
0  2.0     NaN
1  2.1     0.0
2  2.2     0.0
3  2.3     0.0
4  2.4     0.0

Body:
Add parameter include_lowest-True to cut:

include_lowest bool, default False

  Whether the first interval should be left-inclusive or not.

dfa['a_label'] = pd.cut(x=dfa['a'], bins=list(edges), labels=range(n-1), include_lowest=True)
print(dfa.head())
     a a_label
0  2.0       0
1  2.1       0
2  2.2       0
3  2.3       0
4  2.4       0


问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
if (string.empty()) foo(const_cast<char*>(string.c_str());

a better but still evil way to remove const is const_cast(const_string); (its better to find via grep/search)

Witch exception did you encountered?
Do u just read the char* or do you change the values? if you change, you should redesign your code.

const char* test = string.c_str();
Does not create a deep copy of string, only a pointer to the internal data representation of string.data().

=> (a suggestion) find a C++ book where you can get a more in deep view of c++. Or something like  to C++.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....


问:
How to get properties from an Object filtering by an array in Javascript
I have a JS object like this:

```<code>const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};
</code>```

and an array of object like this:

```<code>const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];
</code>```

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

```<code>export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};
</code>```

any idea how to do that please?

答:
Another answer.

const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3,
  '$prop4': 4
};
const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];

let propKeys = myArray.map(ele => ele.propKey)

let obj = Object.keys(myObj).reduce((ret, key) => {
  if (propKeys.indexOf(key) > -1) {
    ret[key] = myObj[key]
  }
  return ret
}, {})
console.log(obj)```

Body:
I have a JS object like this:

const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};

and an array of object like this:

const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};

any idea how to do that please?


问:
ionic 3: FAILURE: Build failed with an exception
I am trying to create Android App Bundle for an ionic 3 project. When running the command ./gradlew bundle I get the error below. In the .bash_profile file I have added the following:

```<code>export ANDROID_HOME=/Users/dome/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH/:$ANDROID_HOME/platform-tools
</code>```

The Gradle version is: 4.4.1.

ERROR

```<code>iMac:android dome$ ./gradlew bundle

> Configure project :app
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The onesignal-gradle-plugin MUST be before com.android.application!
   Please put onesignal-gradle-plugin first OR update to com.android.tools.build:gradle:3.0.0 or newer!
An exception occurred while trying to find the Android build tools.
Project evaluation failed including an error in afterEvaluate {}. Run with --stacktrace for details of the afterEvaluate {} error.

FAILURE: Build failed with an exception.

* Where:
Script '/Users/dome/myAPP/platforms/android/CordovaLib/cordova.gradle' line: 121

* What went wrong:
A problem occurred evaluating project ':app'.
> Unable to determine Android SDK directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s
iMac:android dome$
</code>```

答:
After adding the exports below, I didn't close and reopen the terminal hence the issues. Now sorted.</p>

```<code>export ANDROID_HOME=/Users/dome/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH/:$ANDROID_HOME/platform-tools
</code>```

Body:
I am trying to create Android App Bundle for an ionic 3 project. When running the command ./gradlew bundle I get the error below. In the .bash_profile file I have added the following:

export ANDROID_HOME=/Users/dome/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH/:$ANDROID_HOME/platform-tools

The Gradle version is: 4.4.1.

ERROR

iMac:android dome$ ./gradlew bundle

> Configure project :app
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
WARNING: The onesignal-gradle-plugin MUST be before com.android.application!
   Please put onesignal-gradle-plugin first OR update to com.android.tools.build:gradle:3.0.0 or newer!
An exception occurred while trying to find the Android build tools.
Project evaluation failed including an error in afterEvaluate {}. Run with --stacktrace for details of the afterEvaluate {} error.

FAILURE: Build failed with an exception.

* Where:
Script '/Users/dome/myAPP/platforms/android/CordovaLib/cordova.gradle' line: 121

* What went wrong:
A problem occurred evaluating project ':app'.
> Unable to determine Android SDK directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 0s
iMac:android dome$

Body:
After adding the exports below, I didn't close and reopen the terminal hence the issues. Now sorted.

export ANDROID_HOME=/Users/dome/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH/:$ANDROID_HOME/platform-tools


问:
Why does preventDefault stop working when I try to use a function passed by props?
I have a component with a form and when I use this line of code the function passed by props works.

<form onSubmit={this.props.onCreateNewItem.bind(this)}>

If I try to create another function before the render that will run onCreateNewItem it stops working.

<form action="" onSubmit={this.onChangeTest}>

```<code>onChangeTest(event){
    event.preventDefault();
    this.props.onCreateNewItem();
  }
</code>```

If I run the code with out trying to call the function then the preventDefault works. If I try to run the function I get this error: "TypeError: Cannot read property 'preventDefault' of undefined." I tried to bind this and then preventDefault works but it does not run the function.

this.props.onCreateNewItem.bind(this);

I am confused because I can get the preventDefault to work without calling the function and I can get the function to work if I call it directly in the form but I can not get them both to work together.

答:
You have to bind 'onChangeTest' method. Currently the this inside onChangeTest is referring to the form object not React component.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onChangeTest = this.onChangeTest.bind(this);
  }

  onChangeTest(event){
    event.preventDefault();
    this.props.onCreateNewItem();
  }

  render() {
   return (
    <form action="" onSubmit={this.onChangeTest}>
      <button type="submit">Submit</button>
    </form>
   );
  }
}

///
function onCreateNewItem() {
    console.log("onCreateNewItem called")
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App onCreateNewItem={onCreateNewItem} />, rootElement);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
I have a component with a form and when I use this line of code the function passed by props works.

<form onSubmit={this.props.onCreateNewItem.bind(this)}>

If I try to create another function before the render that will run onCreateNewItem it stops working.

<form action="" onSubmit={this.onChangeTest}>

onChangeTest(event){
    event.preventDefault();
    this.props.onCreateNewItem();
  }

If I run the code with out trying to call the function then the preventDefault works. If I try to run the function I get this error: "TypeError: Cannot read property 'preventDefault' of undefined." I tried to bind this and then preventDefault works but it does not run the function.

this.props.onCreateNewItem.bind(this);

I am confused because I can get the preventDefault to work without calling the function and I can get the function to work if I call it directly in the form but I can not get them both to work together.

Body:
You have to bind 'onChangeTest' method. Currently the this inside onChangeTest is referring to the form object not React component.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onChangeTest = this.onChangeTest.bind(this);
  }

  onChangeTest(event){
    event.preventDefault();
    this.props.onCreateNewItem();
  }

  render() {
   return (
    <form action="" onSubmit={this.onChangeTest}>
      <button type="submit">Submit</button>
    </form>
   );
  }
}

///
function onCreateNewItem() {
    console.log("onCreateNewItem called")
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App onCreateNewItem={onCreateNewItem} />, rootElement);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
Modules & services 404 error - Prestashop
When i click on Modules & Services tab on back office it redirect to 404 error page.
Url is like below

https://example.com/admin301f2qz0v/index.php/module/catalog?_token=rwsJaBnDlZ5O28QVeFYLeA4P2D--ySMEhhqLOcsJxA0

I tried

Re generating .htaccess file

Replaced nginx.conf file as like below

https://github.com/MattLoyeD/Prestashop-Nginx/blob/master/prestashop-nginx.conf

but still got 404 error.

Prestashop version : 1.7.0.4

答:
Regenerating the .htaccess file won't have any effect if you are using NGINX. Add these lines to your configuration if they are not there (replace admin-dev by your admin directory name:

```<code>location /admin-dev{
    if (!-e $request_filename) {
        rewrite ^/.*$ /admin-dev/index.php last;
    }
}
</code>```

The admin panel has several pages that are accessed in a different way. That snipped will chage the way the page is accessed in some of the cases.

Body:
Regenerating the .htaccess file won't have any effect if you are using NGINX. Add these lines to your configuration if they are not there (replace admin-dev by your admin directory name:

location /admin-dev{
    if (!-e $request_filename) {
        rewrite ^/.*$ /admin-dev/index.php last;
    }
}

The admin panel has several pages that are accessed in a different way. That snipped will chage the way the page is accessed in some of the cases.


问:
Is try catch block necessary inside controller in laravel?
I'm currently working on a project with my friend. He follows this method of writing codes. Is it good or bad? I'm also not that much experience developer.</p>

```<code>public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();
    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}
</code>```

答:
Don't have a broad Exception catch block. Only catch exceptions you expect to be thrown in that block that way you can properly log unexpected exceptions and fix any other bugs in your code that may have caused those, instead of hiding them from yourself.

If you must do this then it might be in the context of something like:

```<code>public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        if (!($e instanceof SQLException)) {
            app()->make(\App\Exceptions\Handler::class)->report($e); // Report the exception if you don't know what actually caused it
        }
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();

    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}
</code>```

This way any unexpected exceptions will still be reported and you can go through your logs later to fix any bugs that are causing them.

As a reminder since PHP 7.1 you can have a union of exceptions in a catch block (Reference) e.g.

```<code>try { }
catch (ExceptionType1|ExceptionType2 $e) {

}
</code>```

This way you can handle the exceptions you know you can handle and let Laravel handle the ones you are not sure how to handle.

Note that you generally don't have to have try-catch blocks in controller code, you can always use the exception handler to do the flash/redirect back combination for all unhandled exceptions if that is your preferred way of handling them.

Body:
I'm currently working on a project with my friend. He follows this method of writing codes. Is it good or bad? I'm also not that much experience developer.

public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();
    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}

Body:
Don't have a broad Exception catch block. Only catch exceptions you expect to be thrown in that block that way you can properly log unexpected exceptions and fix any other bugs in your code that may have caused those, instead of hiding them from yourself.

If you must do this then it might be in the context of something like:

public function store(Request $request)
 {
    try
    {
        $comment = new TicketComment();
        $comment->content = $request['comment'];
        $comment->user_id = Auth::user()->id;
        $comment->ticket_id = $request['ticketId'];
        $comment->save();
        $ticket = Ticket::where('id', '=', $comment->ticket_id)->first();
        $ticket->updated_at = $comment->created_at;
        $ticket->update();
    }
    catch(Exception $e)
    {
        if (!($e instanceof SQLException)) {
            app()->make(\App\Exceptions\Handler::class)->report($e); // Report the exception if you don't know what actually caused it
        }
        request()->session()->flash('unsuccessMessage', 'Failed to add comment !!!');
        return redirect()->back();

    }
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');
    return redirect()->back();
}

This way any unexpected exceptions will still be reported and you can go through your logs later to fix any bugs that are causing them.

As a reminder since PHP 7.1 you can have a union of exceptions in a catch block (Reference) e.g.

try { }
catch (ExceptionType1|ExceptionType2 $e) {

}

This way you can handle the exceptions you know you can handle and let Laravel handle the ones you are not sure how to handle.

Note that you generally don't have to have try-catch blocks in controller code, you can always use the exception handler to do the flash/redirect back combination for all unhandled exceptions if that is your preferred way of handling them.


问:
Why isn't "--comment" working when "-- comment" does?
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?</p>

```<code><?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>
</code>```

答:
Because the MySQL dev team decided that if SELECT -1 is valid code to select -1

then SELECT --1 Should be valid (My)SQL for selecting +1.

Body:
I've finally found why my PHP script didn't work. It was because of MySQL "--comment" instead of "-- comment". I recently started with PHP, and until then, I had always used "--comment". Now, I wonder why this isn't allowed in PHP's mysql_query()?

<?php

$query = "SELECT firstname,
-- comment
lastname, address,
--not a comment
age FROM friends WHERE firstname='%s' AND lastname='%s'";

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

?>


问:
add_shortcode(); is php predefined or only WordPress function?
add_shortcode(); is php predefined or only WordPress function? I need to make a plugin for several calculators and each calculator have a separate shortcode. Please help me out community.</p>

答:
add_shortcode functions is defined in wordpress core
"wp-includes/shortcodes.php"
in the above file.</p>


问:
Number of days between today and a negative year ("-2580,01,01", today")
I need to calculate the number of days between two dates. One will be today and the other one is -2580,01,01.

I have tried with the datetime library but I can't because the datetime library don't accept negative years (MIN=1, MAX=9999).

I have tried with dateutil.relativedelta:

```<code>from datetime import *
from dateutil.relativedelta import *
import calendar

RightNOW = datetime.now() # with full time
JustTODAY = date.today() # only days

PastTime = JustTODAY+relativedelta(years=-4600)

print(PastTime)
</code>```

Traceback (most recent call last):
  File "GoblinTest.py", line 11, in <module>
    PastTime = JustTODAY+relativedelta(years=-4600)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)
ValueError: year -2580 is out of range
```

答:
The issue is that datetime only supports years > 0 for datetime.

```<code>>>> datetime.datetime(2,1,1) - relativedelta(years=1)
datetime.datetime(1, 1, 1, 0, 0)
>>> datetime.datetime(2,1,1) - relativedelta(years=2)
ValueError: year 0 is out of range
</code>```

As stated in the docs:

The datetime module exports the following constants:
    datetime.MINYEAR
    The smallest year number allowed in a date or datetime object. MINYEAR is 1.

Body:
I need to calculate the number of days between two dates. One will be today and the other one is -2580,01,01.

I have tried with the datetime library but I can't because the datetime library don't accept negative years (MIN=1, MAX=9999).

I have tried with dateutil.relativedelta:

from datetime import *
from dateutil.relativedelta import *
import calendar

RightNOW = datetime.now() # with full time
JustTODAY = date.today() # only days

PastTime = JustTODAY+relativedelta(years=-4600)

print(PastTime)

Traceback (most recent call last):
  File "GoblinTest.py", line 11, in <module>
    PastTime = JustTODAY+relativedelta(years=-4600)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)
ValueError: year -2580 is out of range

Body:
The issue is that datetime only supports years > 0 for datetime.

>>> datetime.datetime(2,1,1) - relativedelta(years=1)
datetime.datetime(1, 1, 1, 0, 0)
>>> datetime.datetime(2,1,1) - relativedelta(years=2)
ValueError: year 0 is out of range

As stated in the docs:

The datetime module exports the following constants:
    datetime.MINYEAR
    The smallest year number allowed in a date or datetime object. MINYEAR is 1.


问:
Why is my mapped network drive not appearing in Network Locations?
I'm using Windows 10. Here is my code to map the network drive.

```<code>System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "net.exe";
p.StartInfo.Arguments = "use Z: " + dPath; //dPath has escaped characters
p.Start();
</code>```

What I was trying to do was trying to run the command net.exe use Z: DPATH as administrator but the Z drive does not appear in File Explorer but when I run the exact same command using cmd with Admin rights, the Z drive appears correctly.

Proof of mapped drive

My Network drive is mapped as evidenced below (Encountered this error when trying to re-map it manually) just that it wasn't appearing under Network Locations in File Explorer > This PC.

答: It helped me restarting explorer.exe with admin rights via Task Manager.</p>

Body:
I'm using Windows 10. Here is my code to map the network drive.

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "net.exe";
p.StartInfo.Arguments = "use Z: " + dPath; //dPath has escaped characters
p.Start();

What I was trying to do was trying to run the command net.exe use Z: DPATH as administrator but the Z drive does not appear in File Explorer but when I run the exact same command using cmd with Admin rights, the Z drive appears correctly.

Proof of mapped drive

My Network drive is mapped as evidenced below (Encountered this error when trying to re-map it manually) just that it wasn't appearing under Network Locations in File Explorer > This PC.


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

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

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
You can calculate the run lengths of each sign using rle from base to  and do something like this.

```<code>set.seed(0)
z <- round(rnorm(20, sd = 0.02), 3)
run_lengths <- rle(sign(z))$lengths
run_lengths
# [1] 1 1 1 3 1 1 2 2 1 2 2 1 1 1
</code>```

To get n_of_sequence

```<code>n_of_sequence <- run_lengths %>% map(seq) %>% unlist
n_of_sequence
# [1] 1 1 1 1 2 3 1 1 1 2 1 2 1 1 2 1 2 1 1 1
</code>```

Finally, to get the summations of the sequences,

```<code>start <- cumsum(c(1,run_lengths))
start <- start[-length(start)] # start points of each series
map2(start,run_lengths,~cumsum(z[.x:(.x+.y-1)])) %>% unlist()
# [1] -0.010  0.003 -0.002  0.018  0.020  0.026 -0.012  0.014 -0.017 -0.024
# [11]  0.002  0.004 -0.004  0.015  0.017 -0.001 -0.009  0.010 -0.018  0.046
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

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

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
You can calculate the run lengths of each sign using rle from base to  and do something like this.

set.seed(0)
z <- round(rnorm(20, sd = 0.02), 3)
run_lengths <- rle(sign(z))$lengths
run_lengths
# [1] 1 1 1 3 1 1 2 2 1 2 2 1 1 1

To get n_of_sequence

n_of_sequence <- run_lengths %>% map(seq) %>% unlist
n_of_sequence
# [1] 1 1 1 1 2 3 1 1 1 2 1 2 1 1 2 1 2 1 1 1

Finally, to get the summations of the sequences,

start <- cumsum(c(1,run_lengths))
start <- start[-length(start)] # start points of each series
map2(start,run_lengths,~cumsum(z[.x:(.x+.y-1)])) %>% unlist()
# [1] -0.010  0.003 -0.002  0.018  0.020  0.026 -0.012  0.014 -0.017 -0.024
# [11]  0.002  0.004 -0.004  0.015  0.017 -0.001 -0.009  0.010 -0.018  0.046


问:
How to write a custom powershell host
Similar to nuget

Looking for any starter material hopefully before delving into the debugger

答:
I have a series of blog posts dedicated to this.

Here's the first.

I have also implemented a debugger.  I'd be glad to answer questions you might have.  Contact info on my blog.

Also, here's a project that actually implemented a debugger using the API...it's the only place I've found any published code to do that.

Title: How to write a custom powershell host


问:
How to filter rows, hide/unhide columns in protected worksheet?
I have an Excel worksheet for group collaboration. It is protected with a password.

Because of the password protection restriction, I am trying to compose a VBA code so other users can still filter the rows, hide/unhide the columns while in protected worksheet.

It resides in ThisWorkbook as follows:-

```<code>Private Sub Workbook_Open()

Dim wSheet As Worksheet

For Each wSheet In Worksheets
    wSheet.Protect Password:="LoveisPatience", _
    UserInterFaceOnly:=True
Next wSheet

With ActiveSheet
    .Protect Password:="LoveisPatience", AllowFiltering:=True
    .EnableSelection = xlUnlockedCells
End With

With ActiveSheet
    .Protect Password:="LoveisPatience", AllowFormattingColumns:=True
    .EnableSelection = xlUnlockedCells
End With

End Sub
</code>```

With the above code, I manage to hide the columns which are previously complete with " Data tab> Group", but I could not unhide any columns.

And because of the inclusion of this "AllowFormattingColumns:", the "AllowFiltering" function for rows is now unworkable.

How can I make filter rows & hide/unhide columns work seamlessly?

答:
The following code works for me:

```<code>Private Sub Workbook_Open()

Dim wSheet As Worksheet

For Each wSheet In Worksheets
    wSheet.Protect Password:="password", UserInterFaceOnly:=True
Next wSheet

With ActiveSheet
    .Protect Password:="password", AllowFiltering:=True, AllowFormattingColumns:=True
    .EnableSelection = xlUnlockedCells
End With
</code>```

The problem seems to be an inconsistency between the two with statements. The second with statement (formatting columns) was blocking the first one (filtering). It was a bit strange because the rows were unlocked as it should be.

Does it work for you ?

Cheers

Body:
I have an Excel worksheet for group collaboration. It is protected with a password.

Because of the password protection restriction, I am trying to compose a VBA code so other users can still filter the rows, hide/unhide the columns while in protected worksheet.

It resides in ThisWorkbook as follows:-

Private Sub Workbook_Open()

Dim wSheet As Worksheet

For Each wSheet In Worksheets
    wSheet.Protect Password:="LoveisPatience", _
    UserInterFaceOnly:=True
Next wSheet

With ActiveSheet
    .Protect Password:="LoveisPatience", AllowFiltering:=True
    .EnableSelection = xlUnlockedCells
End With

With ActiveSheet
    .Protect Password:="LoveisPatience", AllowFormattingColumns:=True
    .EnableSelection = xlUnlockedCells
End With

End Sub

With the above code, I manage to hide the columns which are previously complete with " Data tab> Group", but I could not unhide any columns.

And because of the inclusion of this "AllowFormattingColumns:", the "AllowFiltering" function for rows is now unworkable.

How can I make filter rows & hide/unhide columns work seamlessly?

Body:
The following code works for me:

Private Sub Workbook_Open()

Dim wSheet As Worksheet

For Each wSheet In Worksheets
    wSheet.Protect Password:="password", UserInterFaceOnly:=True
Next wSheet

With ActiveSheet
    .Protect Password:="password", AllowFiltering:=True, AllowFormattingColumns:=True
    .EnableSelection = xlUnlockedCells
End With

The problem seems to be an inconsistency between the two with statements. The second with statement (formatting columns) was blocking the first one (filtering). It was a bit strange because the rows were unlocked as it should be.

Does it work for you ?

Cheers


问:
saving userType in ReactJs thorughout the session
I am using ReactJs and Nodejs with mysql as my backend, I am maintaining user session via express-session and setting cookie header in my browser. The problem is that I want to display components based on role (eg.admin or user). I am sending the userType from database to React app,in response to the successful login.
How can I maintain and store this userType througout the session so that I can manage my roles.
I dont think local Storage is a good option.

P.S: I have also key:value pair of userType inside the cookie which I am receiving in my browser.but I dont know how to extract userType from the cookie

答:
If you are having a single cookie, ie userType, you can simple do this in componentDidMount or any other applicable control location:

```<code>let userType = document.cookie.split("=")[1]
console.log(userType) //your cokkie value
</code>```

Else, if there are many cookies, you can follow this:

```<code>var cookies= {};
document.cookie.split(/\s*;\s*/).forEach(function(pair) {
    pair = pair.split(/\s*=\s*/);
    cookies[pair[0]] = pair.splice(1).join('=');
});
console.log(cookies.userType)
</code>```

Body:
If you are having a single cookie, ie userType, you can simple do this in componentDidMount or any other applicable control location:

let userType = document.cookie.split("=")[1]
console.log(userType) //your cokkie value

Else, if there are many cookies, you can follow this:

var cookies= {};
document.cookie.split(/\s*;\s*/).forEach(function(pair) {
    pair = pair.split(/\s*=\s*/);
    cookies[pair[0]] = pair.splice(1).join('=');
});
console.log(cookies.userType)


问:
Oracle Analytic functions - How to reuse a PARTITION BY clause?
I have written a complex SQL query with Oracle in which I want to use two analytic function over the same partition.

Let's be quite simple but not too much:

```<code>SELECT col1,
       MAX(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC),
       MIN(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC)
  FROM my_table;
</code>```

Is there a more elegant syntax for factoring the PARTITION BY clause?

Thank you.

答:
Partition definition could be reused with WINDOW clause. Starting from version 20c Oracle supports it:

Enhanced Analytic Functions

The query_block clause of a SELECT statement now supports the window_clause, which implements the window clause of the SQL standard table expression as defined in the SQL:2011 standard.

SELECT

Note that OVER window_name is not equivalent to OVER (window_name …). OVER (window_name …) implies copying and modifying the window specification, and will be rejected if the referenced window specification includes a windowing_clause.

You cannot use existing_window_name with windowing_clause

Query could be rewritten as:

```<code>SELECT col1,
       MAX(col2) OVER w AS max_col2,
       MIN(col2) OVER w AS min_col2
FROM my_table
WINDOW w AS (PARTITION BY col3, col4, col5, col6,
                          CASE WHEN col7 LIKE 'foo'
                               THEN SUBSTR(col7,1,5)
                               ELSE col7
                          END
                          ORDER BY col5 ASC, col6 DESC);
</code>```

Note that part of window definition could be extended, for instance queries could share PARTITION BY but have different sorting:

```<code>SELECT col_x,
       FIRST_VALUE(col_y) OVER (w ORDER BY col3),
       FIRST_VALUE(col_z) OVER (w ORDER BY col4)
FROM tab
WINDOW w AS (PARTITION BY col1, col2);
</code>```

We cannot perform sth like sharing the same PARTITION BY and ORDER BY but with different window size:

```<code>SELECT col_x,
       AVG(col_y) OVER (w ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS moving_avg_3,
       AVG(col_y) OVER (w ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) AS moving_avg_5
FROM tab
WINDOW w AS (PARTITION BY col1, col2 ORDER BY col3)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have written a complex SQL query with Oracle in which I want to use two analytic function over the same partition.

Let's be quite simple but not too much:

SELECT col1,
       MAX(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC),
       MIN(col2) OVER(PARTITION BY col3, col4, col5, col6,
                                   CASE WHEN col7 LIKE 'foo'
                                        THEN SUBSTR(col7,1,5)
                                        ELSE col7
                                   END
                                   ORDER BY col5 ASC, col6 DESC)
  FROM my_table;

Is there a more elegant syntax for factoring the PARTITION BY clause?

Thank you.

Body:
Partition definition could be reused with WINDOW clause. Starting from version 20c Oracle supports it:

Enhanced Analytic Functions

The query_block clause of a SELECT statement now supports the window_clause, which implements the window clause of the SQL standard table expression as defined in the SQL:2011 standard.

SELECT

Note that OVER window_name is not equivalent to OVER (window_name …). OVER (window_name …) implies copying and modifying the window specification, and will be rejected if the referenced window specification includes a windowing_clause.

You cannot use existing_window_name with windowing_clause

Query could be rewritten as:

SELECT col1,
       MAX(col2) OVER w AS max_col2,
       MIN(col2) OVER w AS min_col2
FROM my_table
WINDOW w AS (PARTITION BY col3, col4, col5, col6,
                          CASE WHEN col7 LIKE 'foo'
                               THEN SUBSTR(col7,1,5)
                               ELSE col7
                          END
                          ORDER BY col5 ASC, col6 DESC);

Note that part of window definition could be extended, for instance queries could share PARTITION BY but have different sorting:

SELECT col_x,
       FIRST_VALUE(col_y) OVER (w ORDER BY col3),
       FIRST_VALUE(col_z) OVER (w ORDER BY col4)
FROM tab
WINDOW w AS (PARTITION BY col1, col2);

We cannot perform sth like sharing the same PARTITION BY and ORDER BY but with different window size:

SELECT col_x,
       AVG(col_y) OVER (w ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS moving_avg_3,
       AVG(col_y) OVER (w ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) AS moving_avg_5
FROM tab
WINDOW w AS (PARTITION BY col1, col2 ORDER BY col3)


问:
ReactJS delay onChange while typing
I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can't quite place my finger on how to do both.

So When the user stops typing I want an action to be triggered, but not before. Any suggestions?

答:
With React Hooks and Function components

To keep the string the user is typing, use the useState hook to store the text the user is typing. Then give that state to the value of the input. Also be sure to use setState on the onChange event handler of the input, otherwise the input value won't change.

To trigger an action only sometime after the user stops typing, you can use the useEffect hook together with setTimeout. In this case, we want to trigger useEffect when the input value changes, so we'll create a useEffect hook and on its dependency array give it the variable with the value of the input. The function given to useEffect should use setTimeout to trigger an action after the delay time that is desired. Also, the function given to useEffect should return a cleanup function that clears the timeout set. This avoids doing actions for input values which are no longer relevant to the user.

Below is a little example of an app that uses the above steps to keep the string the user is typing visible and to show the finished string 500ms after the user stops typing.

```<code>function App() {
  const [query, setQuery] = useState("");
  const [displayMessage, setDisplayMessage] = useState("");

  useEffect(() => {
    const timeOutId = setTimeout(() => setDisplayMessage(query), 500);
    return () => clearTimeout(timeOutId);
  }, [query]);

  return (
    <>
      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
      />
      <p>{displayMessage}</p>
    </>
  );
}
</code>```

Title: ReactJS delay onChange while typing

Body:
With React Hooks and Function components

To keep the string the user is typing, use the useState hook to store the text the user is typing. Then give that state to the value of the input. Also be sure to use setState on the onChange event handler of the input, otherwise the input value won't change.

To trigger an action only sometime after the user stops typing, you can use the useEffect hook together with setTimeout. In this case, we want to trigger useEffect when the input value changes, so we'll create a useEffect hook and on its dependency array give it the variable with the value of the input. The function given to useEffect should use setTimeout to trigger an action after the delay time that is desired. Also, the function given to useEffect should return a cleanup function that clears the timeout set. This avoids doing actions for input values which are no longer relevant to the user.

Below is a little example of an app that uses the above steps to keep the string the user is typing visible and to show the finished string 500ms after the user stops typing.

function App() {
  const [query, setQuery] = useState("");
  const [displayMessage, setDisplayMessage] = useState("");

  useEffect(() => {
    const timeOutId = setTimeout(() => setDisplayMessage(query), 500);
    return () => clearTimeout(timeOutId);
  }, [query]);

  return (
    <>
      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
      />
      <p>{displayMessage}</p>
    </>
  );
}


问:
Visual Studio code makes React code weird
When I click 'save' on a React .js file in VSCode, the code changes form from this, for example:

```<code>import React from 'react';
const withClass = (WrappedComponent, className) => {
  return props => (
    <div className={className}>
      <WrappedComponent {...props}/>
    </div>
  );
};

export default withClass;
</code>```

to this:

```<code>import React from 'react';
const withClass = (WrappedComponent, className) => {
    return props => ( <
        div className = { className } >
        <
        WrappedComponent {...props }
        /> <
        /div>
    );
};

export default withClass;
</code>```

Why?

答: The reason was this extension: JS-CSS-HTML Formatter (by: lonefy)</p>

Body:
When I click 'save' on a React .js file in VSCode, the code changes form from this, for example:

import React from 'react';
const withClass = (WrappedComponent, className) => {
  return props => (

      <WrappedComponent {...props}/>

  );
};

export default withClass;

to this:

import React from 'react';
const withClass = (WrappedComponent, className) => {
    return props => ( <
        div className = { className } >
        <
        WrappedComponent {...props }
        /> <
        /div>
    );
};

export default withClass;

Why?


问:
Can someone show me how to create this very simple makefile?
This is in C, am running UNIX through Putty and want to create a Makefile.

So I have a program that is in only one file "recommender.c" and i need to make a makefile that creates an executable file called recommender using the all function. The part i don't know how to do is that i compile recommender.c using the line gcc recommender.c -std=gnu99
I don't know how to make sure it does the -std=gun99 part too. please help? :)

答: You don't even need a makefile;  CFLAGS="-std=gnu99" make recommender should "just work".


问:
Xamarin.iOS Notification Suggestion
Need to show notification in Xamarin.iOS app.

Calling web service at some interval when
application in background

Any better approach ?

Thanks in Advance !

答:
For this, you can use local notification. You can use below code where you are calling web service:

// create the notification

```<code>var notification = new UILocalNotification();

// set the fire date (the date time in which it will fire)
notification.FireDate = NSDate.FromTimeIntervalSinceNow(60);

// configure the alert
notification.AlertAction = "View Alert";
notification.AlertBody = "Your one minute alert has fired!";

// modify the badge
notification.ApplicationIconBadgeNumber = 1;

// set the sound to be the default sound
notification.SoundName = UILocalNotification.DefaultSoundName;

// schedule it
UIApplication.SharedApplication.ScheduleLocalNotification(notification);
</code>```

Title: Xamarin.iOS Notification Suggestion

Body:
For this, you can use local notification. You can use below code where you are calling web service:

// create the notification

var notification = new UILocalNotification();

// set the fire date (the date time in which it will fire)
notification.FireDate = NSDate.FromTimeIntervalSinceNow(60);

// configure the alert
notification.AlertAction = "View Alert";
notification.AlertBody = "Your one minute alert has fired!";

// modify the badge
notification.ApplicationIconBadgeNumber = 1;

// set the sound to be the default sound
notification.SoundName = UILocalNotification.DefaultSoundName;

// schedule it
UIApplication.SharedApplication.ScheduleLocalNotification(notification);


问:
What Jekyll syntax to filter key:value pair in Front Matter?
In my Jekyll site, I have a page that stores an array of data in front matter, like this:

```<code>---
layout: page
title: MyTitle
array:
  - key1: value1
  - key2: value2
---
</code>```

What I want to do in my template: given a keyX, obtain valueX from the array.

I figured out a way to access the array:

```<code>{% assign subpage = site.pages | where: 'title', 'MyTitle' %}
{% assign array = subpage[0].array %}
</code>```

Now the query that I need to write is: "from the array, extract the value that matches keyX".

Is there a way to search through the array, without the need for looping? All the examples I can find are based on one-dimensional arrays...

答:
I found this workaround in the meantime:

{% for valueList in array %}
  {% for valuePair in valueList %}
    {% if valuePair[0] ==  "key1" %}
      {% assign value = valuePair[1] %}
    {% endif %}
  {% endfor %}
{% endfor %}
```

Body:
In my Jekyll site, I have a page that stores an array of data in front matter, like this:

---
layout: page
title: MyTitle
array:
  - key1: value1
  - key2: value2
---

What I want to do in my template: given a keyX, obtain valueX from the array.

I figured out a way to access the array:

{% assign subpage = site.pages | where: 'title', 'MyTitle' %}
{% assign array = subpage[0].array %}

Now the query that I need to write is: "from the array, extract the value that matches keyX".

Is there a way to search through the array, without the need for looping? All the examples I can find are based on one-dimensional arrays...


问:
Using Webpack, how to dynamically load an external module built with another Webpack
Let's say I manage 2 JavaScript projects both built with Webpack:

A Website called User-Website

A JavaScript module called External-Module

Note that I'm using 2 separate projets for the same reasons described by the Micro Front end architecture.

I want my User-Website to be able to dynamically load External-Module on demand (using any JavaScript module technology). My User-Website knows at build-time the URL where to reach External-Module.

I can chose whatever technology is needed on both User-Website and External-Module.

I'm looking for a solution:

That is easy to implement (maybe JSONP that Webpack already handles to dynamically load chunks?)

That doesn't add to much overhead on both User-Website and External-Module (For example JavaScript modules looks good but requires a lot of polyfilling)

My question is related to https://github.com/webpack/webpack/issues/7526

I tried to use JSONP library output on my External-Module but I don't know how to load it in User-Website.

I'm also thinking about using the SystemJS in User-Website to dynamically load External-Module:

I could also replace internal JSONP mechanism with SystemJS within Webpack (to save having JSONP mechanism in m bundles).

SystemJS looks better and more modern than RequireJS

This will require to add SystemJS (s.js only) overhead.. I'm trying to use less dependencies as possible.

答:
I'm sorry if I did not get the question but I've recently made a project based on the article from the link You've provided.
Can't You just host both of the applications and load the part of chunk.js on the runtime ? It's how this particular article's example works. There is an example provided in the article. Some restaurant app with different microfrontends loaded dynamically on the runtime. Isn't it exactly what You need ?

Below code is the 'heart' of this particular example. Take a look.

componentDidMount() {
    const { name, host } = this.props;
    const scriptId = `micro-frontend-script-${name}`;

    if (document.getElementById(scriptId)) {
      this.renderMicroFrontend();
      return;
    }

    fetch(`${host}/asset-manifest.json`)
      .then(res => res.json())
      .then(manifest => {
        const script = document.createElement('script');
        script.id = scriptId;
        script.src = `${host}${manifest['main.js']}`;
        script.onload = this.renderMicroFrontend;
        document.head.appendChild(script);
      });
  }
```


问:
Why can't I cast DateTime[] to object[]?
It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?</p>

答:
BTW, you can accomplish this using Array.Copy()</p>

```<code>void Main()
{
    DateTime[] dates = new DateTime[] { new DateTime(2000, 1, 1), new DateTime (2000, 3, 25) };
    object[] objDates = new object[2];
    Array.Copy(dates, objDates, 2);

    foreach (object o in objDates) {
        Console.WriteLine(o);
    }
}
</code>```

Body:
BTW, you can accomplish this using Array.Copy()

void Main()
{
    DateTime[] dates = new DateTime[] { new DateTime(2000, 1, 1), new DateTime (2000, 3, 25) };
    object[] objDates = new object[2];
    Array.Copy(dates, objDates, 2);

    foreach (object o in objDates) {
        Console.WriteLine(o);
    }
}


问:
Form input type date-time returns a string instead of a date
In this sheet,

From the script editor we have an HTML form that submits dates and times into the sheet.

The purpose is to check with the calendar app if there is any events among the submitted time range.

The problem is that the calendar app is reading the submitted dates and times as a string/text, instead of dates and times and returns an error

Cannot find method getEvents(string,string)

I manually modified the inputs from 2020-02-21T18:00 into 2020-02-21 18:00:00, tested the code and it worked. So, I guess that the problem is with the format of the date-time values submitted by the form

The shared file is an editable version, feel free to edit and fix. Thanks in advance :)

Google Apps Script

```<code>function doPost (e) {
  Logger.log(JSON.stringify(e))

  if (!e || !e.parameter) {
    return;
  }

  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);

  try {

    // Form response sheet
    var doc = SpreadsheetApp.getActive();
    var sheet = doc.getSheetByName(sheetName);
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    // Get all events for the time range
    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("###");
    var allEvents = cal.getEvents(startTime, endTime);
    if (allEvents.length > 0) {
    return ContentService
    .createTextOutput(JSON.stringify('Not Available. Thanks'))
      .setMimeType(ContentService.MimeType.JSON)
    }else {
    return ContentService
    .createTextOutput(JSON.stringify('Available. Thanks'))
      .setMimeType(ContentService.MimeType.JSON)
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en">
<body>

<form name="Class1" id="Class1" action="https://script.google.com/macros/s/###/exec" target="_blank" method="POST">

Start Date & Time
<input type="datetime-local" required name="Start Date & Time">

End Date & Time
<input type="datetime-local" required name="End Date & Time">

<button type="submit">Check</button>

</form>

</body>
</html>
</code>```

答:
How about this modification? I think that in your script, the values of startTime and endTime are the string values of ISO8601. And at getEvents(startTime, endTime), startTime and endTime are required to be the date object. So I think that new Date() can be used.

Modified script:

When your script is modified, please modify as follows.

From:

```<code>var allEvents = cal.getEvents(startTime, endTime);
</code>```

To:

```<code>var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));
</code>```

Note:

When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected. Please be of careful this.

References:

ISO 8601

Date

getEvents(startTime, endTime)

If I misunderstood your question, and this was not the direction you want, I apologize.

Body:
In this sheet,

From the script editor we have an HTML form that submits dates and times into the sheet.

The purpose is to check with the calendar app if there is any events among the submitted time range.

The problem is that the calendar app is reading the submitted dates and times as a string/text, instead of dates and times and returns an error

Cannot find method getEvents(string,string)

I manually modified the inputs from 2020-02-21T18:00 into 2020-02-21 18:00:00, tested the code and it worked. So, I guess that the problem is with the format of the date-time values submitted by the form

The shared file is an editable version, feel free to edit and fix. Thanks in advance :)

Google Apps Script

function doPost (e) {
  Logger.log(JSON.stringify(e))

  if (!e || !e.parameter) {
    return;
  }

  var lock = LockService.getScriptLock();
  lock.tryLock(10 * 1000);

  try {

    // Form response sheet
    var doc = SpreadsheetApp.getActive();
    var sheet = doc.getSheetByName(sheetName);
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow() + 1;
    var newRow = headers.map(function(header) {
      return header === 'Timestamp' ? new Date() : e.parameter[header]
    });
    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);

    // Get all events for the time range
    var startTime = newRow[1];
    var endTime = newRow[2];
    var cal = CalendarApp.getCalendarById("###");
    var allEvents = cal.getEvents(startTime, endTime);
    if (allEvents.length > 0) {
    return ContentService
    .createTextOutput(JSON.stringify('Not Available. Thanks'))
      .setMimeType(ContentService.MimeType.JSON)
    }else {
    return ContentService
    .createTextOutput(JSON.stringify('Available. Thanks'))
      .setMimeType(ContentService.MimeType.JSON)
    };

  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

HTML:

<!DOCTYPE html>

<form name="Class1" id="Class1" action="https://script.google.com/macros/s/###/exec" target="_blank" method="POST">

Start Date & Time
<input type="datetime-local" required name="Start Date & Time">

End Date & Time
<input type="datetime-local" required name="End Date & Time">

<button type="submit">Check</button>

</form>

Body:
How about this modification? I think that in your script, the values of startTime and endTime are the string values of ISO8601. And at getEvents(startTime, endTime), startTime and endTime are required to be the date object. So I think that new Date() can be used.

Modified script:

When your script is modified, please modify as follows.

From:

var allEvents = cal.getEvents(startTime, endTime);

To:

var allEvents = cal.getEvents(new Date(startTime), new Date(endTime));

Note:

When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected. Please be of careful this.

References:

ISO 8601

Date

getEvents(startTime, endTime)

If I misunderstood your question, and this was not the direction you want, I apologize.


问:
How to include bootstrap css and js in reactjs app?
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

```<code>var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;
</code>```

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

答:
I too had a similar scenario. My setup was as indicated below

```<code>npm install create-react-app
</code>```

This will provide you with a boiler-plate code setup to begin. Play around with the App.js file for the main logic.

Later you can use bootstrap CDN in index.html created by the CLI tool.
or

```<code>npm install bootstrap popper jquery
</code>```

and then simply include this in the App.js file.

```<code>import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.bundle'
</code>```

Few authors have mentioned using className attribute instead of class, but in my case, both were working like below. But if you use class and look at console in developer tools on browser, you will see error for using class.So use className instead.

```<code>    <div className="App" class = "container"> //dont use class attribute
</code>```

And don't forget to remove the default CSS imports to avoid conflicts with bootstrap.

Hope that helps, Happy coding!!!

Body:
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

Body:
I too had a similar scenario. My setup was as indicated below

npm install create-react-app

This will provide you with a boiler-plate code setup to begin. Play around with the App.js file for the main logic.

Later you can use bootstrap CDN in index.html created by the CLI tool.
or

npm install bootstrap popper jquery

and then simply include this in the App.js file.

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.bundle'

Few authors have mentioned using className attribute instead of class, but in my case, both were working like below. But if you use class and look at console in developer tools on browser, you will see error for using class.So use className instead.

    <div className="App" class = "container"> //dont use class attribute

And don't forget to remove the default CSS imports to avoid conflicts with bootstrap.

Hope that helps, Happy coding!!!


问:
Finding a TextSpan to tap on with Flutter tests
With a Flutter WidgetTester how can you tap on a TextSpan, like in the code below?</p>

```<code>RichText(
  text: TextSpan(
    children: [
      TextSpan(text: 'aaa '),
      TextSpan(
        text: 'bbb ',
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            // How to reach this code in a widget test?
          },
      ),
      TextSpan(text: 'ccc'),
    ],
  ),
)
</code>```

答:
CommonFinders byWidgetPredicate method

InlineSpan visitChildren method

Find the TextSpan:

```<code>final finder = find.byWidgetPredicate(
  (widget) => widget is RichText && tapTextSpan(widget, "bbb "),
);
</code>```

```<code>bool findTextAndTap(InlineSpan visitor, String text) {
  if (visitor is TextSpan && visitor.text == text) {
    (visitor.recognizer as TapGestureRecognizer).onTap();

    return false;
  }

  return true;
}

bool tapTextSpan(RichText richText, String text) {
  final isTapped = !richText.text.visitChildren(
    (visitor) => findTextAndTap(visitor, text),
  );

  return isTapped;
}
</code>```

Body:
With a Flutter WidgetTester how can you tap on a TextSpan, like in the code below?

RichText(
  text: TextSpan(
    children: [
      TextSpan(text: 'aaa '),
      TextSpan(
        text: 'bbb ',
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            // How to reach this code in a widget test?
          },
      ),
      TextSpan(text: 'ccc'),
    ],
  ),
)

Body:
CommonFinders byWidgetPredicate method

InlineSpan visitChildren method

Find the TextSpan:

final finder = find.byWidgetPredicate(
  (widget) => widget is RichText && tapTextSpan(widget, "bbb "),
);

bool findTextAndTap(InlineSpan visitor, String text) {
  if (visitor is TextSpan && visitor.text == text) {
    (visitor.recognizer as TapGestureRecognizer).onTap();

    return false;
  }

  return true;
}

bool tapTextSpan(RichText richText, String text) {
  final isTapped = !richText.text.visitChildren(
    (visitor) => findTextAndTap(visitor, text),
  );

  return isTapped;
}


问:
How to compare a single value to an array using XSLT
I want to compare a single value if it's existing to an array. I have an XML input file:

```<code><wd:Report_Entry
    xmlns:wd="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice">
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>1</wd:pubbsType>
        <wd:pubbsService>A+</wd:pubbsService>
        <wd:validFrom>2019-08-01</wd:validFrom>
        <wd:validTo>2100-01-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2019-08-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>1</wd:pubbsType>
        <wd:pubbsService>A-</wd:pubbsService>
        <wd:validFrom>2019-08-01</wd:validFrom>
        <wd:validTo>2100-01-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2019-08-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>FMDAUTOPSY</wd:pubbsType>
        <wd:pubbsService>FMDAUTOPSY</wd:pubbsService>
        <wd:validFrom>2020-02-02</wd:validFrom>
        <wd:validTo>2020-02-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2020-02-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>FMDBODYSTOR</wd:pubbsType>
        <wd:pubbsService>FMDBODYSTOR</wd:pubbsService>
        <wd:validFrom>2020-01-01</wd:validFrom>
        <wd:validTo>2020-01-31</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2020-01-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2020-01-31</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
 <wd:Customer_Invoice_Lines_group>
        <wd:referenceID>CUSTOMER_INVOICE_LINE-6-46</wd:referenceID>
        <wd:Unit_Cost>0</wd:Unit_Cost>
        <wd:Quantity>0</wd:Quantity>
        <wd:Calculated_Tax_Amount>0</wd:Calculated_Tax_Amount>
        <wd:CFI_AC_Merchandise_Amount>100</wd:CFI_AC_Merchandise_Amount>
        <wd:Line_Item_Description>LINE ITEM DESC</wd:Line_Item_Description>
        <wd:Line_Memo>LINE MEMO</wd:Line_Memo>
        <wd:Transaction_Tax_Amount>0</wd:Transaction_Tax_Amount>
        <wd:CFI_LRV_Sales_Item_Reference_ID>FMDAUTOPSY</wd:CFI_LRV_Sales_Item_Reference_ID>
    </wd:Customer_Invoice_Lines_group>
    <wd:CFI_FD_PUBBS_HSA_Current_Date>2020-02-16</wd:CFI_FD_PUBBS_HSA_Current_Date>
</wd:Report_Entry>
</code>```

I want to know if the wd:CFI_LRV_Sales_Item_Reference_ID value is equal to wd:Customer_Invoice_Lines_group/wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService and wd:CFI_FD_PUBBS_HSA_Current_Date is greater than wd:CF_FD_PUBBS_HSA_Valid_To_Date and then just return a string value true if there is. I have a code like this but this doesn't work because I'm comparing a value to an object that has multiple values. Not sure how to do compare single value to an array using xslt 2 or 3.. Appreciate the help.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all" version="3.0"
    xmlns:wd="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice"
    xmlns:d9="urn:this-stylesheet">

    <xsl:output method="xml"/>

    <xsl:template match="/">
        <PUBBS>

            <xsl:for-each select="wd:Report_Entry/wd:Customer_Invoice_Lines_group">
                <xsl:if test="wd:CFI_LRV_Sales_Item_Reference_ID != ''">
                    <xsl:for-each select="../wd:CFI_ARI_PUBBS_HSA_group">
                        <xsl:if test="../wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService != ''
                            and wd:CFI_LRV_Sales_Item_Reference_ID = ../wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService
                            and xs:date(../wd:CFI_FD_PUBBS_HSA_Current_Date) > xs:date(../wd:CFI_ARI_PUBBS_HSA_group/wd:CF_FD_PUBBS_HSA_Valid_To_Date)
                            ">
                            <HASINVALIDSALESITEM>
                                <xsl:value-of select="'true'"/>
                            </HASINVALIDSALESITEM>
                        </xsl:if>
                    </xsl:for-each>
                </xsl:if>
            </xsl:for-each>
    </PUBBS>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
I have tried to simplify the code by using xpath-default-namespace and by using templates; I have also assumed the two values you want to compare the two details of the various CFI_ARI_PUBBS_HSA_group to only exist once in the input document:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:mode on-no-match="shallow-skip"/>

  <xsl:template match="/*">
      <PUBBS>
          <xsl:apply-templates select="CFI_ARI_PUBBS_HSA_group"/>
      </PUBBS>
  </xsl:template>

  <xsl:template match="CFI_ARI_PUBBS_HSA_group[xs:date(//CFI_FD_PUBBS_HSA_Current_Date) > xs:date(CF_FD_PUBBS_HSA_Valid_To_Date)
                       and
                       //CFI_LRV_Sales_Item_Reference_ID = pubbsService]">
     <HASINVALIDSALESITEM>true</HASINVALIDSALESITEM>
  </xsl:template>

</xsl:stylesheet>
</code>```

At https://xsltfiddle.liberty-development.net/jz1Q1ym that gives an empty <PUBBS/>, which seems the right result as the only CFI_ARI_PUBBS_HSA_group with pubbsService having the value FMDAUTOPSY has a CF_FD_PUBBS_HSA_Valid_To_Date of 2100-01-01 and the CFI_FD_PUBBS_HSA_Current_Date with the value 2020-02-16 is not greater than that.

It is not quite clear whether you want a single output of HASINVALIDSALESITEM even if there are several but the code could obviously adapted.

Body:
I want to compare a single value if it's existing to an array. I have an XML input file:

<wd:Report_Entry
    xmlns:wd="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice">
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>1</wd:pubbsType>
        <wd:pubbsService>A+</wd:pubbsService>
        <wd:validFrom>2019-08-01</wd:validFrom>
        <wd:validTo>2100-01-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2019-08-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>1</wd:pubbsType>
        <wd:pubbsService>A-</wd:pubbsService>
        <wd:validFrom>2019-08-01</wd:validFrom>
        <wd:validTo>2100-01-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2019-08-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>FMDAUTOPSY</wd:pubbsType>
        <wd:pubbsService>FMDAUTOPSY</wd:pubbsService>
        <wd:validFrom>2020-02-02</wd:validFrom>
        <wd:validTo>2020-02-01</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2020-02-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2100-01-01</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
    <wd:CFI_ARI_PUBBS_HSA_group>
        <wd:pubbsType>FMDBODYSTOR</wd:pubbsType>
        <wd:pubbsService>FMDBODYSTOR</wd:pubbsService>
        <wd:validFrom>2020-01-01</wd:validFrom>
        <wd:validTo>2020-01-31</wd:validTo>
        <wd:CF_FD_PUBBS_HSA_Valid_From_Date>2020-01-01</wd:CF_FD_PUBBS_HSA_Valid_From_Date>
        <wd:CF_FD_PUBBS_HSA_Valid_To_Date>2020-01-31</wd:CF_FD_PUBBS_HSA_Valid_To_Date>
    </wd:CFI_ARI_PUBBS_HSA_group>
 <wd:Customer_Invoice_Lines_group>
        <wd:referenceID>CUSTOMER_INVOICE_LINE-6-46</wd:referenceID>
        <wd:Unit_Cost>0</wd:Unit_Cost>
        <wd:Quantity>0</wd:Quantity>
        <wd:Calculated_Tax_Amount>0</wd:Calculated_Tax_Amount>
        <wd:CFI_AC_Merchandise_Amount>100</wd:CFI_AC_Merchandise_Amount>
        <wd:Line_Item_Description>LINE ITEM DESC</wd:Line_Item_Description>
        <wd:Line_Memo>LINE MEMO</wd:Line_Memo>
        <wd:Transaction_Tax_Amount>0</wd:Transaction_Tax_Amount>
        <wd:CFI_LRV_Sales_Item_Reference_ID>FMDAUTOPSY</wd:CFI_LRV_Sales_Item_Reference_ID>
    </wd:Customer_Invoice_Lines_group>
    <wd:CFI_FD_PUBBS_HSA_Current_Date>2020-02-16</wd:CFI_FD_PUBBS_HSA_Current_Date>
</wd:Report_Entry>

I want to know if the wd:CFI_LRV_Sales_Item_Reference_ID value is equal to wd:Customer_Invoice_Lines_group/wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService and wd:CFI_FD_PUBBS_HSA_Current_Date is greater than wd:CF_FD_PUBBS_HSA_Valid_To_Date and then just return a string value true if there is. I have a code like this but this doesn't work because I'm comparing a value to an object that has multiple values. Not sure how to do compare single value to an array using xslt 2 or 3.. Appreciate the help.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all" version="3.0"
    xmlns:wd="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice"
    xmlns:d9="urn:this-stylesheet">

    <xsl:output method="xml"/>

    <xsl:template match="/">
        <PUBBS>

            <xsl:for-each select="wd:Report_Entry/wd:Customer_Invoice_Lines_group">
                <xsl:if test="wd:CFI_LRV_Sales_Item_Reference_ID != ''">
                    <xsl:for-each select="../wd:CFI_ARI_PUBBS_HSA_group">
                        <xsl:if test="../wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService != ''
                            and wd:CFI_LRV_Sales_Item_Reference_ID = ../wd:CFI_ARI_PUBBS_HSA_group/wd:pubbsService
                            and xs:date(../wd:CFI_FD_PUBBS_HSA_Current_Date) > xs:date(../wd:CFI_ARI_PUBBS_HSA_group/wd:CF_FD_PUBBS_HSA_Valid_To_Date)
                            ">
                            <HASINVALIDSALESITEM>
                                <xsl:value-of select="'true'"/>
                            </HASINVALIDSALESITEM>
                        </xsl:if>
                    </xsl:for-each>
                </xsl:if>
            </xsl:for-each>
    </PUBBS>
    </xsl:template>
</xsl:stylesheet>

Body:
I have tried to simplify the code by using xpath-default-namespace and by using templates; I have also assumed the two values you want to compare the two details of the various CFI_ARI_PUBBS_HSA_group to only exist once in the input document:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:com.workday.report/CRI_-_INTSG031_CM_011_-_PUBBS_HSA_Customer_Invoice"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:mode on-no-match="shallow-skip"/>

  <xsl:template match="/*">
      <PUBBS>
          <xsl:apply-templates select="CFI_ARI_PUBBS_HSA_group"/>
      </PUBBS>
  </xsl:template>

  <xsl:template match="CFI_ARI_PUBBS_HSA_group[xs:date(//CFI_FD_PUBBS_HSA_Current_Date) > xs:date(CF_FD_PUBBS_HSA_Valid_To_Date)
                       and
                       //CFI_LRV_Sales_Item_Reference_ID = pubbsService]">
     <HASINVALIDSALESITEM>true</HASINVALIDSALESITEM>
  </xsl:template>

</xsl:stylesheet>

At https://xsltfiddle.liberty-development.net/jz1Q1ym that gives an empty <PUBBS/>, which seems the right result as the only CFI_ARI_PUBBS_HSA_group with pubbsService having the value FMDAUTOPSY has a CF_FD_PUBBS_HSA_Valid_To_Date of 2100-01-01 and the CFI_FD_PUBBS_HSA_Current_Date with the value 2020-02-16 is not greater than that.

It is not quite clear whether you want a single output of HASINVALIDSALESITEM even if there are several but the code could obviously adapted.


问:
CakePHP gets new tab after submit form
i am working on cakePHP framework and jQuery.My Doubt is when a form sumbmit using
  jQuery i ll get the result in new tab.Please help me

My form is :

```<code><?php echo $form->create('viewupdFiles', array('id'=>'viewFile', 'enctype'=>'multipart/form-data', 'url'=>'/Review/view'),array('target' => '_blank')); ?>
                                <a title="Click here to view File Status" target="_new" ><img src="../images/viewFile.jpg" alt=""width="21" height="21" id="view"></a>
                            <?php echo $html->tags['formend'];?>
</code>```

My JQuery code for form submit is :

```<code>$('#view').click(function(){
         $('#viewFile').target = "_new";
        $('#viewFile').submit();
    });
</code>```

答:
```<code>$(document).ready(function(){
    $('Form').attr("target", "_blank");
});
</code>```

Put this in your JS file, will add new attr in your form.
Enjoy ^^

Title: CakePHP gets new tab after submit form

Body:
i am working on cakePHP framework and jQuery.My Doubt is when a form sumbmit using
  jQuery i ll get the result in new tab.Please help me

My form is :

<?php echo $form->create('viewupdFiles', array('id'=>'viewFile', 'enctype'=>'multipart/form-data', 'url'=>'/Review/view'),array('target' => '_blank')); ?>

                            <?php echo $html->tags['formend'];?>

My JQuery code for form submit is :

$('#view').click(function(){
         $('#viewFile').target = "_new";
        $('#viewFile').submit();
    });

Body:
$(document).ready(function(){
    $('Form').attr("target", "_blank");
});

Put this in your JS file, will add new attr in your form.
Enjoy ^^


问:
Disable all breakpoints in RStudio
Is there a a way to disable all breakpoints in RStudio? I have looked at the RStudio documentation as well as done google searches but couldn't find a way.</p>

答:
It's right there under the Debug menu:

Default keyboard shortcut (on my system): Ctrl+Shift+F9

Title: Disable all breakpoints in RStudio


问:
AutoSizing in VisualStudio for Xamarin.iOS
Don't we have "AutoSizing" feature in VisualStudio for Xamarin.iOS?. I believe it's available in Xamarin Studio.</p>

答: If you are facing problem with Visual studio storyboard then open your storyboard in Xcode and do whatever you want, there you can do autosizing easily. I would prefer to use Xcode only for any UI creation instead of Visual Studio layout editor.</p>


问:
How to create a loop 1M with random numbers >100000
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

```<code>start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");
</code>```

This the gcd:

```<code>int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}
</code>```

答:
in gcd

you have an extra close brace

if x == y then z is undefined; so bad things can happen

Body:
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}


问:
"ImportError: No module named gtk" although it is installed
The following code fails although I have the gtk bindings for python installed. This is a debian machine and I have the package named python-gtk2 installed

```<code>>>> import gtk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named gtk
</code>```

How can I fix this?

Edit1: Per comment request: Python 2.7.3rc2 (default, May 22 2012, 01:05:47)

Edit2: Per comment request:

```<code>>>> print sys.path
['', '/home/lorb', '/usr/lib/python2.7/dist-packages', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages/SpssClient200', '/usr/local/lib/python2.7/site-packages/spss200']
</code>```

答:
Do this if you are using something other than Ubuntu 20:

```<code>sudo apt install python-gtk2 libcanberra-gtk-module libcanberra-gtk3-module
</code>```

And do this if you are using Ubuntu 20:

```<code>wget http://archive.ubuntu.com/ubuntu/pool/universe/p/pygtk/python-gtk2_2.24.0-5.1ubuntu2_amd64.deb && sudo dpkg -i python-gtk2_2.24.0-5.1ubuntu2_amd64.deb && sudo apt install --fix-broken && sudo dpkg -i python-gtk2_2.24.0-5.1ubuntu2_amd64.deb
</code>```

Body:
The following code fails although I have the gtk bindings for python installed. This is a debian machine and I have the package named python-gtk2 installed

>>> import gtk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named gtk

How can I fix this?

Edit1: Per comment request: Python 2.7.3rc2 (default, May 22 2012, 01:05:47)

Edit2: Per comment request:

>>> print sys.path
['', '/home/lorb', '/usr/lib/python2.7/dist-packages', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages/SpssClient200', '/usr/local/lib/python2.7/site-packages/spss200']

Body:
Do this if you are using something other than Ubuntu 20:

sudo apt install python-gtk2 libcanberra-gtk-module libcanberra-gtk3-module

And do this if you are using Ubuntu 20:

wget http://archive.ubuntu.com/ubuntu/pool/universe/p/pygtk/python-gtk2_2.24.0-5.1ubuntu2_amd64.deb && sudo dpkg -i python-gtk2_2.24.0-5.1ubuntu2_amd64.deb && sudo apt install --fix-broken && sudo dpkg -i python-gtk2_2.24.0-5.1ubuntu2_amd64.deb


问:
Number of days between today and a negative year ("-2580,01,01", today")
I need to calculate the number of days between two dates. One will be today and the other one is -2580,01,01.

I have tried with the datetime library but I can't because the datetime library don't accept negative years (MIN=1, MAX=9999).

I have tried with dateutil.relativedelta:

```<code>from datetime import *
from dateutil.relativedelta import *
import calendar

RightNOW = datetime.now() # with full time
JustTODAY = date.today() # only days

PastTime = JustTODAY+relativedelta(years=-4600)

print(PastTime)
</code>```

Traceback (most recent call last):
  File "GoblinTest.py", line 11, in <module>
    PastTime = JustTODAY+relativedelta(years=-4600)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)
ValueError: year -2580 is out of range
```

答:
Do a work around by accepting the limitations of the dateutil module and the datetime module.

Use years=1, and manually add in the previous days: 2581 * 365 = 942065.

This gives you limited accuracy; and you'd need to state, and account for, those assumptions in your application.

Body:
I need to calculate the number of days between two dates. One will be today and the other one is -2580,01,01.

I have tried with the datetime library but I can't because the datetime library don't accept negative years (MIN=1, MAX=9999).

I have tried with dateutil.relativedelta:

from datetime import *
from dateutil.relativedelta import *
import calendar

RightNOW = datetime.now() # with full time
JustTODAY = date.today() # only days

PastTime = JustTODAY+relativedelta(years=-4600)

print(PastTime)

Traceback (most recent call last):
  File "GoblinTest.py", line 11, in <module>
    PastTime = JustTODAY+relativedelta(years=-4600)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)
ValueError: year -2580 is out of range


问:
How do you set a default value for a MySQL Datetime column?
How do you set a default value for a MySQL Datetime column?

In SQL Server it's getdate(). What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.

答:
Working fine with MySQL 8.x    </p>

```<code>CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
      `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `mobile_UNIQUE` (`mobile`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
</code>```

OwnerDisplayName: brian

Body:
Working fine with MySQL 8.x

CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
      `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `mobile_UNIQUE` (`mobile`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;