问:
Update EmailSubject and EmailMessage in Cloud Formation config file
Anyone know if I can set the Email Subject and Email Message fields in my cloud formation template config file?

It appears in the AWS documentation that those fields are not available.

答:
There you go:

```<code>Resources:
  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: ${self:custom.service}-${self:custom.stage}-UserPool
      AdminCreateUserConfig:
        InviteMessageTemplate:
          EmailMessage: "Your username is {username} and temporary password is {####}."
          EmailSubject: "Your temporary password"
</code>```

There is a whole documentation about configuring it using CloudFormation
https://docs.amazonaws.cn/en_us/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html#cfn-cognito-userpool-invitemessagetemplate-emailmessage

Body:
There you go:

Resources:
  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: ${self:custom.service}-${self:custom.stage}-UserPool
      AdminCreateUserConfig:
        InviteMessageTemplate:
          EmailMessage: "Your username is {username} and temporary password is {####}."
          EmailSubject: "Your temporary password"

There is a whole documentation about configuring it using CloudFormation
https://docs.amazonaws.cn/en_us/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html#cfn-cognito-userpool-invitemessagetemplate-emailmessage


来源: stackexchange

问:
Dart and ASP.NET core ISO-8601 fractional seconds parsing incompatible
Evidently when using DateTime objects in ASP.NET core, JSON.Net serializes them out with 7 digits of accuracy.

Example:

```<code> "registrationDate": "2019-05-30T09:21:05.1676144-04:00",
</code>```

or

```<code>    "registrationDate": "2019-05-30T15:34:04.0929048Z",
</code>```

In Dart pad:

```<code> var t = DateTime.parse('2019-05-30T15:34:04.0929048Z');
</code>```

yields:

```<code>Uncaught exception:
FormatException: Invalid date format
2019-05-30T15:34:04.0929048Z
</code>```

but when I trim the last digit (an '8'):

```<code> var t = DateTime.parse('2019-05-30T15:34:04.092904Z');
</code>```

yields:

```<code>2019-05-30 15:34:04.093Z
</code>```

When consuming them in Dart from an API, Dart only accepts six digits of accuracy and throws an error when it encounters the 7th digit.

Here's the link to the Dart docs:
https://api.dartlang.org/stable/2.3.1/dart-core/DateTime/parse.html

Here's the relevant code from their docs:

```<code>  int parseMilliAndMicroseconds(String matched) {
     if (matched == null) return 0;
     int length = matched.length;
     assert(length >= 1);
     assert(length <= 6);
</code>```

It's unlikely there'll be a fix any time soon on the Dart side, as it's a pretty fundamental library.

So, can anyone tell me how to have my ASP.NET Core API reduce the accuracy by one digit?  These dates are everywhere in the system, and it would be really great if I could just change the formatted output from one spot.

I guess an alternative would be to write a JsonConverter but I really don't want to do that for every class.

Ideas?

TIA

答:
It seems there are two approaches, one is to use a CustomContractResolver from Json.Net.  I didn't pursue that because it occurred to me that I might end up needing those seven digits for comparisons in other places that weren't restricted like Dart is.

So instead I used a JsonConverter.  Here's the code:

```<code>public class DartDateTimeConverter : IsoDateTimeConverter
{
    public DartDateTimeConverter()
    {
        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
    }
}
</code>```

Note the 'F' positions are only 6 long.

I took this directly from another SO example.

I then updated my data transfer object to have the related attribute:

```<code>[JsonConverter(typeof(DartDateTimeConverter))]
[JsonProperty("registrationDate")]
public DateTime RegistrationDate { get; set; }
</code>```

Hope this helps someone.

ContentLicense: CC BY-SA 4.0

Body:
Evidently when using DateTime objects in ASP.NET core, JSON.Net serializes them out with 7 digits of accuracy.

Example:

 "registrationDate": "2019-05-30T09:21:05.1676144-04:00",

or

    "registrationDate": "2019-05-30T15:34:04.0929048Z",

In Dart pad:

 var t = DateTime.parse('2019-05-30T15:34:04.0929048Z');

yields:

Uncaught exception:
FormatException: Invalid date format
2019-05-30T15:34:04.0929048Z

but when I trim the last digit (an '8'):

 var t = DateTime.parse('2019-05-30T15:34:04.092904Z');

yields:

2019-05-30 15:34:04.093Z

When consuming them in Dart from an API, Dart only accepts six digits of accuracy and throws an error when it encounters the 7th digit.

Here's the link to the Dart docs:
https://api.dartlang.org/stable/2.3.1/dart-core/DateTime/parse.html

Here's the relevant code from their docs:

  int parseMilliAndMicroseconds(String matched) {
     if (matched == null) return 0;
     int length = matched.length;
     assert(length >= 1);
     assert(length <= 6);

It's unlikely there'll be a fix any time soon on the Dart side, as it's a pretty fundamental library.

So, can anyone tell me how to have my ASP.NET Core API reduce the accuracy by one digit?  These dates are everywhere in the system, and it would be really great if I could just change the formatted output from one spot.

I guess an alternative would be to write a JsonConverter but I really don't want to do that for every class.

Ideas?

TIA

Body:
It seems there are two approaches, one is to use a CustomContractResolver from Json.Net.  I didn't pursue that because it occurred to me that I might end up needing those seven digits for comparisons in other places that weren't restricted like Dart is.

So instead I used a JsonConverter.  Here's the code:

public class DartDateTimeConverter : IsoDateTimeConverter
{
    public DartDateTimeConverter()
    {
        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
    }
}

Note the 'F' positions are only 6 long.

I took this directly from another SO example.

I then updated my data transfer object to have the related attribute:

[JsonConverter(typeof(DartDateTimeConverter))]
[JsonProperty("registrationDate")]
public DateTime RegistrationDate { get; set; }

Hope this helps someone.


问:
Trouble installing Cufflinks in Anaconda in Windows 10
I'm having trouble installing Cufflinks in Anaconda in Windows 10.

I get the following error

```<code>C:\WINDOWS\system32>conda install cufflinks
Fetching package metadata .............

PackageNotFoundError: Package missing in current win-64 channels:
  - cufflinks
</code>```

答:
DRozen's solution is correct, but you can also use

```<code>pip install git+git://github.com/santosjorge/cufflinks.git
</code>```

to install your package. While not necessary here, this is useful for when you need to install modules directly from GitHub.

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble installing Cufflinks in Anaconda in Windows 10.

I get the following error

C:\WINDOWS\system32>conda install cufflinks
Fetching package metadata .............

PackageNotFoundError: Package missing in current win-64 channels:
  - cufflinks

Body:
DRozen's solution is correct, but you can also use

pip install git+git://github.com/santosjorge/cufflinks.git

to install your package. While not necessary here, this is useful for when you need to install modules directly from GitHub.


问:
Returning C++ const item, depending whether exists, safely
I have an std::unordered_map<uint64_t, Object> _map and I'd like to provide a read-only getter for clients.

Originally I thought of this:

```<code>bool foundItem(const uint64_t key, Object& object) const
{
    if(_map.find(key) != _map.end())
    {
        object = _map.at(key);
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

but obviously that isn't read-only, so I changed the signature to return the object and the bool can be passed by reference:

```<code>const Object& foundItem(const uint64_t key, bool& found) const
{
    if(_map.find(key) != _map.end())
    {
        found = true;
        return _map.at(key);
    }
    else
    {
        found = false;
        // What can I return here??
    }
}
</code>```

but now I have no type to return if the key is not found.

What is the best way to allow the user read-only access to the (maybe) returned object?

答:
You could return a pointer:

```<code>// Returns nullptr if not found
const Object* getItem(const uint64_t key) const
{
    auto it = _map.find(key);
    if (it == _map.end())
       return nullptr;

    return &it->second;
}
</code>```

Or you could return a std::optional, or you could return const Object& but throw an exception on lookup failure.

In all cases, be careful to document the expected lifetime of the result. In particular, you should comment which member functions will result in the result of this function being invalidated. Usually that'll be "any non-const function", like how std::string::c_str() is valid until you do mutatey things on the string.

Body:
I have an std::unordered_map<uint64_t, Object> _map and I'd like to provide a read-only getter for clients.

Originally I thought of this:

bool foundItem(const uint64_t key, Object& object) const
{
    if(_map.find(key) != _map.end())
    {
        object = _map.at(key);
        return true;
    }
    else
    {
        return false;
    }
}

but obviously that isn't read-only, so I changed the signature to return the object and the bool can be passed by reference:

const Object& foundItem(const uint64_t key, bool& found) const
{
    if(_map.find(key) != _map.end())
    {
        found = true;
        return _map.at(key);
    }
    else
    {
        found = false;
        // What can I return here??
    }
}

but now I have no type to return if the key is not found.

What is the best way to allow the user read-only access to the (maybe) returned object?

Body:
You could return a pointer:

// Returns nullptr if not found
const Object* getItem(const uint64_t key) const
{
    auto it = _map.find(key);
    if (it == _map.end())
       return nullptr;

    return &it->second;
}

Or you could return a std::optional, or you could return const Object& but throw an exception on lookup failure.

In all cases, be careful to document the expected lifetime of the result. In particular, you should comment which member functions will result in the result of this function being invalidated. Usually that'll be "any non-const function", like how std::string::c_str() is valid until you do mutatey things on the string.


问:
How to get jmDNS ServiceInfo description string
How to get description string of jmDNS ServiceInfo whitch we specify in 4 parameters of this overload:

```<code>ServiceInfo mServiceInfo = ServiceInfo.create(TYPE, SERVICE_NAME, PORT, DESCRIPTION);
</code>```

What method can I get value from DESCRIPTION variable of this instance.

Thanks in advance, regards...)

答:
The following website has the documentation for the ServiceInfo class. http://jmdns.sourceforge.net/apidocs/javax/jmdns/ServiceInfo.html

The method you're looking for is ServiceInfo.getNiceTextString(), which "Returns a description of the service info suitable for printing." This method returns the entire DESCRIPTION variable in a printable string. You can also use the getPropertyNames() method with the getPropertyBytes(String name) or getPropertyString(String name) methods to get specific TXT entries and their values. For instance, if your DESCRIPTION variable is "color=blue" then you can call ServiceInfo.getPropertyString("color") and it will return "blue".

Body:
How to get description string of jmDNS ServiceInfo whitch we specify in 4 parameters of this overload:

ServiceInfo mServiceInfo = ServiceInfo.create(TYPE, SERVICE_NAME, PORT, DESCRIPTION);

What method can I get value from DESCRIPTION variable of this instance.

Thanks in advance, regards...)


问:
Can I find the position of a given value in a Binary Search Tree better?
I need some help on how to find the (sorted) position of a given value in a Binary Search Tree better than I already did (if possible).

I have another method that searches for the i-th element of the tree and returns the node. So basically I solved the problem by searching through the tree until I find the given value or the node's data is bigger than the value I am searching for.

Our teacher gave us the algorithm on how to find the i-th element by knowing how many elements are there in that subtree. That is why I am wondering if my problem can be done in less steps?

Thanks in advance!

This is the not so optimal solution:

```<code>template <class T>
int BST<T>::Rang(const T& x) {

int meret = root->size;     //meret = size of the whole
                            //tree
Node<T>* temp = i_th_Node_rec(1, root);
int i = 1;
while (temp && i <= meret && x != temp->data && x < temp->data) {
    ++i;
    temp = i_th_Node_rec(i, root);
}

return (i < meret) ? i : -1;
}
</code>```

答:
It's very similar to how you locate the i:th node, but "in reverse".

If the element is in the root, its position is the size of the left subtree.

If the element is to the left, its position is the same as its position in that subtree.

If the element is to the right, its position is its position in that subtree, plus the size of the root's left subtree, plus one.

Body:
I need some help on how to find the (sorted) position of a given value in a Binary Search Tree better than I already did (if possible).

I have another method that searches for the i-th element of the tree and returns the node. So basically I solved the problem by searching through the tree until I find the given value or the node's data is bigger than the value I am searching for.

Our teacher gave us the algorithm on how to find the i-th element by knowing how many elements are there in that subtree. That is why I am wondering if my problem can be done in less steps?

Thanks in advance!

This is the not so optimal solution:

template <class T>
int BST<T>::Rang(const T& x) {

int meret = root->size;     //meret = size of the whole
                            //tree
Node<T>* temp = i_th_Node_rec(1, root);
int i = 1;
while (temp && i <= meret && x != temp->data && x < temp->data) {
    ++i;
    temp = i_th_Node_rec(i, root);
}

return (i < meret) ? i : -1;
}


问:
Does JavaScript have undefined behaviour?
Does JavaScript have undefined behaviour (similar to C) or is it completely well-defined by the spec, and deterministic?

Note that I am discarding implementation bugs and spec divergences. I am also discarding stuff like Math.random() and Date.now().

Is there a piece of JavaScript code for which the behaviour is not completely determined by the JavaScript specifications, and, as such, has "undefined behaviour"?

答:
Firstly, the ECMA-262 standard that defined the language informally known as JavaScript uses the terms "implementation-dependent" and "implementation-defined" without ever defining what these terms mean. Effectively, all those behaviors are undefined; no requirements are given about what should happen. An implementation that crashes or behaves unpredictably is conforming; certainly so if it documents that behavior: that crashing or erratic behavior is then what is defined by the implementation. By contrast, the ISO C standard formally defines terms like "unspecified behavior", "implementation-defined behavior" and "undefined behavior". These words actually mean something wherever they occur.

Secondly, the ECMA-262 standard is mum about implementation limits. That does not mean they are not there. For instance, can a Javascript program in a given specific implementation have any depth of recursion? Any number of function arguments? Any depth of lexical scoping? Can it allocate any number of objects? Certainly not, right? The word "limit" doesn't even appear anywhere in ECMA-262 2018, except as a function argument name. The document doesn't say, for instance, that a conforming implementation of ECMAScript must allow functions with 64 parmeters. Therefore, it comes to reason that implementations must support functions with any number of parameters thrown at them. If we make a function with ten million parameters, and the implementation crashes, it is nonconforming; nowhere does ECMA-262 state that such a failure is permitted. If a C compiler crashes due to ten million parameters in a function, we can squarely pinpoint that as an issue in the program: it is exceeding a minimum implementation limit documented in the standard, and thus fails to be strictly conforming (a formal term). This is a case of undefined behavior: it involves a non-portable program, for which the standard imposes no requirements (does not require implementations to handle that many function arguments).


问:
Using Smart Pointers
I am working on a legacy C++ app which has the following function,

```<code>char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}
</code>```

This function is called from many classes in the app and here's an example use case.

```<code>char * nodeID = obj.CreateNewString(process->GetNodeID());
</code>```

The app calls a different process and get a node ID as char pointer and then passes it to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what I observe, there's a definite memory leak here.

I think there're few ways of resolving this issue. But I want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So I came up with following function:

```<code>  char* CreateNewString (const char* node)
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }
</code>```

The goal is to keep function signature the same, i.e. it returns a char pointer, so that I don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is to:

Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way I am aware of is to dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way. BTW, I am not interested in exploring std::string at this point.

答:
This is kind of a hack, but it will work and you will not have a memory leak.  What you can do is add a static vector of smart pointers  and then when you call the function you store the pointer in the vector so that it won't go out of scope at the end of the function.  That would look like

```<code>char* CreateNewString (const char* node)
{
    std::size_t len = strlen(node) + 1;
    static std::vector<std::unique_ptr<char[]>> data_pool; // static pool, destroyed at end of program
    data_pool.push_back(std::unique_ptr<char[]>(new char [len]{})); // add pointer to pool
    strcpy_s(data_pool.back().get(), len, node); // copy the string
    return data_pool.back().get(); // return pointer to the managed data
}
</code>```

using a std::unique_ptr, which deletes arrays correctly so we don't need a custom deleter

Do note that using this solution you wont have a memory leak, but all of the allocated memory will last until the end of the program.  You don't gain anything, but at least you are guaranteed the memory is deallocated before the program terminates.

Title: Using Smart Pointers

Body:
I am working on a legacy C++ app which has the following function,

char* CreateNewString (const char* node)
{
   int len = (int) strlen(node) + 1;
   char * ptr = new char [len];
   strcpy_s(ptr, len, node);
   return ptr;
}

This function is called from many classes in the app and here's an example use case.

char * nodeID = obj.CreateNewString(process->GetNodeID());

The app calls a different process and get a node ID as char pointer and then passes it to CreateNewString function to dynamically allocate memory for a new string.

Nowhere in the app after the above call, it's deleting the memory. From what I observe, there's a definite memory leak here.

I think there're few ways of resolving this issue. But I want to explore using the smart pointers in C++11 first before trying anything else.

What I Tried:

So I came up with following function:

  char* CreateNewString (const char* node)
  {
       int len = (int) strlen(node) + 1;
       shared_ptr<char> ptr (new char [len](), [](char* p) {delete [] p;});
       strcpy_s(ptr.get(), len, node);
       return ptr.get();
    }

The goal is to keep function signature the same, i.e. it returns a char pointer, so that I don't have to make changes at all calling places.

The above is not working as ptr is released as it's declared inside the scope of this function.

My goal is to:

Use C++ 11 smart pointers to achieve this with minimum code changes to the existing application.

An alternative way I am aware of is to dynamically initialize array in calling places itself and then delete it before end of that scope. But I want to explore new C++ features before going back to traditional C++ way. BTW, I am not interested in exploring std::string at this point.

Body:
This is kind of a hack, but it will work and you will not have a memory leak.  What you can do is add a static vector of smart pointers  and then when you call the function you store the pointer in the vector so that it won't go out of scope at the end of the function.  That would look like

char* CreateNewString (const char* node)
{
    std::size_t len = strlen(node) + 1;
    static std::vector<std::unique_ptr<char[]>> data_pool; // static pool, destroyed at end of program
    data_pool.push_back(std::unique_ptr<char[]>(new char [len]{})); // add pointer to pool
    strcpy_s(data_pool.back().get(), len, node); // copy the string
    return data_pool.back().get(); // return pointer to the managed data
}

using a std::unique_ptr, which deletes arrays correctly so we don't need a custom deleter

Do note that using this solution you wont have a memory leak, but all of the allocated memory will last until the end of the program.  You don't gain anything, but at least you are guaranteed the memory is deallocated before the program terminates.


问:
React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
I'm trying to use react hooks for a simple problem

```<code>const [personState,setPersonState] = useState({ DefinedObject });
</code>```

with following dependencies.

```<code>"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.0"
}
</code>```

but I'm still getting the following error:

./src/App.js

Line 7:

  React Hook "useState" is called in function
  "app" which is neither a React function component or a custom React
  Hook function  react-hooks/rules-of-hooks

Line 39:

  'state' is not defined

  no-undef

Search for the keywords to learn more about each error.

Component code is below:

```<code>import React, {useState} from 'react';
import './App.css';
import Person from './Person/Person';

const app = props => {
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], });
    return (
        <div className="App">
            <h2>This is react</h2>
            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person>
        </div> );
    };
    export default app;
</code>```

Person component

```<code>import React from 'react';

const person = props => {
    return(
        <div>
            <h3>i am {props.name}</h3>
            <p>i am {props.age} years old</p>
            <p>{props.children}</p>
        </div>
    )
};

export default person;
</code>```

答:
I had the same issue, but not with the App. I had a custom class but used a lowercase letter to start the function name and also received the error.

Changed the first letter of the function name and the export line to CamelCase and error gone.

in my case the end result was something like:

```<code>function Document() {
....
}
export default Document;
</code>```

this solved my problem.

Body:
I'm trying to use react hooks for a simple problem

const [personState,setPersonState] = useState({ DefinedObject });

with following dependencies.

"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.0"
}

but I'm still getting the following error:

./src/App.js

Line 7:

  React Hook "useState" is called in function
  "app" which is neither a React function component or a custom React
  Hook function  react-hooks/rules-of-hooks

Line 39:

  'state' is not defined

  no-undef

Search for the keywords to learn more about each error.

Component code is below:

import React, {useState} from 'react';
import './App.css';
import Person from './Person/Person';

const app = props => {
    const [personState, setPersonSate] = useState({ person:[ {name:'bishnu',age:'32'}, {name:'rasmi',age:'27'}, {name:'fretbox',age:'4'} ], });
    return (

This is react

            <Person name={personState.person[1].name} age="27"></Person>
            <Person name={personState.person[2].name} age="4"></Person>

 );
    };
    export default app;

Person component

import React from 'react';

const person = props => {
    return(

i am {props.name}

i am {props.age} years old

{props.children}

    )
};

export default person;

Body:
I had the same issue, but not with the App. I had a custom class but used a lowercase letter to start the function name and also received the error.

Changed the first letter of the function name and the export line to CamelCase and error gone.

in my case the end result was something like:

function Document() {
....
}
export default Document;

this solved my problem.


问:
Requery Listbox on secondary form when another form is closed
I have two forms, frmOwnership and frmContactDetails.  On frmOwnership you can click a button to open frmContactDetails to a specific record.

The issue I'm having is frmContactDetails is opened from several different sources, and doesn't designate (and can't really?) a form to open when it's closed.  And frmOwnership is not openable from frmContactDetails, meaning when you go to edit a record in the Contact Details, the Ownership form stays open.  However, I'm looking to refresh a control (lstItem) on frmOwnership when frmContactDetails is closed.  I tried to add a requery call (lstItem.Requery) to the Got_Focus procedure, but it's not refreshing.

Thanks!!

答: The easiest thing to do is open frmContactDetails with acDialog (as a popup on top of whatever other form is opening it). Then whatever VBA code opens it on the original form only continues after frmContactDetails is closed and you can put your refresh there.


问:
What is the difference between |+ and |- when creating a configmap from a file in kubernetes yaml definitions?
i've came across 2 types of syntax for creating configmaps from files in kubernetes.

first one ;

```<code>apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap
</code>```

second one ;

```<code>apiVersion: v1
data:
  file1.yaml: | -
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap
</code>```

what is the difference between |+ and |- ?

答:
These are block chomping indicators, they influence how the trailing newlines in a literal (|) or folded (>) block style scalar are handled.

By default, if there is no + or - after the | (or >), those trailing newlines are clipped, i.e. the scalar will be loaded as a string ending in a single newline, independent of whether there are multiple empty lines at the end of the scalar.

If + is specified, each newline is kept, so the scalar will have one extra newline for every empty line before the outdent for the next node (in addition to the one ending the last non-empty line)

If - is specified, the scalar is stripped and will not end in a newline, even if there are multiple empty lines at the end of the block style scalar.

Please note that your second example is invalid, the production rules indicate that the chomping indicator can only be separated from the | by the indentation indicator (i.e. number, if specified) and that no space is allowed between | and -.

Body:
i've came across 2 types of syntax for creating configmaps from files in kubernetes.

first one ;

apiVersion: v1
data:
  file1.yaml: |+
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap

second one ;

apiVersion: v1
data:
  file1.yaml: | -
    parameter1=value1
kind: ConfigMap
metadata:
  name: my-configmap

what is the difference between |+ and |- ?


问:
Is it possible to view secret variable declared in angular in browser, after build and run?
I want to use an a decryption algorithm on the data I receive through REST-API, for that I am storing the secret-key in angular component ts file.

I want to know that after I build and deploy the code. Will my secret key be visible somewhere in the browser, because the built code is pure javascript which is fetched by server.

I am using crypto-js library for decryption of data.

```<code>var secret_key = "super-secret";

CryptoJS.AES.decrypt(ciphertext, secret_key)
</code>```

答:
If you can explain the situation why you need it, may be a chance you can get better way to do it.

There are 3 different ways to achieve it :-

Pass roles/permissions to local storage as well as same time put into session table(or any other table) in backend. Check role/permission every time user request for something to make sure it is not modified.

Store the roles/permission in backend e.g in session table and then provide roles/permission on every request. This way you do not have to worry about any modification by user anytime.

Pass the encrypted (RSA algorithm)roles/permission in cookies and make cookie httpOnly true and secure true, these cookies cannot be accessed/modified as per protocol and then in each request you will have

Body:
I want to use an a decryption algorithm on the data I receive through REST-API, for that I am storing the secret-key in angular component ts file.

I want to know that after I build and deploy the code. Will my secret key be visible somewhere in the browser, because the built code is pure javascript which is fetched by server.

I am using crypto-js library for decryption of data.

var secret_key = "super-secret";

CryptoJS.AES.decrypt(ciphertext, secret_key)


问:
How to resolve incorrect return result from Ramda reduce function (javascript)
I have a data structure I call a 'spec' which looks like this:

```<code>const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};
</code>```

So the elements inside of command and arguments are properties mapped to paths. The best illustration of this is spec.command.arguments. What I need to do is translate this into another object with the same shape, but the paths are converted into Ramda lenses (using R.lensPath).

So conceptually, this is translated into something like this:

```<code>const spec = {
  command: {
    name: lens('name'),
    description: lens('description'),
    alias: lens('alias'),
    arguments: lens('_children/Arguments')
  },
  arguments: {
    name: lens('name'),
    alias: lens('alias'),
    optional: lens('optional'),
    description: lens('description')
  }
};
</code>```

The above is not meant to be taken literally, it is a pseudo structure. For example lens('_children/Arguments') just represents a lens built using Ramda lensPath.

So here is my code:

```<code>const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};

function lensify (spec) {
  const result = R.pipe(
    R.toPairs,
    R.reduce((acc, pair) => {
      const field = pair[0];
      const path = pair[1];
      const lens = R.compose(
        R.lensPath,
        R.split('/')
      )(path);

      acc[field] = lens; // Is there something wrong with this, if so what?
      return acc;
    }, { dummy: '***' }) // list of pairs passed as last param here
  )(spec);

  // The following log should show entries for 'name', 'description', 'alias' ...
  console.log(`+++ lensify RESULT: ${JSON.stringify(result)}`);
  return result;
}

function makeLenses (spec) {
  const result = {
    command: lensify(spec.command),
    arguments: lensify(spec.arguments)
  };

  return result;
}

makeLenses(spec);
</code>```

The key point of failure I think is inside the reducer function, which returns the updated accumulator (acc[field] = lens;). For some reason which I can't understand, this assignment is being lost, and the accumulator is not being correctly populated on each iteration. As you can see from the code sample, the initial value passed into reduce is an object with a single dummy property. The result of the reduce is incorrectly just this single dummy value and not all the fields with their respective Ramda lenses.

However, what's really gonna bake your noodle is that the exact same code running in Ramda repl exhibits different behaviour, see this code in the repl at: Ramda code

I'm running node version 10.13.0

The result that the Repl code produces is this:

```<code>{
  'arguments': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'optional': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  },
  'command': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'arguments': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  }
}
</code>```

As you can see, the result looks a bit complicated because the values of each property is the lens created by lensProp.

This is in contrast to the following (note that order of command and arguments is reversed, but this shouldn't be significant):

```<code>{
  'command': {
    'dummy': '***'
  },
  'arguments': {
    'dummy': '***'
  }
}
</code>```

which is being returned in my unit test.

I've wasted about 2 days on this and have now admitted defeat, so hopefully, somebody can shed some light on this. Cheers.

答:
This shows the simplest usage of your output I can imagine, mapping view on the lenses against a common object.  It seems to work properly both in the REPL, here in a snippet, and in Node 10.13.0:

const {map, pipe, split, lensPath, view} = ramda

const makeLenses = map ( map ( pipe ( split ('/'), lensPath )))

const applyLensSpec = (lensSpec) => (obj) =>
  map ( map ( f => view (f, obj) ), lensSpec)

const spec = {command: {name: "name", description: "description", alias: "alias", arguments: "_children/Arguments"}, arguments: {name: "name", alias: "alias", optional: "optional", description: "description"}};

const myTransform = applyLensSpec(
  makeLenses(spec),
)

const testObj =   {
  name: 'foo',
  alias: 'bar',
  description: 'baz',
  optional: false,
  _children: {
    Arguments: ['qux', 'corge']
  }
}

console .log (
  myTransform (testObj)
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://bundle.run/ramda@0.26.1"></script></code>```

Body:
I have a data structure I call a 'spec' which looks like this:

const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};

So the elements inside of command and arguments are properties mapped to paths. The best illustration of this is spec.command.arguments. What I need to do is translate this into another object with the same shape, but the paths are converted into Ramda lenses (using R.lensPath).

So conceptually, this is translated into something like this:

const spec = {
  command: {
    name: lens('name'),
    description: lens('description'),
    alias: lens('alias'),
    arguments: lens('_children/Arguments')
  },
  arguments: {
    name: lens('name'),
    alias: lens('alias'),
    optional: lens('optional'),
    description: lens('description')
  }
};

The above is not meant to be taken literally, it is a pseudo structure. For example lens('_children/Arguments') just represents a lens built using Ramda lensPath.

So here is my code:

const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};

function lensify (spec) {
  const result = R.pipe(
    R.toPairs,
    R.reduce((acc, pair) => {
      const field = pair[0];
      const path = pair[1];
      const lens = R.compose(
        R.lensPath,
        R.split('/')
      )(path);

      acc[field] = lens; // Is there something wrong with this, if so what?
      return acc;
    }, { dummy: '***' }) // list of pairs passed as last param here
  )(spec);

  // The following log should show entries for 'name', 'description', 'alias' ...
  console.log(`+++ lensify RESULT: ${JSON.stringify(result)}`);
  return result;
}

function makeLenses (spec) {
  const result = {
    command: lensify(spec.command),
    arguments: lensify(spec.arguments)
  };

  return result;
}

makeLenses(spec);

The key point of failure I think is inside the reducer function, which returns the updated accumulator (acc[field] = lens;). For some reason which I can't understand, this assignment is being lost, and the accumulator is not being correctly populated on each iteration. As you can see from the code sample, the initial value passed into reduce is an object with a single dummy property. The result of the reduce is incorrectly just this single dummy value and not all the fields with their respective Ramda lenses.

However, what's really gonna bake your noodle is that the exact same code running in Ramda repl exhibits different behaviour, see this code in the repl at: <a href="https://ramdajs.com/repl/#?const%20spec%20%3D%20%7B%0A%20%20command%3A%20%7B%0A%20%20%20%20name%3A%20%27name%27%2C%0A%20%20%20%20description%3A%20%27description%27%2C%0A%20%20%20%20alias%3A%20%27alias%27%2C%0A%20%20%20%20arguments%3A%20%27_children%2FArguments%27%0A%20%20%7D%2C%0A%20%20arguments%3A%20%7B%0A%20%20%20%20name%3A%20%27name%27%2C%0A%20%20%20%20alias%3A%20%27alias%27%2C%0A%20%20%20%20optional%3A%20%27optional%27%2C%0A%20%20%20%20description%3A%20%27description%27%0A%20%20%7D%0A%7D%3B%0A%0Afunction%20lensify%20%28spec%29%20%7B%0A%20%20const%20result%20%3D%20R.pipe%28%0A%20%20%20%20R.toPairs%2C%0A%20%20%20%20R.reduce%28%28acc%2C%20pair%29%20%3D%3E%20%7B%0A%20%20%20%20%20%20const%20field%20%3D%20pair%5B0%5D%3B%0A%20%20%20%20%20%20const%20path%20%3D%20pair%5B1%5D%3B%0A%20%20%20%20%20%20const%20lens%20%3D%20R.compose%28%0A%20%20%20%20%20%20%20%20R.lensPath%2C%0A%20%20%20%20%20%20%20%20R.split%28%27%2F%27%29%0A%20%20%20%20%20%20%29%28path%29%3B%0A%20%20%20%20%20%20%0A%20%20%20%20%20%20acc%5Bfield%5D%20%3D%20lens%3B%20%2F%2F%20Is%20there%20something%20wrong%20with%20this%2C%20if%20so%20what%3F%0A%20%20%20%20%20%20return%20acc%3B%0A%20%20%20%20%7D%2C%20%7B%20dummy%3A%20%27%2A%2A%2A%27%20%7D%29%20%2F%2F%20list%20of%20pairs%20passed%20as%20last%20param%20here%0A%20%20%29%28spec%29%3B%0A%0A%20%20%2F%2F%20The%20following%20log%20should%20show%20entries%20for%20%27name%27%2C%20%27description%27%2C%20%27alias%27%20...%0A%20%20console.log%28%60%2B%2B%2B%20lensify%20RESULT%3A%20%24%7BJSON.stringify%28result%29%7D%60%29%3B%0A%20%20return%20result%3B%0A%7D%0A%0Afunction%20makeLenses%20%28spec%29%20%7B%0A%20%20const%20result%20%3D%20%7B%0A%20%20%20%20command%3A%20lensify%28spec.command%29%2C%0A%20%20%20%20arguments%3A%20lensify%28spec.arguments%29%0A%20%20%7D%3B%0A%20%20%0A%20%20return%20result%3B%0A%7D%0A%0AmakeLenses%28spec%29%3B%0A%0A" rel="nofollow noreferrer">Ramda code

I'm running node version 10.13.0

The result that the Repl code produces is this:

{
  'arguments': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'optional': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  },
  'command': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'arguments': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  }
}

As you can see, the result looks a bit complicated because the values of each property is the lens created by lensProp.

This is in contrast to the following (note that order of command and arguments is reversed, but this shouldn't be significant):

{
  'command': {
    'dummy': '***'
  },
  'arguments': {
    'dummy': '***'
  }
}

which is being returned in my unit test.

I've wasted about 2 days on this and have now admitted defeat, so hopefully, somebody can shed some light on this. Cheers.

Body:
This shows the simplest usage of your output I can imagine, mapping view on the lenses against a common object.  It seems to work properly both in the REPL, here in a snippet, and in Node 10.13.0:

const {map, pipe, split, lensPath, view} = ramda

const makeLenses = map ( map ( pipe ( split ('/'), lensPath )))

const applyLensSpec = (lensSpec) => (obj) =>
  map ( map ( f => view (f, obj) ), lensSpec)

const spec = {command: {name: "name", description: "description", alias: "alias", arguments: "_children/Arguments"}, arguments: {name: "name", alias: "alias", optional: "optional", description: "description"}};

const myTransform = applyLensSpec(
  makeLenses(spec),
)

const testObj =   {
  name: 'foo',
  alias: 'bar',
  description: 'baz',
  optional: false,
  _children: {
    Arguments: ['qux', 'corge']
  }
}

console .log (
  myTransform (testObj)
)

<script src="https://bundle.run/ramda@0.26.1"></script>


问:
Extend contigency table with proportions (percentages)
I have a contingency table of counts, and I want to extend it with corresponding proportions of each group.

Some sample data (tips data set from ggplot2 package):

```<code>library(ggplot2)

head(tips, 3)
#   total_bill tip    sex smoker day   time size
# 1         17 1.0 Female     No Sun Dinner    2
# 2         10 1.7   Male     No Sun Dinner    3
# 3         21 3.5   Male     No Sun Dinner    3
</code>```

First, use table to count smoker vs non-smoker, and nrow to count total number of subjects:

```<code>table(tips$smoker)
#  No Yes
# 151  93

nrow(tips)
# [1] 244
</code>```

Then, I want to calculate percentage of smokers vs. non smokers. Something like this (ugly code):

```<code># percentage of smokers
options(digits = 2)

transform(as.data.frame(table(tips$smoker)), percentage_column = Freq / nrow(tips) * 100)
#   Var1 Freq percentage_column
# 1   No  151                62
# 2  Yes   93                38
</code>```

Is there a better way to do this?

(even better it would be to do this on a set of columns (which I enumerate) and have output somewhat nicely formatted)
(e.g., smoker, day, and time)

答:
Here's a tidyverse version:

```<code>library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))
</code>```

Or if you want a handy function:

```<code>getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>%
    table() %>%
    as.data.frame() %>%
    rename({{colName}} :=1, Freq=2) %>%
    mutate(Perc=100*Freq/sum(Freq))
}
</code>```

Now you can do:

```<code>diamonds %>% getPercentages(cut)
</code>```

or this:

```<code>df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)
</code>```

Body:
I have a contingency table of counts, and I want to extend it with corresponding proportions of each group.

Some sample data (tips data set from ggplot2 package):

library(ggplot2)

head(tips, 3)
#   total_bill tip    sex smoker day   time size
# 1         17 1.0 Female     No Sun Dinner    2
# 2         10 1.7   Male     No Sun Dinner    3
# 3         21 3.5   Male     No Sun Dinner    3

First, use table to count smoker vs non-smoker, and nrow to count total number of subjects:

table(tips$smoker)
#  No Yes
# 151  93

nrow(tips)
# [1] 244

Then, I want to calculate percentage of smokers vs. non smokers. Something like this (ugly code):

# percentage of smokers
options(digits = 2)

transform(as.data.frame(table(tips$smoker)), percentage_column = Freq / nrow(tips) * 100)
#   Var1 Freq percentage_column
# 1   No  151                62
# 2  Yes   93                38

Is there a better way to do this?

(even better it would be to do this on a set of columns (which I enumerate) and have output somewhat nicely formatted)
(e.g., smoker, day, and time)

Body:
Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>%
    table() %>%
    as.data.frame() %>%
    rename({{colName}} :=1, Freq=2) %>%
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)


问:
Add numbers to filename
I want to store data in different files. Therefore I want to create files as follows: data_1.log, data_2.log, ..., data_N.log. The appendix .log is not necessary but would be nice. All my approaches failed so far. Here is one sample that is probably close to what I need:

```<code>#include <stdio.h>
#include <string.h>

char get_file_name(int k){
    int i, j;
    char s1[100] = "logs/data_";
    char s2[100];
    snprintf(s2, 100, "%d", k);
    for(i = 0; s1[i] != '\0'; ++i);
    for(j = 0; s2[j] != '\0'; ++j, ++i){
        s1[i] = s2[j];
    }
    s1[i] = '\0';
    return s1;
}

int main(){

    char file_name[100];
    for(int k=0; k<10; k++){
        // Get data
        // ...
        // Create filename
        strcpy(file_name, get_file_name(k));
        printf("%s", file_name);
        // fp = fopen(file_name, "w+");
        // Write data to file
        // print_results_to_file();
        // fclose(fp);
    }

    return 0;
}
</code>```

At the moment I get the following errors which I don't understand:

```<code>    string.c: In function ‘get_file_name’:
string.c:14:12: warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]
     return s1;
            ^~
string.c:14:12: warning: function returns address of local variable [-Wreturn-local-addr]
string.c: In function ‘main’:
string.c:24:27: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
         strcpy(file_name, get_file_name(k));
                           ^~~~~~~~~~~~~~~~
In file included from string.c:2:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^~~~~~
</code>```

Is there a more simpler way to create such filenames? I can't believe that there isn't one.

答:
There are various issues with this code and rather than correcting them one by one here’s an alternative approach. It’s not the only one but it’s simple and should be easy to understand and adapt:

#include <stdio.h>

void get_file_name(int k, char* buffer, size_t buflen) {
    snprintf(buffer, buflen, "logs/data_%d.log", k);
}

int main() {
    const size_t BUFLEN = 50;
    char file_name[BUFLEN];

    for (int i = 0; i < 10; i++) {
        get_file_name(i, file_name, BUFLEN);
        printf("%s\n", file_name);
        // Code for writing to file.
    }
}
```

A few details:

Rather than attempting to return (pointers to) memory, this function passes a buffer that is written to. It’s up to the caller to ensure that the buffer is big enough (this is always the case here, but if the actual filenames are longer, you should add logic that inspects the return value of snprintf and performs appropriate error handling).

The actual logic of the function requires only a single call to snprintf, which already performs everything you require, so it’s unclear whether having a separate function is even necessary or helpful.

The above uses variable-length arrays. If you want to ensure constant buffers, you can use a #define instead of a const size_t variable for the buffer length. However, using a variable-length array here is fine, and some compilers even convert it into a constant array.

As mentioned in comments, it’s important that you (a) read and understand the documentation of the functions you’re using, and (b) read and understand the compiler error messages.

Title: Add numbers to filename

Body:
I want to store data in different files. Therefore I want to create files as follows: data_1.log, data_2.log, ..., data_N.log. The appendix .log is not necessary but would be nice. All my approaches failed so far. Here is one sample that is probably close to what I need:

#include <stdio.h>
#include <string.h>

char get_file_name(int k){
    int i, j;
    char s1[100] = "logs/data_";
    char s2[100];
    snprintf(s2, 100, "%d", k);
    for(i = 0; s1[i] != '\0'; ++i);
    for(j = 0; s2[j] != '\0'; ++j, ++i){
        s1[i] = s2[j];
    }
    s1[i] = '\0';
    return s1;
}

int main(){

    char file_name[100];
    for(int k=0; k<10; k++){
        // Get data
        // ...
        // Create filename
        strcpy(file_name, get_file_name(k));
        printf("%s", file_name);
        // fp = fopen(file_name, "w+");
        // Write data to file
        // print_results_to_file();
        // fclose(fp);
    }

    return 0;
}

At the moment I get the following errors which I don't understand:

    string.c: In function ‘get_file_name’:
string.c:14:12: warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]
     return s1;
            ^~
string.c:14:12: warning: function returns address of local variable [-Wreturn-local-addr]
string.c: In function ‘main’:
string.c:24:27: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
         strcpy(file_name, get_file_name(k));
                           ^~~~~~~~~~~~~~~~
In file included from string.c:2:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘char’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^~~~~~

Is there a more simpler way to create such filenames? I can't believe that there isn't one.

Body:
There are various issues with this code and rather than correcting them one by one here’s an alternative approach. It’s not the only one but it’s simple and should be easy to understand and adapt:

#include <stdio.h>

void get_file_name(int k, char* buffer, size_t buflen) {
    snprintf(buffer, buflen, "logs/data_%d.log", k);
}

int main() {
    const size_t BUFLEN = 50;
    char file_name[BUFLEN];

    for (int i = 0; i < 10; i++) {
        get_file_name(i, file_name, BUFLEN);
        printf("%s\n", file_name);
        // Code for writing to file.
    }
}

A few details:

Rather than attempting to return (pointers to) memory, this function passes a buffer that is written to. It’s up to the caller to ensure that the buffer is big enough (this is always the case here, but if the actual filenames are longer, you should add logic that inspects the return value of snprintf and performs appropriate error handling).

The actual logic of the function requires only a single call to snprintf, which already performs everything you require, so it’s unclear whether having a separate function is even necessary or helpful.

The above uses variable-length arrays. If you want to ensure constant buffers, you can use a #define instead of a const size_t variable for the buffer length. However, using a variable-length array here is fine, and some compilers even convert it into a constant array.

As mentioned in comments, it’s important that you (a) read and understand the documentation of the functions you’re using, and (b) read and understand the compiler error messages.


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答:
A token is whatever you want it to be.  Traditionally (and for
good reasons), language specifications broke the analysis into
two parts: the first part broke the input stream into tokens,
and the second parsed the tokens.  (Theoretically, I think you
can write any grammar in only a single level, without using
tokens—or what is the same thing, using individual
characters as tokens.  I wouldn't like to see the results of
that for a language like C++, however.)  But the definition of
what a token is depends entirely on the language you are
parsing: most languages, for example, treat white space as
a separator (but not Fortran); most languages will predefine
a set of punctuation/operators using punctuation characters, and
not allow these characters in symbols (but not COBOL, where
"abc-def" would be a single symbol).  In some cases (including
in the C++ preprocessor), what is a token depends on context, so
you may need some feedback from the parser.  (Hopefully not;
that sort of thing is for very experienced programmers.)

One thing is probably sure (unless each character is a token):
you'll have to read ahead in the stream.  You typically can't
tell whether there are more tokens by just looking at a single
character.  I've generally found it useful, in fact, for the
tokenizer to read a whole token at a time, and keep it until the
parser needs it.  A function like hasMoreTokens would in fact
scan a complete token.

(And while I'm at it, if source is an istream:
istream::peek does not return a pointer, but an int.)

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}


问:
compare two lists to get non matching elements
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

```<code>len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890
</code>```

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

答:
You can use sets to more efficiently find the difference between both lists. If you need to keep the order in the original list you can use sorted with a key.

We want to sort the elements in the set according to their appearance in the original list, so one way is to build a lookup dictionary. We can use enumerate for that. Then we only need to lookup on the dictionary as a key function:

```<code>d = {j:i for i,j in enumerate(h)}
new_list  = sorted(list((set(h) - set(y))), key = lambda x: d[x])
</code>```

Let's try with a simple example:

```<code>y = range(5)
h = range(7)
d = {j:i for i,j in enumerate(h)}
sorted(list((set(h) - set(y))), key = lambda x: d[x])
# [5, 6]
</code>```

Timings -

```<code>import random
y = random.sample(range(1, 10001), 10000)
h = random.sample(range(1, 20001), 10000)

%timeit [i for i in h if i not in y]
# 1.28 s ± 37.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def using_sets(a,b):
    d = {j:i for i,j in enumerate(a)}
    sorted(list((set(a) - set(b))), key = lambda x: d[x])

%timeit using_sets(h,y)
# 6.16 ms ± 373 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

So there's a clear improvement, with the proposed approach performing up to 200 times faster.

Body:
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

Body:
You can use sets to more efficiently find the difference between both lists. If you need to keep the order in the original list you can use sorted with a key.

We want to sort the elements in the set according to their appearance in the original list, so one way is to build a lookup dictionary. We can use enumerate for that. Then we only need to lookup on the dictionary as a key function:

d = {j:i for i,j in enumerate(h)}
new_list  = sorted(list((set(h) - set(y))), key = lambda x: d[x])

Let's try with a simple example:

y = range(5)
h = range(7)
d = {j:i for i,j in enumerate(h)}
sorted(list((set(h) - set(y))), key = lambda x: d[x])
# [5, 6]

Timings -

import random
y = random.sample(range(1, 10001), 10000)
h = random.sample(range(1, 20001), 10000)

%timeit [i for i in h if i not in y]
# 1.28 s ± 37.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def using_sets(a,b):
    d = {j:i for i,j in enumerate(a)}
    sorted(list((set(a) - set(b))), key = lambda x: d[x])

%timeit using_sets(h,y)
# 6.16 ms ± 373 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So there's a clear improvement, with the proposed approach performing up to 200 times faster.


问:
Variable assignment does not assign to variable - what am I doing wrong?
I'm performing a variable assignment in a non-asynchronous function, but the value of the destination variable does not change after the assignment statement runs.

ctx is a Koa2 context. This code runs once a http response has been received. I'm trying to update the context with the values from the (http) response object.

Neither ctx, nor ctx.response is frozen.

I expect ctx.response.status to equal 200 in the 'AFTER' console.log

I suspect that this is idiosyncratic Node behaviour, but I don't know Node very well.

What am I doing wrong here?

```<code>console.log('BEFORE=ctx.response.status='+ctx.response.status+'/response.status='+response.status)
  ctx.response.status = response.status
console.log(' AFTER=ctx.response.status='+ctx.response.status+'/response.status='+response.status)
  ctx.response.timestamp = response.timestamp
  ctx.response.body = response.body
</code>```

This was my output. Note the BEFORE/AFTER tags:

BEFORE=ctx.response.status=404/response.status=200
 AFTER=ctx.response.status=404/response.status=200
```

答:
As it turns out, this issue was caused by a preceding middleware call next() being made without an await keyword

I'm no expert at Node or Koa, but from research it appears that there are conditions were the status property becomes immutable.

Body:
I'm performing a variable assignment in a non-asynchronous function, but the value of the destination variable does not change after the assignment statement runs.

ctx is a Koa2 context. This code runs once a http response has been received. I'm trying to update the context with the values from the (http) response object.

Neither ctx, nor ctx.response is frozen.

I expect ctx.response.status to equal 200 in the 'AFTER' console.log

I suspect that this is idiosyncratic Node behaviour, but I don't know Node very well.

What am I doing wrong here?

console.log('BEFORE=ctx.response.status='+ctx.response.status+'/response.status='+response.status)
  ctx.response.status = response.status
console.log(' AFTER=ctx.response.status='+ctx.response.status+'/response.status='+response.status)
  ctx.response.timestamp = response.timestamp
  ctx.response.body = response.body

This was my output. Note the BEFORE/AFTER tags:

BEFORE=ctx.response.status=404/response.status=200
 AFTER=ctx.response.status=404/response.status=200


问:
How to indicate that date is null in sql
With the following code I was hoping to retrieve the records that have a null value for the ClosedDateTimeT field, but it only shows the records that have a value. Am I doing something wrong here:</p>

```<code>SELECT DISTINCT
    t.ticketid,
    t.Sub,
    i.status,
    i.OwnedByTeam,
    i.OwnedByTeamT,
    i.TypeOptions,
    i.ClosedDateTimeT,
    i.CompletedDateTime,
    i.TitleT
FROM
    ticket AS t
INNER JOIN
    Incident AS i ON t.TicketID = i.IncidentID
WHERE
    CAST(t.Sub AS DATE) >= '01-01-2019'
    AND CAST(t.Sub AS DATE ) <= '05-30-2019'
    AND i.Subcategory = 'Content Request'
    AND (i.TypeOptions = 'New/Initial Submission' OR
         i.TypeOptions = 'Am/Re')
    AND ((i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NOT NULL) OR
         (i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NULL) OR
         (i.OwnedByTeamT LIKE '%E - Cl%'
          AND i.TitleT LIKE '%OP B V%'))
</code>```

答:
Not really sure what the issue is you are facing but your query could be simplified a bit and formatted. Notice I also am using ANSI compliant date literals.</p>

```<code>Select distinct t.ticketid
    , t.Sub
    , i.status
    , i.OwnedByTeam
    , i.OwnedByTeamT
    , i.TypeOptions
    , i.ClosedDateTimeT
    , i.CompletedDateTime
    , i.TitleT
From ticket as t
inner join Incident as i on t.TicketID=i.IncidentID
where
    CAST(t.Sub AS DATE) >= '20190101'
    AND CAST(t.Sub AS DATE ) <= '20190530'
    AND i.Subcategory = 'Content Request'
    AND i.TypeOptions in ('New/Initial Submission', 'Am/Re')
    AND
    (
        (
            i.OwnedByTeamT like '%C - CA%'
            AND
            i.TitleT LIKE '%B Build%'
        )
        OR
        (
            i.OwnedByTeamT like '%E - Cl%'
            AND
            i.TitleT LIKE '%OP B V%'
        )
    )
</code>```

Body:
With the following code I was hoping to retrieve the records that have a null value for the ClosedDateTimeT field, but it only shows the records that have a value. Am I doing something wrong here:

SELECT DISTINCT
    t.ticketid,
    t.Sub,
    i.status,
    i.OwnedByTeam,
    i.OwnedByTeamT,
    i.TypeOptions,
    i.ClosedDateTimeT,
    i.CompletedDateTime,
    i.TitleT
FROM
    ticket AS t
INNER JOIN
    Incident AS i ON t.TicketID = i.IncidentID
WHERE
    CAST(t.Sub AS DATE) >= '01-01-2019'
    AND CAST(t.Sub AS DATE ) <= '05-30-2019'
    AND i.Subcategory = 'Content Request'
    AND (i.TypeOptions = 'New/Initial Submission' OR
         i.TypeOptions = 'Am/Re')
    AND ((i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NOT NULL) OR
         (i.OwnedByTeamT LIKE '%C - CA%'
          AND i.TitleT LIKE '%B Build%'
          AND i.ClosedDateTimeT IS NULL) OR
         (i.OwnedByTeamT LIKE '%E - Cl%'
          AND i.TitleT LIKE '%OP B V%'))

Body:
Not really sure what the issue is you are facing but your query could be simplified a bit and formatted. Notice I also am using ANSI compliant date literals.

Select distinct t.ticketid
    , t.Sub
    , i.status
    , i.OwnedByTeam
    , i.OwnedByTeamT
    , i.TypeOptions
    , i.ClosedDateTimeT
    , i.CompletedDateTime
    , i.TitleT
From ticket as t
inner join Incident as i on t.TicketID=i.IncidentID
where
    CAST(t.Sub AS DATE) >= '20190101'
    AND CAST(t.Sub AS DATE ) <= '20190530'
    AND i.Subcategory = 'Content Request'
    AND i.TypeOptions in ('New/Initial Submission', 'Am/Re')
    AND
    (
        (
            i.OwnedByTeamT like '%C - CA%'
            AND
            i.TitleT LIKE '%B Build%'
        )
        OR
        (
            i.OwnedByTeamT like '%E - Cl%'
            AND
            i.TitleT LIKE '%OP B V%'
        )
    )


问:
On hover change all with same id with style 1 while changing the hovered div with style 2
I have some dynamic user generated divs.
I'm trying to create a function so when the user hovers on one of the divs it highlights while the other divs get blurred.

Therefore I need to figure out how (if possible) I can change the hovered div with one style while changing all the others with another style.

The generated divs are simply spawn through php as a simple div looking like this:

```<code>  <div class="usercontainer" id="usercontainer"> </div>
</code>```

I have tried something like this to change the div the user hovers on. But I can't figure out how I at the same time can change all the others.
Do I need javascript for it? or can it be done with css alone?

```<code> .usercontainer:hover
  {

   background-color: red;
    opacity: 1.0;
    }
</code>```

答:
I am sharing with css approach only, though you can do it by adding a class at parent with javascript.

Disadvantage of this approach is you have to use !important to override child styles.

.children {
    display: inline-block;
 height: 100px;
 width: 100px;
 background-color: grey;
 color: red;
 font-size: 50px;
 border: solid 1px yellow;
}

.parent:hover .children {
 opacity: 0.2;
}

.children:hover {
 opacity: 1 !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="children">1</div>
    <div class="children">2</div>
    <div class="children">3</div>
    <div class="children">4</div>
</div></code>```

Body:
I have some dynamic user generated divs.
I'm trying to create a function so when the user hovers on one of the divs it highlights while the other divs get blurred.

Therefore I need to figure out how (if possible) I can change the hovered div with one style while changing all the others with another style.

The generated divs are simply spawn through php as a simple div looking like this:

I have tried something like this to change the div the user hovers on. But I can't figure out how I at the same time can change all the others.
Do I need javascript for it? or can it be done with css alone?

 .usercontainer:hover
  {

   background-color: red;
    opacity: 1.0;
    }

Body:
I am sharing with css approach only, though you can do it by adding a class at parent with javascript.

Disadvantage of this approach is you have to use !important to override child styles.

.children {
    display: inline-block;
 height: 100px;
 width: 100px;
 background-color: grey;
 color: red;
 font-size: 50px;
 border: solid 1px yellow;
}

.parent:hover .children {
 opacity: 0.2;
}

.children:hover {
 opacity: 1 !important;
}

<div class="parent">
    <div class="children">1</div>
    <div class="children">2</div>
    <div class="children">3</div>
    <div class="children">4</div>
</div>


问:
How to get list of joined keys in jpa
How can I get a list of pictures_id in my Event Object?

```<code>@Entity
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String title;
    private String description;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date starttime;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date endtime;

    // add List<Long> picture_ids

    @OneToMany(cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.TRUE)
    private List<Picture> pictures = new ArrayList<Picture>();
}
</code>```

I want to be able to fetch the Event without the whole picture Objects since they're pretty big. But I can't find a solution to just query the keys to the pictures.

答:
@LazyCollection is a hibernate specific annotation and will only work using Hibernate as JPA Providor.

The @OneToMany annotation is pure JPA, so it will work with any Jpa Providor.

You can achieve lazy loading only using @OneToMany(fetch = FetchType.LAZY)

```<code>@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Picture> pictures = new ArrayList<Picture>();
</code>```

Title: How to get list of joined keys in jpa

Body:
How can I get a list of pictures_id in my Event Object?

@Entity
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String title;
    private String description;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date starttime;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date endtime;

    // add List<Long> picture_ids

    @OneToMany(cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.TRUE)
    private List<Picture> pictures = new ArrayList<Picture>();
}

I want to be able to fetch the Event without the whole picture Objects since they're pretty big. But I can't find a solution to just query the keys to the pictures.

Body:
@LazyCollection is a hibernate specific annotation and will only work using Hibernate as JPA Providor.

The @OneToMany annotation is pure JPA, so it will work with any Jpa Providor.

You can achieve lazy loading only using @OneToMany(fetch = FetchType.LAZY)

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Picture> pictures = new ArrayList<Picture>();


问:
Is there a faster way than fread() to read big data?
Hi first of all I already search on stack and google and found posts such at this one :
Quickly reading very large tables as dataframes. While those are helpfull and well answered, I'm looking for more informations.

I am looking for the best way to read/import "big" data that can go up to 50-60GB.
I am currently using the fread() function from data.table and it is the function that is the fastest I know at the moment. The pc/server I work on got a good cpu (work station) and 32 GB RAM, but still datas over 10GB and sometimes near billions observations takes a lot of time to get read.

We already have sql databases but for some reasons we have to work with big data in R.
Is there a way to speed up R or an even better option than fread() when it comes to huge file like this?

Thank you.

Edit : fread("data.txt", verbose = TRUE)

```<code>omp_get_max_threads() = 2
omp_get_thread_limit() = 2147483647
DTthreads = 0
RestoreAfterFork = true
Input contains no \n. Taking this to be a filename to open
[01] Check arguments
  Using 2 threads (omp_get_max_threads()=2, nth=2)
  NAstrings = [<<NA>>]
  None of the NAstrings look like numbers.
  show progress = 1
  0/1 column will be read as integer
[02] Opening the file
  Opening file C://somefolder/data.txt
  File opened, size = 1.083GB (1163081280 bytes).
  Memory mapped ok
[03] Detect and skip BOM
[04] Arrange mmap to be \0 terminated
  \n has been found in the input and different lines can end with different line endings (e.g. mixed \n and \r\n in one file). This is common and ideal.
[05] Skipping initial rows if needed
  Positioned on line 1 starting: <<ID,Dat,No,MX,NOM_TX>>
[06] Detect separator, quoting rule, and ncolumns
  Detecting sep automatically ...
  sep=','  with 100 lines of 5 fields using quote rule 0
  Detected 5 columns on line 1. This line is either column names or first data row. Line starts as: <<ID,Dat,No,MX,NOM_TX>>
  Quote rule picked = 0
  fill=false and the most number of columns found is 5
[07] Detect column types, good nrow estimate and whether first row is column names
  Number of sampling jump points = 100 because (1163081278 bytes from row 1 to eof) / (2 * 5778 jump0size) == 100647
  Type codes (jump 000)    : 5A5AA  Quote rule 0
  Type codes (jump 100)    : 5A5AA  Quote rule 0
  'header' determined to be true due to column 1 containing a string on row 1 and a lower type (int32) in the rest of the 10054 sample rows
  =====
  Sampled 10054 rows (handled \n inside quoted fields) at 101 jump points
  Bytes from first data row on line 2 to the end of last row: 1163081249
  Line length: mean=56.72 sd=20.65 min=25 max=128
  Estimated number of rows: 1163081249 / 56.72 = 20506811
  Initial alloc = 41013622 rows (20506811 + 100%) using bytes/max(mean-2*sd,min) clamped between [1.1*estn, 2.0*estn]
  =====
[08] Assign column names
[09] Apply user overrides on column types
  After 0 type and 0 drop user overrides : 5A5AA
[10] Allocate memory for the datatable
  Allocating 5 column slots (5 - 0 dropped) with 41013622 rows
[11] Read the data
  jumps=[0..1110), chunk_size=1047820, total_size=1163081249
|--------------------------------------------------|
|==================================================|
Read 20935277 rows x 5 columns from 1.083GB (1163081280 bytes) file in 00:31.484 wall clock time
[12] Finalizing the datatable
  Type counts:
         2 : int32     '5'
         3 : string    'A'
=============================
   0.007s (  0%) Memory map 1.083GB file
   0.739s (  2%) sep=',' ncol=5 and header detection
   0.001s (  0%) Column type detection using 10054 sample rows
   1.809s (  6%) Allocation of 41013622 rows x 5 cols (1.222GB) of which 20935277 ( 51%) rows used
  28.928s ( 92%) Reading 1110 chunks (0 swept) of 0.999MB (each chunk 18860 rows) using 2 threads
   +   26.253s ( 83%) Parse to row-major thread buffers (grown 0 times)
   +    2.639s (  8%) Transpose
   +    0.035s (  0%) Waiting
   0.000s (  0%) Rereading 0 columns due to out-of-sample type exceptions
  31.484s        Total
</code>```

答:
You can use select = columns to only load the relevant columns without saturating your memory. For example:

```<code>dt <- fread("./file.csv", select = c("column1", "column2", "column3"))
</code>```

I used read.delim() to read a file that fread() could not load completely. So you could convert your data into .txt and use read.delim().

However, why don't you open a connection to the SQL server you're pulling your data from. You can open connections to SQL servers with library(odbc) and write your query like you normally would. You can optimize your memory usage that way.

Check out this short introduction to odbc.

Body:
Hi first of all I already search on stack and google and found posts such at this one :
Quickly reading very large tables as dataframes. While those are helpfull and well answered, I'm looking for more informations.

I am looking for the best way to read/import "big" data that can go up to 50-60GB.
I am currently using the fread() function from data.table and it is the function that is the fastest I know at the moment. The pc/server I work on got a good cpu (work station) and 32 GB RAM, but still datas over 10GB and sometimes near billions observations takes a lot of time to get read.

We already have sql databases but for some reasons we have to work with big data in R.
Is there a way to speed up R or an even better option than fread() when it comes to huge file like this?

Thank you.

Edit : fread("data.txt", verbose = TRUE)

omp_get_max_threads() = 2
omp_get_thread_limit() = 2147483647
DTthreads = 0
RestoreAfterFork = true
Input contains no \n. Taking this to be a filename to open
[01] Check arguments
  Using 2 threads (omp_get_max_threads()=2, nth=2)
  NAstrings = [<<NA>>]
  None of the NAstrings look like numbers.
  show progress = 1
  0/1 column will be read as integer
[02] Opening the file
  Opening file C://somefolder/data.txt
  File opened, size = 1.083GB (1163081280 bytes).
  Memory mapped ok
[03] Detect and skip BOM
[04] Arrange mmap to be \0 terminated
  \n has been found in the input and different lines can end with different line endings (e.g. mixed \n and \r\n in one file). This is common and ideal.
[05] Skipping initial rows if needed
  Positioned on line 1 starting: <<ID,Dat,No,MX,NOM_TX>>
[06] Detect separator, quoting rule, and ncolumns
  Detecting sep automatically ...
  sep=','  with 100 lines of 5 fields using quote rule 0
  Detected 5 columns on line 1. This line is either column names or first data row. Line starts as: <<ID,Dat,No,MX,NOM_TX>>
  Quote rule picked = 0
  fill=false and the most number of columns found is 5
[07] Detect column types, good nrow estimate and whether first row is column names
  Number of sampling jump points = 100 because (1163081278 bytes from row 1 to eof) / (2 * 5778 jump0size) == 100647
  Type codes (jump 000)    : 5A5AA  Quote rule 0
  Type codes (jump 100)    : 5A5AA  Quote rule 0
  'header' determined to be true due to column 1 containing a string on row 1 and a lower type (int32) in the rest of the 10054 sample rows
  =====
  Sampled 10054 rows (handled \n inside quoted fields) at 101 jump points
  Bytes from first data row on line 2 to the end of last row: 1163081249
  Line length: mean=56.72 sd=20.65 min=25 max=128
  Estimated number of rows: 1163081249 / 56.72 = 20506811
  Initial alloc = 41013622 rows (20506811 + 100%) using bytes/max(mean-2*sd,min) clamped between [1.1*estn, 2.0*estn]
  =====
[08] Assign column names
[09] Apply user overrides on column types
  After 0 type and 0 drop user overrides : 5A5AA
[10] Allocate memory for the datatable
  Allocating 5 column slots (5 - 0 dropped) with 41013622 rows
[11] Read the data
  jumps=[0..1110), chunk_size=1047820, total_size=1163081249
|--------------------------------------------------|
|==================================================|
Read 20935277 rows x 5 columns from 1.083GB (1163081280 bytes) file in 00:31.484 wall clock time
[12] Finalizing the datatable
  Type counts:
         2 : int32     '5'
         3 : string    'A'
=============================
   0.007s (  0%) Memory map 1.083GB file
   0.739s (  2%) sep=',' ncol=5 and header detection
   0.001s (  0%) Column type detection using 10054 sample rows
   1.809s (  6%) Allocation of 41013622 rows x 5 cols (1.222GB) of which 20935277 ( 51%) rows used
  28.928s ( 92%) Reading 1110 chunks (0 swept) of 0.999MB (each chunk 18860 rows) using 2 threads
   +   26.253s ( 83%) Parse to row-major thread buffers (grown 0 times)
   +    2.639s (  8%) Transpose
   +    0.035s (  0%) Waiting
   0.000s (  0%) Rereading 0 columns due to out-of-sample type exceptions
  31.484s        Total

Body:
You can use select = columns to only load the relevant columns without saturating your memory. For example:

dt <- fread("./file.csv", select = c("column1", "column2", "column3"))

I used read.delim() to read a file that fread() could not load completely. So you could convert your data into .txt and use read.delim().

However, why don't you open a connection to the SQL server you're pulling your data from. You can open connections to SQL servers with library(odbc) and write your query like you normally would. You can optimize your memory usage that way.

Check out this short introduction to odbc.


问:
How to use grep to extract ip adresses and date/time strings from log file?
I have a log file that looks like this:

```<code>May 25 05:34:16 server sshd[1203]: Received disconnect from 192.0.2.2 port 39102:11
May 25 05:34:16 server sshd[1203]: Disconnected from 192.0.2.1 port 39102
</code>```

Now i want to extract all of the ip addresses and the date/time strings at the beginning using grep. I already know how to get the ips:

```<code>grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /log.txt
</code>```

and the dates/times:

```<code>grep -o '[A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]' /log.txt
</code>```

but i don't know how to get both at the same time in a format like:

```<code>May 25 05:34:16 192.0.2.1
</code>```

I've read something like:

```<code> grep -oE 'match1|match2' /log.txt
</code>```

but that doesn't seem to work.

答:
Printing two matches in the single line is easier with awk, following will print date(by printing $1,$2,$3 and all the valid IP address.

```<code>gawk  '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/,a);split(a[0],b,".")} b[1]<=255&& b[2]<=255 && b[3]<=255 && b[4]<=255 &&length(a[0]){print $1,$2,$3, a[0]}' log_file
May 25 05:34:16 192.0.2.2
May 25 05:34:16 192.0.2.1
</code>```

Explanation: First use match function to capture all the strings having format of digit.digit.digit.digit and store them into an array called "a" , then split the captured array(a) by dot(.) characters  and check if each is <= 255 to ensure the IP address is valid.

Note that: GNU awk is used here.

Also note that, the regex you mentioned will also print invalid IP addresses (Eg: 333.222.555.666).

Body:
I have a log file that looks like this:

May 25 05:34:16 server sshd[1203]: Received disconnect from 192.0.2.2 port 39102:11
May 25 05:34:16 server sshd[1203]: Disconnected from 192.0.2.1 port 39102

Now i want to extract all of the ip addresses and the date/time strings at the beginning using grep. I already know how to get the ips:

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /log.txt

and the dates/times:

grep -o '[A-Z][a-z][a-z] [0-3][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]' /log.txt

but i don't know how to get both at the same time in a format like:

May 25 05:34:16 192.0.2.1

I've read something like:

 grep -oE 'match1|match2' /log.txt

but that doesn't seem to work.

Body:
Printing two matches in the single line is easier with awk, following will print date(by printing $1,$2,$3 and all the valid IP address.

gawk  '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/,a);split(a[0],b,".")} b[1]<=255&& b[2]<=255 && b[3]<=255 && b[4]<=255 &&length(a[0]){print $1,$2,$3, a[0]}' log_file
May 25 05:34:16 192.0.2.2
May 25 05:34:16 192.0.2.1

Explanation: First use match function to capture all the strings having format of digit.digit.digit.digit and store them into an array called "a" , then split the captured array(a) by dot(.) characters  and check if each is <= 255 to ensure the IP address is valid.

Note that: GNU awk is used here.

Also note that, the regex you mentioned will also print invalid IP addresses (Eg: 333.222.555.666).


问:
Alert for reminding the user to rate the app
As you may have seen in some apps an alert pops up asking the user to rate the app in itunes and usually the alternatives you get to choose from is something like: Sure which opens the rate page for the app. The second option is No Thanks which closes the alert and the third option usually is maybe later which displays the alert later.

I was wondering how to do this.
I want the alert to be displayed after say the app has launched 20 times if that would be possible.
And how can I create an maybe later alternative which displays the alert maybe 15 launches of the app later?

And a final question is there a special link for the apps rate page? So when you click the sure button or whatever it will take your directly to the rate page.

答:
I've used this: https://github.com/arashpayan/appirater. You can look at my fork as well for a specific mod I needed.

[EDIT: comment re NSUserDefaults]

I suggested this link because it is a full, working implementation of what you describe that is easily integrated into existing apps. I've used (and modified) it myself. NSUserDefaults is a general purpose mechanism for persisting app state. I agree with the others that it's a very useful thing to learn and use, it's just not a full answer to your question. If you choose to roll your own implementation of a rating system (nothing wrong with that) you will most likely use NSUserDefaults to store the relevant info.


问:
Errors: Data path ".builders['app-shell']" should have required property 'class'
I am getting this error while running my application. Here are the details of my application.

```<code>Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0
</code>```

I have already tried cache clean.

答:
In your package.json change the devkit builder.

```<code>"@angular-devkit/build-angular": "^0.800.1",
</code>```

to

```<code>"@angular-devkit/build-angular": "^0.10.0",
</code>```

it works for me.

Body:
I am getting this error while running my application. Here are the details of my application.

Angular CLI: 7.3.3
Node: 10.15.1
Angular: 7.2.7
@angular-devkit/architect -0.13.3
@angular-devkit/build-angular- 0.800.1
@angular-devkit/build-optimizer - 0.800.1
@angular-devkit/build-webpack - 0.800.1
@angular-devkit/core -7.3.3
@angular-devkit/schematics -7.3.3
@angular/cli -7.3.3
@ngtools/webpack -8.0.1
@schematics/angular -7.3.3
@schematics/update 0.13.3
rxjs 6.3.3
typescript 3.2.4
webpack 4.30.0

I have already tried cache clean.

Body:
In your package.json change the devkit builder.

"@angular-devkit/build-angular": "^0.800.1",

to

"@angular-devkit/build-angular": "^0.10.0",

it works for me.