问:
Project Reactor - How to create a sliding window Flux from a Java 8 stream
Java 8 Streams do not permit reuse. This creates a puzzle about how to reuse a stream when creating a sliding window flux to calculate a relationship like x(i)*x(i-1).

The following code is based on the idea of a shift operator. I shift the first stream with skip(1) to create a second stream.

```<code>Flux<Integer> primary = Flux.fromStream(IntStream.range(1, 10).boxed());
Flux<Integer> secondary = primary.skip(1);
primary.zipWith(secondary)
        .map(t -> t.getT1() * t.getT2())
        .subscribe(System.out::println);
</code>```

Here is a visual representation of the above code:

```<code>1 2 3 4 5 6 7 8 9 10
v v v v v v v v v v  skip(1)
2 3 4 5 6 7 8 9 10
v v v v v v v v v v  zipWith
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 10 <- sliding window of length 2
v v v v v v v v v v  multiples
2 6 12 20 30 42 56 72 90
</code>```

Unfortunately this code errors as:

```<code>java.lang.IllegalStateException: stream has already been operated upon or closed
</code>```

The obvious work-around is to cache the elements and ensure the cache size is greater than or equal to the stream size:

```<code>Flux<Integer> primary = Flux.fromStream(IntStream.range(1, 10).boxed()).cache(10);
</code>```

or use a stream replacement:

```<code>Flux<Integer> primary = Flux.range(0, 10);
</code>```

The second solution will just re-execute the original sequence for the skip(1) sequence.

However an efficient solution only requires a buffer of size 2. This is a big deal if the stream happens to be a large file:

```<code>Files.lines(Paths.get(megaFile));
</code>```

How can I buffer a stream efficiently so multiple subscriptions to the primary Flux do not cause everything to be read into memory or cause re-executions?

答:
I've implemented the following solution:

public <T> Flux<Flux<T>> toSlidingWindow(Flux<T> source, int size) {
    return toSlidingWindow(source, deque -> {
        while (deque.size() > size) {
            deque.poll();
        }
        return Flux.fromIterable(deque);
    });
}

public <T> Flux<Flux<T>> toSlidingWindow(Flux<T> source, Function<Deque<T>, Flux<T>> dequePruneFunction) {
    return source.map(ohlc -> {
        Deque<T> deque = dequeAtomicReference.get();
        deque.offer(ohlc);
        return dequePruneFunction.apply(deque);
    });
}
```

<p>This can either be a fixed size sliding window or use a custom function to determine the extent of each window.</p>

<p>If any multithreading problems arise using it like this you could copy the <code>Deque</code> within an <code>acquire</code> and <code>release</code> block which seems to be supported by <code>AtomicReference</code>. This would ensure the resulting window <code>Flux</code> to remain unchanged by other threads.</p>

<p>Perhaps like so:</p>

<pre class="lang-java prettyprint-override"><code>public <T> Flux<Flux<T>> toSlidingWindowAsync(Flux<T> source, int size) {
    return toSlidingWindowAsync(source, deque -> {
        while (deque.size() > size) {
            deque.poll();
        }
        return Flux.fromIterable(new LinkedList<>(deque));
    });
}

public <T> Flux<Flux<T>> toSlidingWindowAsync(Flux<T> source, Function<Deque<T>, Flux<T>> dequePruneFunction) {
    AtomicReference<Deque<T>> dequeAtomicReference = new AtomicReference<>(new LinkedList<>());
    return source.map(ohlc -> {
        Deque<T> deque = dequeAtomicReference.getAcquire();
        deque.offer(ohlc);
        Flux<T> windowFlux = dequePruneFunction.apply(deque);
        dequeAtomicReference.setRelease(deque);
        return windowFlux;
    });
}
</code>```

This copies the Deque that is used for each resultant sliding window.

Body:
Java 8 Streams do not permit reuse. This creates a puzzle about how to reuse a stream when creating a sliding window flux to calculate a relationship like x(i)*x(i-1).

The following code is based on the idea of a shift operator. I shift the first stream with skip(1) to create a second stream.

Flux<Integer> primary = Flux.fromStream(IntStream.range(1, 10).boxed());
Flux<Integer> secondary = primary.skip(1);
primary.zipWith(secondary)
        .map(t -> t.getT1() * t.getT2())
        .subscribe(System.out::println);

Here is a visual representation of the above code:

1 2 3 4 5 6 7 8 9 10
v v v v v v v v v v  skip(1)
2 3 4 5 6 7 8 9 10
v v v v v v v v v v  zipWith
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9 10 <- sliding window of length 2
v v v v v v v v v v  multiples
2 6 12 20 30 42 56 72 90

Unfortunately this code errors as:

java.lang.IllegalStateException: stream has already been operated upon or closed

The obvious work-around is to cache the elements and ensure the cache size is greater than or equal to the stream size:

Flux<Integer> primary = Flux.fromStream(IntStream.range(1, 10).boxed()).cache(10);

or use a stream replacement:

Flux<Integer> primary = Flux.range(0, 10);

The second solution will just re-execute the original sequence for the skip(1) sequence.

However an efficient solution only requires a buffer of size 2. This is a big deal if the stream happens to be a large file:

Files.lines(Paths.get(megaFile));

How can I buffer a stream efficiently so multiple subscriptions to the primary Flux do not cause everything to be read into memory or cause re-executions?

Body:
I've implemented the following solution:

public <T> Flux<Flux<T>> toSlidingWindow(Flux<T> source, int size) {
    return toSlidingWindow(source, deque -> {
        while (deque.size() > size) {
            deque.poll();
        }
        return Flux.fromIterable(deque);
    });
}

public <T> Flux<Flux<T>> toSlidingWindow(Flux<T> source, Function<Deque<T>, Flux<T>> dequePruneFunction) {
    return source.map(ohlc -> {
        Deque<T> deque = dequeAtomicReference.get();
        deque.offer(ohlc);
        return dequePruneFunction.apply(deque);
    });
}

This can either be a fixed size sliding window or use a custom function to determine the extent of each window.

If any multithreading problems arise using it like this you could copy the Deque within an acquire and release block which seems to be supported by AtomicReference. This would ensure the resulting window Flux to remain unchanged by other threads.

Perhaps like so:

public <T> Flux<Flux<T>> toSlidingWindowAsync(Flux<T> source, int size) {
    return toSlidingWindowAsync(source, deque -> {
        while (deque.size() > size) {
            deque.poll();
        }
        return Flux.fromIterable(new LinkedList<>(deque));
    });
}

public <T> Flux<Flux<T>> toSlidingWindowAsync(Flux<T> source, Function<Deque<T>, Flux<T>> dequePruneFunction) {
    AtomicReference<Deque<T>> dequeAtomicReference = new AtomicReference<>(new LinkedList<>());
    return source.map(ohlc -> {
        Deque<T> deque = dequeAtomicReference.getAcquire();
        deque.offer(ohlc);
        Flux<T> windowFlux = dequePruneFunction.apply(deque);
        dequeAtomicReference.setRelease(deque);
        return windowFlux;
    });
}

This copies the Deque that is used for each resultant sliding window.


来源: stackexchange

问:
Hide a list except the selected list option
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

```<code><ul class="links">
  <li class="us">United States</li>
  <li class="canada">Canada</li>
  <li class="france">France</li>
  <li class="china">China</li>
  <li class="englande">England</li>
</code>```

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

答:
If 'us' was selected, you could:</p>

```<code>$('ul > li[class!=us]').css('display', 'none');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

United States

Canada

France

China

England

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

Body:
If 'us' was selected, you could:

$('ul > li[class!=us]').css('display', 'none');


问:
Getting first day of the month, is outputting the wrong first day of the month
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

```<code>$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);
</code>```

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

答:
To get the day of the week falling on the first day of any month you can use the prefix first day of e.g.

```<code>echo (new \DateTime('first day of August'))->format('l');
</code>```

This will show correctly Thursday for August 2019.

If you want to do it dynamically using numbers for months, you can create a dummy date like you were trying to do.

```<code>$timeString = sprintf('01.%02d.%04d', 8, 2019); // replace the numbers with your variables
echo (new \DateTime($timeString))->format('l');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

Body:
To get the day of the week falling on the first day of any month you can use the prefix first day of e.g.

echo (new \DateTime('first day of August'))->format('l');

This will show correctly Thursday for August 2019.

If you want to do it dynamically using numbers for months, you can create a dummy date like you were trying to do.

$timeString = sprintf('01.%02d.%04d', 8, 2019); // replace the numbers with your variables
echo (new \DateTime($timeString))->format('l');


问:
How to interpolate a specified number of generated values in a column in R?
I have a data with 78 observations in a column. I need to generate a column with 6400 observations. I thought I could interpolate value by value, but that will generate only one value between each of my original values.</p>

Body:
You can interpolate n values with approx(). Check documentation here

small example:

x <- c(1,2,3,4)
approx(x, n=100)

output:

  [1] 1.000000 1.030303 1.060606 1.090909 1.121212 1.151515 1.181818 1.212121 1.242424 1.272727 1.303030
 [12] 1.333333 1.363636 1.393939 1.424242 1.454545 1.484848 1.515152 1.545455 1.575758 1.606061 1.636364
 [23] 1.666667 1.696970 1.727273 1.757576 1.787879 1.818182 1.848485 1.878788 1.909091 1.939394 1.969697
 [34] 2.000000 2.030303 2.060606 2.090909 2.121212 2.151515 2.181818 2.212121 2.242424 2.272727 2.303030
 [45] 2.333333 2.363636 2.393939 2.424242 2.454545 2.484848 2.515152 2.545455 2.575758 2.606061 2.636364
 [56] 2.666667 2.696970 2.727273 2.757576 2.787879 2.818182 2.848485 2.878788 2.909091 2.939394 2.969697
 [67] 3.000000 3.030303 3.060606 3.090909 3.121212 3.151515 3.181818 3.212121 3.242424 3.272727 3.303030
 [78] 3.333333 3.363636 3.393939 3.424242 3.454545 3.484848 3.515152 3.545455 3.575758 3.606061 3.636364
 [89] 3.666667 3.696970 3.727273 3.757576 3.787879 3.818182 3.848485 3.878788 3.909091 3.939394 3.969697
[100] 4.000000

So just change it for your case like:

approx(df$column, n=6400)


问:
C#: How to add an attributes to an object at run-time?
As an entity class, I want to add an attributes at run-time, how should I do?</p>

答:
I would go with PostSharp, a very elegant AOP framework (or Policy Injection).

PostSharp allows you to inject custom attributes.

The blog entry refered to in the post has some code you can download to achieve your goal.

LastEditorDisplayName: Samuel

OwnerDisplayName: Renaud Bompuis

ContentLicense: CC BY-SA 2.5


问:
Help with merging adjacent nodes
I apologize for not knowing xsl very well, but i have an xml document that I would like to transform and I've not been able to find an example that works for me. I would like to merge the locations into a single element. I have the following document:

```<code><?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Lake Athletic Complex</name>
    </locations>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Athletic Complex</name>
    </locations>
    <locations>
        <id>6</id>
        <name>HS Baseball Field</name>
    </locations>
</event>
</code>```

I am trying to make it like this:

```<code><?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <location_name>Lake Athletic Complex</location_name>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <location_name>Athletic Complex, HS Baseball Field</location_name>
</event>
</code>```

答:
Use the identity transform with templates that handle the special cases:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="event">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()[not(self::locations)]" />
            <location_name>
                <xsl:apply-templates select="locations" />
            </location_name>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="locations">
        <xsl:value-of select="name" />
        <xsl:if test="position() != last()">
            <xsl:text>, </xsl:text>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: Help with merging adjacent nodes

Body:
I apologize for not knowing xsl very well, but i have an xml document that I would like to transform and I've not been able to find an example that works for me. I would like to merge the locations into a single element. I have the following document:

<?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Lake Athletic Complex</name>
    </locations>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <locations>
        <id>116</id>
        <name>Athletic Complex</name>
    </locations>
    <locations>
        <id>6</id>
        <name>HS Baseball Field</name>
    </locations>
</event>

I am trying to make it like this:

<?xml version="1.0" encoding="UTF-8"?><tfs_events>
<title>Referees Events</title>
<event>
    <id>256</id>
    <name>SB-V,SB-JV vs McKinley HS</name>
    <time_start>2011-04-12 17:00:00</time_start>
    <time_end>2011-04-12 19:00:00</time_end>
    <status>Active</status>
    <location_name>Lake Athletic Complex</location_name>
</event>
<event>
    <id>257</id>
    <name>SB-V,SB-JV vs Jackson HS</name>
    <time_start>2011-04-14 17:00:00</time_start>
    <time_end>2011-04-14 19:00:00</time_end>
    <status>Active</status>
    <location_name>Athletic Complex, HS Baseball Field</location_name>
</event>

Body:
Use the identity transform with templates that handle the special cases:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="event">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()[not(self::locations)]" />
            <location_name>
                <xsl:apply-templates select="locations" />
            </location_name>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="locations">
        <xsl:value-of select="name" />
        <xsl:if test="position() != last()">
            <xsl:text>, </xsl:text>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>


问:
Unable to invoke SageMaker endpoint(TensorFlow Model) using Boto3 client from AWS Lambda in python
I have a TensorFlow Model deployed with AWS SageMaker endpoint exposed .
From Lambda Python I am using boto3 client to invoke the endpoint .
The TensorFlow model accepts 3 inputs as follows

```<code>{'input1' : numpy array , 'input2' : integer ,'input3' :numpy array }
</code>```

From Lambda using runtime.invoke_endpoint to invoke the SageMaker endpoint .
Getting the error as Parse Error when the API is invoked from boto3client
I tried serializing the data into csv format before calling the API endpoint

Below code written in Lambda

```<code>payload = {'input1': encoded_enc_inputstanza_in_batch,
'input2' : encoded_enc_inputstanza_in_batch.shape[1],
'input3' : np.reshape([[15]*20],20) }
infer_file = io.StringIO()
writer = csv.writer(infer_file)
for key, value in payload.items():
  writer.writerow([key, value])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
           ContentType='text/csv',
           Body=infer_file.getvalue())
</code>```

Additional Details
These are the additional details
- Sagemaker Model expects 3 fields as input - 'input1' - Numpy array
 'input2' - Int data type ,
 'input3' - numpy array

Actual result -

```<code>Traceback (most recent call last):
        File "/var/task/lambda_function.py", line 143, in lambda_handler
        Body=infer_file.getvalue())
        File "/var/runtime/botocore/client.py", line 320, in _api_call
        return self._make_api_call(operation_name, kwargs)
        File "/var/runtime/botocore/client.py", line 623, in _make_api_call
        raise error_class(parsed_response, operation_name)
        END RequestId: fa70e1f3-763b-41be-ad2d-76ae80aefcd0
</code>```

Expected Result - Successful invocation of the API endpoint .

答:
After converting the data to text/csv format with comma delimited, have you updated the Endpoint to use the new model data? The input data needs to match the schema of the model.
Is there comma in the "encoded_enc_inputstanza_in_batch" variable?</p>

Body:
I have a TensorFlow Model deployed with AWS SageMaker endpoint exposed .
From Lambda Python I am using boto3 client to invoke the endpoint .
The TensorFlow model accepts 3 inputs as follows

{'input1' : numpy array , 'input2' : integer ,'input3' :numpy array }

From Lambda using runtime.invoke_endpoint to invoke the SageMaker endpoint .
Getting the error as Parse Error when the API is invoked from boto3client
I tried serializing the data into csv format before calling the API endpoint

Below code written in Lambda

payload = {'input1': encoded_enc_inputstanza_in_batch,
'input2' : encoded_enc_inputstanza_in_batch.shape[1],
'input3' : np.reshape([[15]*20],20) }
infer_file = io.StringIO()
writer = csv.writer(infer_file)
for key, value in payload.items():
  writer.writerow([key, value])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
           ContentType='text/csv',
           Body=infer_file.getvalue())

Additional Details
These are the additional details
- Sagemaker Model expects 3 fields as input - 'input1' - Numpy array
 'input2' - Int data type ,
 'input3' - numpy array

Actual result -

Traceback (most recent call last):
        File "/var/task/lambda_function.py", line 143, in lambda_handler
        Body=infer_file.getvalue())
        File "/var/runtime/botocore/client.py", line 320, in _api_call
        return self._make_api_call(operation_name, kwargs)
        File "/var/runtime/botocore/client.py", line 623, in _make_api_call
        raise error_class(parsed_response, operation_name)
        END RequestId: fa70e1f3-763b-41be-ad2d-76ae80aefcd0

Expected Result - Successful invocation of the API endpoint .


问:
Apollo graphql is returning null data for an empty subdocument in mongodb
I added another field(contacts) to my apollo graphql mutation but when retrieving the field it produces false data.  Even if the matching mongodb field has real data or not, graphql returns mutliple fields with null values.

I've already tried removing __typename in the apollo client graphql options but it doesn't help.  Current stack is:

```<code>reactjs 16.8.5
react-apollo 2.5.2
mongodb 3.6.11
mongoose 5.3.6
apollo-server 2.3.1
</code>```

I don't understand why it does this since I have another subdocument that is almost identical but returns correctly.

```<code>// CLIENTSIDE
// APOLLO SETUP
const cache = new InMemoryCache({
   dataIdFromObject: object => object.key || null
 })

 const AuthLink = (operation, forward) => {
   const token = cookies._uid
   operation.setContext(context => ({
     ...context,
     headers: {
       ...context.headers,
       authorization: token
     }
   }))

   return forward(operation)
 }

 const httpLink = new HttpLink({
   uri:"/graphql",
   credentials: "include"
 })

// mutation
 export const LOGIN_MUTATION = gql`
  mutation loginMutation($email: String!, $password: String!) {
    login(input: {email: $email, password: $password}) {
      token
      user {
        _id
        contacts {  // This is the subfield in question
          _id
          username
        }
        subscriptions {  // This subfield returns corretly
          _id
          title
          levels {
            _id
          }
        }
      }
      error {
        path
        message
      }
    }
  }
`

// SERVERSIDE
// APOLLO SETUP
 const baseSchema = `
   schema {
     query: Query,
     mutation: Mutation
   }
 `
 const schema = makeExecutableSchema({
   typeDefs: [
     userTypeDefs,
   ],
   resolvers: merge(
     {},
     userResolvers,
   )
 })

 const {ObjectId} = mongoose.Types
 ObjectId.prototype.valueOf = function() {
  return this.toString()
 }

 export default new ApolloServer({
   introspection: true,
   credentials: true,
   schema,
   context: ({req, res}) => ({
     url: req.protocol + "://" + req.get("host"),
     req
   })
 })

// USER MONGOOSE MODEL
 export const UserSchema = new mongoose.Schema(
   {
     contacts: [
       {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
       }
     ],
     firstName: {
       type: String
     },
     lastName: {
       type: String
     },
     username: {
       type: String,
       lowercase: true,
       unique: true,
       required: [true, "can't be blank"],
       match: [/^[a-zA-Z0-9]+$/, "is invalid"],
       index: true
     },

     sentRequests: [
       {
         username: {
           type: String,
           default: ""
         }
       }
     ],
     subscriptions: [
       {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Course"
       }
     ],
     password: {
       default: "",
       required: [true, "can't be blank"],
       type: String
     }
   },
   {timestamps: true}
 )

 UserSchema.plugin(uniqueValidator, {message: "is already taken."})
 export default mongoose.model("User", UserSchema)

// USER GRAPHQL SCHEMA
type User {
   _id: ID
   contacts: [User]
   email: String!
   username: String
   subscriptions: [Course]
   createdAt: String
   updatedAt: String
 }

 type AuthPayload {
   token: String
   user: User
   error: [Error]
 }

 input LoginInput {
   email: String!
   password: String!
 }

 type Mutation {
   login(input: LoginInput): AuthPayload
 }

// USER RESOLVER
 const login = async (parent, args, ctx, info) => {
   let email = args.email

   let user = await User.findOne({email})
     .populate("subscriptions")
     .populate("contacts")
     .exec()

  if (!user) {
     arrayOfErrors.push({
       path: "email",
       message: "invalid email"
     })
   } else if (user) {

   console.log("user: ", user)

   return {
     user,
     error: arrayOfErrors
   }
 }

 Mutation: {
   login
 }
</code>```

```<code>// CONSOLE LOG CLIENTSIDE
user:
  confirmed: true
  contacts: Array(3)  // returns an array of 3 items??  It's [] in mongodb
    0: {_id: null, username: null}
    1: {_id: null, username: null}
    2: {_id: null, username: null}
    length: 3
    __proto__: Array(0)
  subscriptions: Array(1)
    0: {_id: "5cd36fc1c8d1e222b99d9c58", title: "Korean Class 101 Study",
    length: 1
    __proto__: Object
__proto__: Object

// CONSOLE LOG SERVERSIDE
POST /graphql 200 64.359 ms - -
user: {
  contacts: [ ],
  subscriptions:
   [ { _id: 5cd6f7f8212af32c75555d4b,
       subscribers: 2,
       owner: 5cd36edec8d1e222b99d9c57,
       createdAt: 2019-05-09T00:09:37.845Z,
       updatedAt: 2019-05-11T16:36:14.661Z,
       __v: 23 } ],
  password: '$2b$10$bkjiazklcoqlkJSJSAioxoAqkoajsdjnqjkiaallaadfadfp7zS',
  _id: 5cd36edec8d1e222b99d9c57,
  email: 'example@test.com',
  username: 'example',
  createdAt: 2019-05-09T00:05:50.314Z,
  updatedAt: 2019-05-29T17:23:21.545Z,
  __v: 32
}
</code>```

I expected an empty array to return [ ], instead graphql returns an array of 3 items with null values.  Even if I add real contacts into the database it still returns the 3 items with null values.
The subscriptions are returning correctly yet it is almost identical to the contacts field with the exception of being a type "Course" in the mongoose model instead of type "User".

答:
I doubt anyone will ever come across this type of error, but here's the solution in case you do.  During development I had placed this code in my resolver for testing purposes.  Removing it solved the problem.

```<code>// USER RESOLVER
...
Query: {...},

/* code to remove
User: {
  contacts: user => {
    return ["Mo", "Larry", "Curly"]
  }
}
*/

Mutation: {...}
</code>```

A very trivial thing but having not been in this actual code for several months made it difficult to spot. I never thought the 3 stooges would ever give me so much headache.

Body:
I added another field(contacts) to my apollo graphql mutation but when retrieving the field it produces false data.  Even if the matching mongodb field has real data or not, graphql returns mutliple fields with null values.

I've already tried removing __typename in the apollo client graphql options but it doesn't help.  Current stack is:

reactjs 16.8.5
react-apollo 2.5.2
mongodb 3.6.11
mongoose 5.3.6
apollo-server 2.3.1

I don't understand why it does this since I have another subdocument that is almost identical but returns correctly.

// CLIENTSIDE
// APOLLO SETUP
const cache = new InMemoryCache({
   dataIdFromObject: object => object.key || null
 })

 const AuthLink = (operation, forward) => {
   const token = cookies._uid
   operation.setContext(context => ({
     ...context,
     headers: {
       ...context.headers,
       authorization: token
     }
   }))

   return forward(operation)
 }

 const httpLink = new HttpLink({
   uri:"/graphql",
   credentials: "include"
 })

// mutation
 export const LOGIN_MUTATION = gql`
  mutation loginMutation($email: String!, $password: String!) {
    login(input: {email: $email, password: $password}) {
      token
      user {
        _id
        contacts {  // This is the subfield in question
          _id
          username
        }
        subscriptions {  // This subfield returns corretly
          _id
          title
          levels {
            _id
          }
        }
      }
      error {
        path
        message
      }
    }
  }
`

// SERVERSIDE
// APOLLO SETUP
 const baseSchema = `
   schema {
     query: Query,
     mutation: Mutation
   }
 `
 const schema = makeExecutableSchema({
   typeDefs: [
     userTypeDefs,
   ],
   resolvers: merge(
     {},
     userResolvers,
   )
 })

 const {ObjectId} = mongoose.Types
 ObjectId.prototype.valueOf = function() {
  return this.toString()
 }

 export default new ApolloServer({
   introspection: true,
   credentials: true,
   schema,
   context: ({req, res}) => ({
     url: req.protocol + "://" + req.get("host"),
     req
   })
 })

// USER MONGOOSE MODEL
 export const UserSchema = new mongoose.Schema(
   {
     contacts: [
       {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
       }
     ],
     firstName: {
       type: String
     },
     lastName: {
       type: String
     },
     username: {
       type: String,
       lowercase: true,
       unique: true,
       required: [true, "can't be blank"],
       match: [/^[a-zA-Z0-9]+$/, "is invalid"],
       index: true
     },

     sentRequests: [
       {
         username: {
           type: String,
           default: ""
         }
       }
     ],
     subscriptions: [
       {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Course"
       }
     ],
     password: {
       default: "",
       required: [true, "can't be blank"],
       type: String
     }
   },
   {timestamps: true}
 )

 UserSchema.plugin(uniqueValidator, {message: "is already taken."})
 export default mongoose.model("User", UserSchema)

// USER GRAPHQL SCHEMA
type User {
   _id: ID
   contacts: [User]
   email: String!
   username: String
   subscriptions: [Course]
   createdAt: String
   updatedAt: String
 }

 type AuthPayload {
   token: String
   user: User
   error: [Error]
 }

 input LoginInput {
   email: String!
   password: String!
 }

 type Mutation {
   login(input: LoginInput): AuthPayload
 }

// USER RESOLVER
 const login = async (parent, args, ctx, info) => {
   let email = args.email

   let user = await User.findOne({email})
     .populate("subscriptions")
     .populate("contacts")
     .exec()

  if (!user) {
     arrayOfErrors.push({
       path: "email",
       message: "invalid email"
     })
   } else if (user) {

   console.log("user: ", user)

   return {
     user,
     error: arrayOfErrors
   }
 }

 Mutation: {
   login
 }

// CONSOLE LOG CLIENTSIDE
user:
  confirmed: true
  contacts: Array(3)  // returns an array of 3 items??  It's [] in mongodb
    0: {_id: null, username: null}
    1: {_id: null, username: null}
    2: {_id: null, username: null}
    length: 3
    __proto__: Array(0)
  subscriptions: Array(1)
    0: {_id: "5cd36fc1c8d1e222b99d9c58", title: "Korean Class 101 Study",
    length: 1
    __proto__: Object
__proto__: Object

// CONSOLE LOG SERVERSIDE
POST /graphql 200 64.359 ms - -
user: {
  contacts: [ ],
  subscriptions:
   [ { _id: 5cd6f7f8212af32c75555d4b,
       subscribers: 2,
       owner: 5cd36edec8d1e222b99d9c57,
       createdAt: 2019-05-09T00:09:37.845Z,
       updatedAt: 2019-05-11T16:36:14.661Z,
       __v: 23 } ],
  password: '$2b$10$bkjiazklcoqlkJSJSAioxoAqkoajsdjnqjkiaallaadfadfp7zS',
  _id: 5cd36edec8d1e222b99d9c57,
  email: 'example@test.com',
  username: 'example',
  createdAt: 2019-05-09T00:05:50.314Z,
  updatedAt: 2019-05-29T17:23:21.545Z,
  __v: 32
}

I expected an empty array to return [ ], instead graphql returns an array of 3 items with null values.  Even if I add real contacts into the database it still returns the 3 items with null values.
The subscriptions are returning correctly yet it is almost identical to the contacts field with the exception of being a type "Course" in the mongoose model instead of type "User".

Body:
I doubt anyone will ever come across this type of error, but here's the solution in case you do.  During development I had placed this code in my resolver for testing purposes.  Removing it solved the problem.

// USER RESOLVER
...
Query: {...},

/* code to remove
User: {
  contacts: user => {
    return ["Mo", "Larry", "Curly"]
  }
}
*/

Mutation: {...}

A very trivial thing but having not been in this actual code for several months made it difficult to spot. I never thought the 3 stooges would ever give me so much headache.


问:
how to fix "cannot open shared object file" in Cshell script?
I am working on Linux system and have a Fortran executable e.g. a.exe successfully run by directly execute. I want to execute this a.exe inside a Cshell script, but is always report error as "error while loading shared libraries: libnetcdff.so.6: cannot open shared object file: No such file or directory"

when I do 'ldd a.exe', it report me some dependency of libraries for this executables.

libnetcdff.so.6 => /met5/ZR_LOCAL_LIBS/lib/libnetcdff.so.6 (0x00002ab536656000)

The library did existed, and I also have the path set as $LD_LIBRARY_PATH

the a.exe need two inputs $INFILE1, $INFILE2 and will generate the output at $OUTPUT

it can be executed by hand typing ./a.exe and providing the path of $INFILE1 and $INFILE2, however, when I write a simple Cshell script as the form:

```<code>#!/bin/csh
#
setenv BASE $PWD
setenv PROGNAME a.exe

cd $BASE

setenv INFILE1 $BASE/agtsc_ave_2017.nc
setenv INFILE2 $BASE/agtsc_ave_2029.nc
setenv OUTFILE $BASE/emis_pct_2029_relative_to_2017.nc

if ( -e $OUTFILE ) rm -f $OUTFILE
$BASE/$PROGNAME
</code>```

it will report the error as:
a.exe: error while loading shared libraries: libnetcdff.so.6: cannot open shared object file: No such file or directory

I have no idea how to debug through this. Can anyone help me to fix it? Thanks a lot!

答: I think I found the problem. I use other people's .cshrc, so there is a $path issue causing the shell script can not find the corresponding libraries. I delete the older .cshrc file and create a new one based on my condition, the problem is gone. Thanks. </p>

Body:
I am working on Linux system and have a Fortran executable e.g. a.exe successfully run by directly execute. I want to execute this a.exe inside a Cshell script, but is always report error as "error while loading shared libraries: libnetcdff.so.6: cannot open shared object file: No such file or directory"

when I do 'ldd a.exe', it report me some dependency of libraries for this executables.

libnetcdff.so.6 => /met5/ZR_LOCAL_LIBS/lib/libnetcdff.so.6 (0x00002ab536656000)

The library did existed, and I also have the path set as $LD_LIBRARY_PATH

the a.exe need two inputs $INFILE1, $INFILE2 and will generate the output at $OUTPUT

it can be executed by hand typing ./a.exe and providing the path of $INFILE1 and $INFILE2, however, when I write a simple Cshell script as the form:

#!/bin/csh
#
setenv BASE $PWD
setenv PROGNAME a.exe

cd $BASE

setenv INFILE1 $BASE/agtsc_ave_2017.nc
setenv INFILE2 $BASE/agtsc_ave_2029.nc
setenv OUTFILE $BASE/emis_pct_2029_relative_to_2017.nc

if ( -e $OUTFILE ) rm -f $OUTFILE
$BASE/$PROGNAME

it will report the error as:
a.exe: error while loading shared libraries: libnetcdff.so.6: cannot open shared object file: No such file or directory

I have no idea how to debug through this. Can anyone help me to fix it? Thanks a lot!


问:
Cocoa-Touch internals: How does the view know its controller?
If you add a subview to a view or add a view to a window, how does iOS know which controller this view belongs too?

Easy example:
Have a UIView without UIViewController and add it to the window [window addSubView:myView] --> it will not rotate.
Now use a UIViewController, have it implement shouldAutoRotateToInterfaceOrientation: and add the controller's view to the window: [window addSubView:myController.view] --> magically, the view will adjust to interface orientation.

But look at the code: in both cases a UIView was added. How can iOS possibly be aware that in the second case a UIViewController was involved?

I'm interested in how this is done internally. My best guess is that UIViewController.view is a setter which adds the controller to an internal array of controllers or assigns itself to some internal variable which holds the currently active controller.

答:
UIViewController has a private class method (called controllerForView:, I believe) which is used to find the view's controller. Internally, there is probably a table used to connect the two together, and this method simply finds the proper location in that table and returns its value. When the result is nil, the default implementation will be used (don't rotate).

If you want to be sure about the name of the method, set a breakpoint in -[UIView becomeFirstResponder], tap on a text field, and step through the code until it shows up in the call stack. I suggest using becomeFirstResponder because it is easier to control than most things which get the view controller.


问:
Object parameter in python class declaration

Concepts of objects in python classes

While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object?
Is it a base class or simply an object or a parameter ?

for e.g. :

New style for creating a class in python

```<code>class Class_name(object):
pass
</code>```

If object is just another class which is base class for Class_name (inheritance) then what will be termed as object in python ?

答:
Object is a generic term.  It could be a class, a string, or any type. (and probably many other things)

As an example look at the term OOP, "Object oriented programming".  Object has the same meaning here.

Body:
Concepts of objects in python classes

While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object?
Is it a base class or simply an object or a parameter ?

for e.g. :

New style for creating a class in python

class Class_name(object):
pass

If object is just another class which is base class for Class_name (inheritance) then what will be termed as object in python ?


问:
Extraction of Data using tbodyclass and Beautifulsoup
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

```<code>import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)
</code>```

Here is the Error

```<code>Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?
</code>```

答:
It's not clear exactly what information you are trying to extract, but doing:

```<code>for res in required_data:
   real_data=res.find_all("tbody", class_="dataSmall")
   for dat in real_data:
       print(dat.text.strip())
</code>```

outputs lots of info about lots of people...

EDIT: If you're looking for the summary table, you need this:

```<code>import pandas as pd

tabs = pd.read_html(url)
print(tabs[0]
</code>```

and there's your table.

Body:
Extraction with tbody class using BeautifulSoup and Python 3.

Im trying to extract the table (summary) on top of it. Im using BeautifulSoup for extraction. However I get the following error while using tclass to extract the table containing name,age,info etc

I am aware I can use the previous table{class :datatable} to extract the table .However I want to try extracting using tbody class

How do i extract the table with tbodyclass and what error am i making?
Im bit new to web scraping and any  detailed help would be appreciated

Here is the code

import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests

urls=['https://www.reuters.com/finance/stocks/company- officers/GOOG.O',
      'https://www.reuters.com/finance/stocks/company- officers/AMZN',
      'https://www.reuters.com/finance/stocks/company- officers/AAPL']

for item in urls:
   response=requests.get(item)
   data=response.content
   soup=BeautifulSoup(data,'html.parser')
   required_data=soup.find_all(class_='moduleBody')
   real_data=required_data.find_all(tbodyclass_='dataSmall')
   print(real_data)

Here is the Error

Traceback (most recent call last):
 File "C:\Users\XXXX\Desktop\scrape.py", line 15, in <module>
real_data=required_data.find_all(tbodyclass_='dataSmall')
 File "C:\Users\XXXX\AppData\Local\Programs\Python\Python37\lib\site-
 packages\bs4\element.py", line 1620, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find_all'. You're
probably treating a list of items like a single item. Did you call
find_all() when you meant to call find()?

Body:
It's not clear exactly what information you are trying to extract, but doing:

for res in required_data:
   real_data=res.find_all("tbody", class_="dataSmall")
   for dat in real_data:
       print(dat.text.strip())

outputs lots of info about lots of people...

EDIT: If you're looking for the summary table, you need this:

import pandas as pd

tabs = pd.read_html(url)
print(tabs[0]

and there's your table.


问:
Make a programmatic change to trix without triggering trix-change
I'm trying to programmatically make a change to trix using something like:

```<code>element.editor.insertHTML(' ')
</code>```

This works without issue, but unfortunately this is already within a trix-change event. So the insertHTML triggers itself again, and we're stuck in a loop.

So the question is, is there any way to make a change to the editor without triggering trix-change?

Thanks.

答:
You could set a flag to ignore the next trix-change event. Something like:

let ignoreNextChange = false

element.addEventListener("trix-change", () => {
  if (ignoreNextChange) {
    ignoreNextChange = false
    return
  }
  if (/* Your logic for inserting a non-breaking space */) {
    ignoreNextChange = true
    element.editor.insertHTML(" ")
  }
})
```

Body:
I'm trying to programmatically make a change to trix using something like:

element.editor.insertHTML(' ')

This works without issue, but unfortunately this is already within a trix-change event. So the insertHTML triggers itself again, and we're stuck in a loop.

So the question is, is there any way to make a change to the editor without triggering trix-change?

Thanks.

Body:
You could set a flag to ignore the next trix-change event. Something like:

let ignoreNextChange = false

element.addEventListener("trix-change", () => {
  if (ignoreNextChange) {
    ignoreNextChange = false
    return
  }
  if (/* Your logic for inserting a non-breaking space */) {
    ignoreNextChange = true
    element.editor.insertHTML("&nbsp;")
  }
})


问:
Is there a good way to display collected data to the user in HTML or javascript and still keep the data?
I am trying to pick up some user data from a HTML page by having the user type it in. I want to retain the data, (they are ID numbers of sorts) display it back to the user on any subsequent section they go to (currently different href sections on one page), collect more data from them and eventually present the data to the user as a review. I thought this would be a little like HTML “Hello World”, but it’s proving to be more than that. . I found out that document.write() is the wrong way to go about it, but no good answer on how to accomplish this. Collecting this data is the first thing I need from the user, and then I will collect more data, so I have to be able to get data and let the user move around.

I have spent a day and a half on this site and others, pulled out two books (yes, paper!) looking for answers, but not reaching a usable solution. Nothing seems to work. When complete, I want to give the user a chance to correct the data before submitting, most likely to post at the moment, but would be a server if implemented.

Here’s how I am collecting, simplified as much as possible:

```<code><form name="getNPIandTIN">
<p> Please enter NPI and TIN</p>
Provider NPI: <input type="number" name="Provider_NPI">
<p>
Provider TIN: <input type="number" name="Provider_TIN">
<input type="submit" value="Submit NPI and TIN">
</form>

...

<p id="demo"></p>

Inner HTML action
<script> document.getElementById"demo").innerHTML=
document.getNPIandTIN.Provider_NPI.value
</script>
</code>```

No error messages; things just don't work. I want to ask the user to enter field 1, have them type it in, click for acceptance, store the data in a variable and echo the information back to them. Sounds pretty simple, but it isn't.

答:
The form is going to get in your way, you don't need it unless you want to post the data somewhere. Since you just want to grab the data directly from the input fields and store it yourself you can just do something like this:</p>

```<code><div>
  Provider NPI: <input type="number" id="providerNPI" name="Provider_NPI" value="">
  <br>
  Provider TIN: <input type="number" id="providerTIN" name="Provider_TIN" value="">
  <br>
  <button onclick="captureNumbers()">Submit NPI and TIN</button>
</div>

<p id="demo"></p>

<script>
  function displayNumbers() {
    // get the stored values and show them to the user
    var providerNPI = sessionStorage.getItem('providerNPI');
    var providerTIN = sessionStorage.getItem('providerTIN');
    document.getElementById("demo").innerHTML = "NPI: " + providerNPI + ", TIN: " + providerTIN;
  }

  function storeNumbers(numbersObject) {
    // store the values locally so you can access them wherever you need them
    sessionStorage.setItem('providerNPI', numbersObject.providerNPI);
    sessionStorage.setItem('providerTIN', numbersObject.providerTIN);
  }

  function captureNumbers() {
    // first get the values from the input fields as a javascript object so you don't have to pass a ton of individual variables
    var providerNumbers = {};
    providerNumbers.providerNPI = document.getElementById("providerNPI").value;
    providerNumbers.providerTIN = document.getElementById("providerTIN").value;

    // then pass the object variable to the storage function
    storeNumbers(providerNumbers);

    // then call the display function
    displayNumbers();
  }
</script>
</code>```

Body:
I am trying to pick up some user data from a HTML page by having the user type it in. I want to retain the data, (they are ID numbers of sorts) display it back to the user on any subsequent section they go to (currently different href sections on one page), collect more data from them and eventually present the data to the user as a review. I thought this would be a little like HTML “Hello World”, but it’s proving to be more than that. . I found out that document.write() is the wrong way to go about it, but no good answer on how to accomplish this. Collecting this data is the first thing I need from the user, and then I will collect more data, so I have to be able to get data and let the user move around.

I have spent a day and a half on this site and others, pulled out two books (yes, paper!) looking for answers, but not reaching a usable solution. Nothing seems to work. When complete, I want to give the user a chance to correct the data before submitting, most likely to post at the moment, but would be a server if implemented.

Here’s how I am collecting, simplified as much as possible:

<form name="getNPIandTIN">

 Please enter NPI and TIN

Provider NPI: <input type="number" name="Provider_NPI">

Provider TIN: <input type="number" name="Provider_TIN">
<input type="submit" value="Submit NPI and TIN">
</form>

...

Inner HTML action

No error messages; things just don't work. I want to ask the user to enter field 1, have them type it in, click for acceptance, store the data in a variable and echo the information back to them. Sounds pretty simple, but it isn't.

Body:
The form is going to get in your way, you don't need it unless you want to post the data somewhere. Since you just want to grab the data directly from the input fields and store it yourself you can just do something like this:

<div>
  Provider NPI: <input type="number" id="providerNPI" name="Provider_NPI" value="">
  <br>
  Provider TIN: <input type="number" id="providerTIN" name="Provider_TIN" value="">
  <br>
  <button onclick="captureNumbers()">Submit NPI and TIN</button>
</div>

<p id="demo"></p>

<script>
  function displayNumbers() {
    // get the stored values and show them to the user
    var providerNPI = sessionStorage.getItem('providerNPI');
    var providerTIN = sessionStorage.getItem('providerTIN');
    document.getElementById("demo").innerHTML = "NPI: " + providerNPI + ", TIN: " + providerTIN;
  }

  function storeNumbers(numbersObject) {
    // store the values locally so you can access them wherever you need them
    sessionStorage.setItem('providerNPI', numbersObject.providerNPI);
    sessionStorage.setItem('providerTIN', numbersObject.providerTIN);
  }

  function captureNumbers() {
    // first get the values from the input fields as a javascript object so you don't have to pass a ton of individual variables
    var providerNumbers = {};
    providerNumbers.providerNPI = document.getElementById("providerNPI").value;
    providerNumbers.providerTIN = document.getElementById("providerTIN").value;

    // then pass the object variable to the storage function
    storeNumbers(providerNumbers);

    // then call the display function
    displayNumbers();
  }
</script>


问:
Div scrolling issues while zoomed in on mobile device
I have a chat log div on my webpage that will scroll fine while on the computer, and it will also scroll fine on mobile while the screen is at the default (zoomed out) position; however, when I zoom in and try to scroll the div, the div will scroll slightly, but unfortunately the entire screen will also scroll (more so than the div)...

Is there a way to prevent this from happening while zoomed?

CSS:

```<code>.a
{
    border:1px solid black;
    width:30vw;
    height:30vw;
    position:relative;
    display:inline-block;
    overflow-y:auto;
    overflow:scroll;
    font-size:1.1vw;
    text-align:left;
background-color:white;
}
</code>```

HTML:

```<code><div class = "a" id = "chatbox">
</code>```

答:
If the following doesn't work, and if you're ok with it, share your project source with me through a repo or something.

I was able to seemingly fix the issue (on FF and Chrome emulating an IPhone X) by changing the structure of the message nodes.

.a {
  border: 1px solid black;
  width: 30vw;
  height: 30vw;
  position: relative;
  display: inline-block;
  overflow-y: auto;
  overflow: scroll;
  font-size: 1.1vw;
  text-align: left;
  background-color: white;
}

.msg {
  width: 100%;
  font-size: 1.1vw;
  text-align: left;
}

.name {
  color: blue
}

.msgContent {
  color: black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a" id="chatbox">
  <div class="msg">
      <span class="name">Name:</span>
      <span class="msgContent">This is a message.</span>
  </div>
</div>

<!-- what you had --

<div class="a" id="chatbox">
  <label style="color:a1bd77; cursor: pointer;" onclick="profilePreview(), reply_click(this.id)" id="name">name</label>
  : Okay time to start a fresh chat
  <br >
</div>

-- what you had --></code>```

I did not test on an actual phone, so results may vary.

Body:
I have a chat log div on my webpage that will scroll fine while on the computer, and it will also scroll fine on mobile while the screen is at the default (zoomed out) position; however, when I zoom in and try to scroll the div, the div will scroll slightly, but unfortunately the entire screen will also scroll (more so than the div)...

Is there a way to prevent this from happening while zoomed?

CSS:

.a
{
    border:1px solid black;
    width:30vw;
    height:30vw;
    position:relative;
    display:inline-block;
    overflow-y:auto;
    overflow:scroll;
    font-size:1.1vw;
    text-align:left;
background-color:white;
}

HTML:

Body:
If the following doesn't work, and if you're ok with it, share your project source with me through a repo or something.

I was able to seemingly fix the issue (on FF and Chrome emulating an IPhone X) by changing the structure of the message nodes.

.a {
  border: 1px solid black;
  width: 30vw;
  height: 30vw;
  position: relative;
  display: inline-block;
  overflow-y: auto;
  overflow: scroll;
  font-size: 1.1vw;
  text-align: left;
  background-color: white;
}

.msg {
  width: 100%;
  font-size: 1.1vw;
  text-align: left;
}

.name {
  color: blue
}

.msgContent {
  color: black
}

<div class="a" id="chatbox">
  <div class="msg">
      <span class="name">Name:</span>
      <span class="msgContent">This is a message.</span>
  </div>
</div>

<!-- what you had --

<div class="a" id="chatbox">
  <label style="color:a1bd77; cursor: pointer;" onclick="profilePreview(), reply_click(this.id)" id="name">name</label>
  : Okay time to start a fresh chat
  <br >
</div>

-- what you had -->

I did not test on an actual phone, so results may vary.


问:
Combining UITabController & UINavigation controller programmatically http://t.co/R52RlUL UITabController & UINavigation controller programmatically
I have created a UItabbarcontroller and 2 views with UITableViews just using code (no IB stuff) and I want to now add a navigation bar at the top that will include add and edit buttons, however I seem to be tripping up and blowing my app up or adding navgation controller to a 3rd tab only.

Here is my main code for adding the tab bar and switching views

FYI -  I am using XCode4

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.mainTabBar = [[UITabBarController alloc] init];

// create the 2 views
tableViewController* vc1 = [[tableViewController alloc] init];
tableViewController2* vc2 = [[tableViewController2 alloc] init];

// put them in an array
NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];

// for the tab bar
mainTabBar.viewControllers = controllers;

// Add the tab bar controller's current view as a subview of the window
[self.window addSubview:self.mainTabBar.view];

// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}
</code>```

答:
Where do you want navigation controller(s)? You have to create one for each tab you want one in the UITabBarController.

You add a navigationController in conjunction with the first view controller on its stack. Try this:

```<code>// create the controllers for UITabBarController
tableViewController *vc1 = [[[TableViewController alloc] init] autorelease];
navController *nav1 = [[[UINavigationController alloc] initWithRootViewController:vc1] autorelease];

tableViewController *vc2 = [[[TableViewController alloc] init] autorelease];
navController *nav2 = [[[UINavigationController alloc] initWithRootViewController:vc2] autorelease];

// put them in an array
NSArray *controllers = [NSArray arrayWithObjects:nav1, nav2, nil];

// rest of your code
</code>```

Also note that you need to release anything you alloc or retain. You can do it as I did by adding autorelease when you initialize them or you can release them explicitly after you've added them to the controllers array.

You then configure the navigationItem for each view controller in its loadView or viewDidLoad method depending on how you implemented it.

Body:
I have created a UItabbarcontroller and 2 views with UITableViews just using code (no IB stuff) and I want to now add a navigation bar at the top that will include add and edit buttons, however I seem to be tripping up and blowing my app up or adding navgation controller to a 3rd tab only.

Here is my main code for adding the tab bar and switching views

FYI -  I am using XCode4

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.mainTabBar = [[UITabBarController alloc] init];

// create the 2 views
tableViewController* vc1 = [[tableViewController alloc] init];
tableViewController2* vc2 = [[tableViewController2 alloc] init];

// put them in an array
NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];

// for the tab bar
mainTabBar.viewControllers = controllers;

// Add the tab bar controller's current view as a subview of the window
[self.window addSubview:self.mainTabBar.view];

// Override point for customization after application launch.
[self.window makeKeyAndVisible];
return YES;
}

Body:
Where do you want navigation controller(s)? You have to create one for each tab you want one in the UITabBarController.

You add a navigationController in conjunction with the first view controller on its stack. Try this:

// create the controllers for UITabBarController
tableViewController *vc1 = [[[TableViewController alloc] init] autorelease];
navController *nav1 = [[[UINavigationController alloc] initWithRootViewController:vc1] autorelease];

tableViewController *vc2 = [[[TableViewController alloc] init] autorelease];
navController *nav2 = [[[UINavigationController alloc] initWithRootViewController:vc2] autorelease];

// put them in an array
NSArray *controllers = [NSArray arrayWithObjects:nav1, nav2, nil];

// rest of your code

Also note that you need to release anything you alloc or retain. You can do it as I did by adding autorelease when you initialize them or you can release them explicitly after you've added them to the controllers array.

You then configure the navigationItem for each view controller in its loadView or viewDidLoad method depending on how you implemented it.


答: All objects in python are ultimately derived from "object". You don't need to be explicit about it in python 3, but it's common to explicitly derive from object.</p>

Title: Object parameter in python class declaration


问:
How to correctly set the Uri of an image from a folder selected by the user to show in an ImageView?
I need to display an image which I know the file name but I don't know the folder, which must be specified by the user.

I use Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); to get the folder from the user. It returns an Uri with a path along these lines:

content://com.android.externalstorage.documents/tree/primary%3ADownload

Now I need to display an image from this folder in an ImageView. I tried the following:

```<code>Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(chosenFolder + "/image.png"));
ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);
</code>```

The first line throws the following exception:

java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary%3ADownload/image.png

Replacing %3A by : doesn't work.

How to correctly set the Uri to display the image?

答:
I managed to achieve what I wanted with an InputStream.

```<code>InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
</code>```

To work, the imageUri must be an Uri along the lines of:

content://com.android.externalstorage.documents/document/primary:Download/image.png

However, this means you will be accessing files you do not have permission by default. This means you will have to deal with getting permission.

This is not what I wanted so I scrapped this approach.

Body:
I need to display an image which I know the file name but I don't know the folder, which must be specified by the user.

I use Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); to get the folder from the user. It returns an Uri with a path along these lines:

content://com.android.externalstorage.documents/tree/primary%3ADownload

Now I need to display an image from this folder in an ImageView. I tried the following:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),
Uri.parse(chosenFolder + "/image.png"));
ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmap);

The first line throws the following exception:

java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary%3ADownload/image.png

Replacing %3A by : doesn't work.

How to correctly set the Uri to display the image?

Body:
I managed to achieve what I wanted with an InputStream.

InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);

To work, the imageUri must be an Uri along the lines of:

content://com.android.externalstorage.documents/document/primary:Download/image.png

However, this means you will be accessing files you do not have permission by default. This means you will have to deal with getting permission.

This is not what I wanted so I scrapped this approach.


问:
I get this error 0xC0000005: Access violation writing location 0x0086B000
I tired the same code on https://repl.it/languages/c and i get no errors but when i paste the same code on Visual Studio 2017 I get this error regarding:

```<code>#include <stdio.h>
#include <string.h>
char input[100];
int calc();
int main() {
    printf("Type \"help\" or enter a mathematical expression\n");
    calc();
}
int calc() {
    printf("Calc:\\> ");
    scanf_s("%s", input);
    if (strcmp(input, "help") == 0) {
        printf("Help is on the way\n");
    }
    else {
        printf("Answer:\\> %s\n", input);
    }
    calc();
    return 0;
}
</code>```

But I get this error when i run it:

```<code>Exception thrown at 0x50FFD4EC (ucrtbased.dll) in Project.exe: 0xC0000005: Access violation writing location 0x0086B000.
</code>```

答:
Problem 1:

You are calling calc() recursively without a base case. This means that you will inevitably cause the stack to overflow when you call that function.

Solution:
Remove the recursive call to calc() in calc().

Problem 2:

scanf_s requires that the string argument satisfying a %s format specifier comes immediately before an integer variable giving the length of the buffer. See its documentation on MSDN.

Solution: pass the length of the string as well:

```<code>scanf_s("%s", input, 100);
</code>```

Side note: checking the return value of scanf-family functions is usually a good idea.

Body:
I tired the same code on https://repl.it/languages/c and i get no errors but when i paste the same code on Visual Studio 2017 I get this error regarding:

#include <stdio.h>
#include <string.h>
char input[100];
int calc();
int main() {
    printf("Type \"help\" or enter a mathematical expression\n");
    calc();
}
int calc() {
    printf("Calc:\\> ");
    scanf_s("%s", input);
    if (strcmp(input, "help") == 0) {
        printf("Help is on the way\n");
    }
    else {
        printf("Answer:\\> %s\n", input);
    }
    calc();
    return 0;
}

But I get this error when i run it:

Exception thrown at 0x50FFD4EC (ucrtbased.dll) in Project.exe: 0xC0000005: Access violation writing location 0x0086B000.

Body:
Problem 1:

You are calling calc() recursively without a base case. This means that you will inevitably cause the stack to overflow when you call that function.

Solution:
Remove the recursive call to calc() in calc().

Problem 2:

scanf_s requires that the string argument satisfying a %s format specifier comes immediately before an integer variable giving the length of the buffer. See its documentation on MSDN.

Solution: pass the length of the string as well:

scanf_s("%s", input, 100);

Side note: checking the return value of scanf-family functions is usually a good idea.


问:
Rails: How to test if an attribute of a class object is required in the model policy?
Briefly, I have a model User with name, email and comment as attributes.

```<code>validates_presence_of :name
validates_presence_of :email
</code>```

So 'name' and 'email' are required but not 'comment'.

```<code>my_user = User.new
</code>```

I'd like to find a way to test like my_user.name.required? or User.name.required? kind of thing.

My goal is to create a form and to add a specific class dynamically to the form item span or td depending on if this item is set as "validates_presence_of"

I tried to search for it but did not find anything about. Is there a easy way to do this?

Thanks

答:
I can't comment as I don't have 50 rep, but on Rails 5+ this doesn't work anymore. You can do:</p>

```<code>ModelName.validators_on(:attribute).any? { |v| v.class == ActiveRecord::Validations::PresenceValidator }
</code>```

Body:
Briefly, I have a model User with name, email and comment as attributes.

validates_presence_of :name
validates_presence_of :email

So 'name' and 'email' are required but not 'comment'.

my_user = User.new

I'd like to find a way to test like my_user.name.required? or User.name.required? kind of thing.

My goal is to create a form and to add a specific class dynamically to the form item span or td depending on if this item is set as "validates_presence_of"

I tried to search for it but did not find anything about. Is there a easy way to do this?

Thanks

Body:
I can't comment as I don't have 50 rep, but on Rails 5+ this doesn't work anymore. You can do:

ModelName.validators_on(:attribute).any? { |v| v.class == ActiveRecord::Validations::PresenceValidator }


问:
Vuetify aligning stacked elements within tool bar/app bar
I have been playing with vuetify, I've been trying to mimic a specific layout to see if I can do it and add tabs. So far, I've been able to center stuff but in a way that I view as weird. I want the h1 to be under the avatar.

I used v-spacer to center things and added tabs that are centered at the bottom

when I use v-slot it aligns everything in the middle.
If it's just the avatar it's perfect.

When I add an h1 under it does not go directly under.

I've been looking at the api and can't figure out.

Here's a link to the codepen https://codepen.io/sanwil9/pen/mYQaRx

```<code><div id="app">
  <v-app id="inspire">
    <v-app-bar prominent extended
    src="https://images3.alphacoders.com/114/114869.jpg"
    dark
    >
      <v-spacer></v-spacer>
      <v-avatar
                size="90"
              >
                <img

                  src="https://media.licdn.com/dms/image/C5103AQHlAw-naKhLig/profile-displayphoto-shrink_100_100/0?e=1564617600&v=beta&t=xLgLkONVQpvaxUZfkcI3TYG9yoditHjjoWNbRUKHWqk"
                  alt="Avatar"
                />
              </v-avatar>
      <h1>Super Steve</h1>
      <v-spacer></v-spacer>
       <template v-slot:extension>
      </template>

      <template v-slot:extension>
        <v-tabs centered>
          <v-tab>Tab 1</v-tab>
          <v-tab>Tab 2</v-tab>
          <v-tab>Tab 3</v-tab>
        </v-tabs>
      </template>
    </v-app-bar>
    <v-content>
      <v-container grid-list-md text-xs-center>
        <v-layout row wrap>
          <v-flex xs12>
            <v-card dark color="primary">
              <v-card-text class="px-0">12</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 2" :key="`6${i}`" xs6>
            <v-card dark color="secondary">
              <v-card-text class="px-0">6</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 3" :key="`4${i}`" xs4>
            <v-card dark color="primary">
              <v-card-text class="px-0">4</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 4" :key="`3${i}`" xs3>
            <v-card dark color="secondary">
              <v-card-text class="px-0">3</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 6" :key="`2${i}`" xs2>
            <v-card dark color="primary">
              <v-card-text class="px-0">2</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 12" :key="`1${i}`" xs1>
            <v-card dark color="secondary">
              <v-card-text class="px-0">1</v-card-text>
            </v-card>
          </v-flex>
        </v-layout>
      </v-container>

    </v-content>

  </v-app>
</div>
</code>```

Help me align the h1 under the gravatar. I want it to be aligned.

答:
Within the <v-app-bar> you can include the following:

```<code><v-container>
    <v-layout row>
        a spacer, the avatar, and another spacer
    </v-layout>
    <v-layout row>
       a spacer, the <h1>, and another spacer
    </v-layout>
</v-container>
the template for the extension
</code>```

This will insert a grid which will allow you to turn the single container of default content into two separate rows.

Body:
I have been playing with vuetify, I've been trying to mimic a specific layout to see if I can do it and add tabs. So far, I've been able to center stuff but in a way that I view as weird. I want the h1 to be under the avatar.

I used v-spacer to center things and added tabs that are centered at the bottom

when I use v-slot it aligns everything in the middle.
If it's just the avatar it's perfect.

When I add an h1 under it does not go directly under.

I've been looking at the api and can't figure out.

Here's a link to the codepen https://codepen.io/sanwil9/pen/mYQaRx

  <v-app id="inspire">
    <v-app-bar prominent extended
    src="https://images3.alphacoders.com/114/114869.jpg"
    dark
    >
      <v-spacer></v-spacer>
      <v-avatar
                size="90"
              >

              </v-avatar>

Super Steve

      <v-spacer></v-spacer>
       <template v-slot:extension>
      </template>

      <template v-slot:extension>
        <v-tabs centered>
          <v-tab>Tab 1</v-tab>
          <v-tab>Tab 2</v-tab>
          <v-tab>Tab 3</v-tab>
        </v-tabs>
      </template>
    </v-app-bar>
    <v-content>
      <v-container grid-list-md text-xs-center>
        <v-layout row wrap>
          <v-flex xs12>
            <v-card dark color="primary">
              <v-card-text class="px-0">12</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 2" :key="`6${i}`" xs6>
            <v-card dark color="secondary">
              <v-card-text class="px-0">6</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 3" :key="`4${i}`" xs4>
            <v-card dark color="primary">
              <v-card-text class="px-0">4</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 4" :key="`3${i}`" xs3>
            <v-card dark color="secondary">
              <v-card-text class="px-0">3</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 6" :key="`2${i}`" xs2>
            <v-card dark color="primary">
              <v-card-text class="px-0">2</v-card-text>
            </v-card>
          </v-flex>
          <v-flex v-for="i in 12" :key="`1${i}`" xs1>
            <v-card dark color="secondary">
              <v-card-text class="px-0">1</v-card-text>
            </v-card>
          </v-flex>
        </v-layout>
      </v-container>

    </v-content>

  </v-app>

Help me align the h1 under the gravatar. I want it to be aligned.

Body:
Within the <v-app-bar> you can include the following:

<v-container>
    <v-layout row>
        a spacer, the avatar, and another spacer
    </v-layout>
    <v-layout row>
       a spacer, the <h1>, and another spacer
    </v-layout>
</v-container>
the template for the extension

This will insert a grid which will allow you to turn the single container of default content into two separate rows.


问:
Reading in columns for a .csv file
I need to read in data from a .csv file that is outputted by an iOS application.

In doing so, I need to print independent columns and their data when they are called (if someone inputs 'interval', the whole interval column must be printed).

I've opened and read it my file, but I don't know how to store it and then recall it when I need it. I honestly do not know how to even try it, I'm used to be able to use line.split(separator), but the data is already stored in a table.

```<code># EPIC Sports variable stores, translating boditrak to tangible values.

def main ():
    print ("Welcome to Epic Sports Boditrak Info processor")
    filename = input("Enter the full name of the file you'd like to read: ")
    f = open(filename,"r")
    lines = []
    lines = f.readlines ()
    for x in lines:
        print (x)
    f.close ()
    interval = [ ]
    total_force = [ ]
    left_force = [ ]
    right_force = [ ]
    COPx_disp = [ ]
    COPy_disp = [ ]
    COPx_velo = [ ]
    COPy_velo = [ ]

main ()
</code>```

I get IndexError when I try to store as a list, then recall list. I believe there are too many trials for it to be a list.

答:
Iterating over a file is easy and fast for amounts of text that can be displayed.  Do you need to store some data structure?  I recommend you parse the headings, and then at each request iterate across all lines.

I can't commend on your line.split(separator) issue without seeing the data.  If it is XML issues then I can only suggest an XML parser.  Otherwise, perhaps you need to do some trickery and define your own split function for this type of file.

Regarding the index errors, perhaps you have incomplete rows?   Catch exceptions as you iterate through the file in that case.   Since you no longer are trying to store the file as some list structure, you should have less issue handling these.

Title: Reading in columns for a .csv file

Body:
I need to read in data from a .csv file that is outputted by an iOS application.

In doing so, I need to print independent columns and their data when they are called (if someone inputs 'interval', the whole interval column must be printed).

I've opened and read it my file, but I don't know how to store it and then recall it when I need it. I honestly do not know how to even try it, I'm used to be able to use line.split(separator), but the data is already stored in a table.

# EPIC Sports variable stores, translating boditrak to tangible values.

def main ():
    print ("Welcome to Epic Sports Boditrak Info processor")
    filename = input("Enter the full name of the file you'd like to read: ")
    f = open(filename,"r")
    lines = []
    lines = f.readlines ()
    for x in lines:
        print (x)
    f.close ()
    interval = [ ]
    total_force = [ ]
    left_force = [ ]
    right_force = [ ]
    COPx_disp = [ ]
    COPy_disp = [ ]
    COPx_velo = [ ]
    COPy_velo = [ ]

main ()

I get IndexError when I try to store as a list, then recall list. I believe there are too many trials for it to be a list.


答:
From [Python 2.Docs]: Built-in Functions - class object (emphasis is mine):

Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes.

You could also check [Python]: New-style Classes (and referenced URLs) for more details.

>>> import sys
>>> sys.version
'2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>>
>>> class OldStyle():
...     pass
...
>>>
>>> class NewStyle(object):
...     pass
...
>>>
>>> dir(OldStyle)
['__doc__', '__module__']
>>>
>>> dir(NewStyle)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
 >>>
>>> old_style = OldStyle()
>>> new_style = NewStyle()
>>>
>>> type(old_style)
<type 'instance'>
>>>
>>> type(new_style)
<class '__main__.ClassNewStyle'>
```

In the above example, old_style and new_style are instances (or may be referred to as objects), so I guess the answer to your question is: depends on the context.

Body:
Concepts of objects in python classes

While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object?
Is it a base class or simply an object or a parameter ?

for e.g. :

New style for creating a class in python

class Class_name(object):
pass

If object is just another class which is base class for Class_name (inheritance) then what will be termed as object in python ?

Body:
From [Python 2.Docs]: Built-in Functions - class object (emphasis is mine):

Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes.

You could also check [Python]: New-style Classes (and referenced URLs) for more details.

>>> import sys
>>> sys.version
'2.7.10 (default, Mar  8 2016, 15:02:46) [MSC v.1600 64 bit (AMD64)]'
>>>
>>> class OldStyle():
...     pass
...
>>>
>>> class NewStyle(object):
...     pass
...
>>>
>>> dir(OldStyle)
['__doc__', '__module__']
>>>
>>> dir(NewStyle)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
 >>>
>>> old_style = OldStyle()
>>> new_style = NewStyle()
>>>
>>> type(old_style)
<type 'instance'>
>>>
>>> type(new_style)
<class '__main__.ClassNewStyle'>

In the above example, old_style and new_style are instances (or may be referred to as objects), so I guess the answer to your question is: depends on the context.


问:
What happens to a Startup IPI sent to an Active AP that is not in a Wait-for-SIPI state
In a previous Stackoverflow answer Margaret Bloom says:

Waking the APs

This is achieved by inssuing a INIT-SIPI-SIPI (ISS) sequence to the all the APs.

The BSP that will send the ISS sequence using as destination the
  shorthand All excluding self, thereby targeting all the APs.

A SIPI (Startup Inter Processor Interrupt) is ignored by all the CPUs
  that are waked by the time they receive it, thus the second SIPI is
  ignored if the first one suffices to wake up the target processors. It
  is advised by Intel for compatibility reason.

I've been doing multi processing code for years and my observation of hardware has been that on some processors it seems different than stated. I'm pretty sure I've observed Application Processors (AP) have their Instruction Pointer modified upon receipt of Startup IPI even when it was active (not in a Wait-for-Startup-IPI).

Is there any Intel documentation that states what an AP will do upon a receipt of a Startup IPI when not in a Wait-for-Startup-IPI state, or documents the behaviour as undefined? I can't seem to find a definitive answer in the Intel Software Documentation Manuals or the supplementary Intel document Minimal Boot Loader for Intel® Architecture.

Generally I write the initialization code to initialize and start an AP by assuming that the AP may get a SIPI and have its Instruction Pointer reset while in an active state (not in a Wait-for-Startup-IPI state).

I'm trying to determine the accuracy of Margaret Bloom's statement that a second Startup IPI will be ignored by an AP that has been previously awoken.

答:
Short Answer

Some CPUs do restart on the second SIPI

I don't know which CPUs restart on the second SIPI because I've been guarding against it for too long

I haven't checked, but I don't think Intel's documentation specifies the behavior for the "SIPI received by running CPU" case

If Intel's documentation does specify the behavior for Intel CPUs, then that doesn't mean CPUs from other vendors (AMD, VIA, SiS, Cyrix, ...) behave the same as Intel CPUs. Intel's manual is only "guaranteed" (excluding errata/specification updates) to apply to Intel's CPUs.

Longer Answer

When I first started implementing multi-CPU support (over 10 years ago) I followed Intel's startup procedure (from Intel'sMultiProcessor  Specification, with the time delays between INIT, SIPI and SIPI), and after the AP started it incremented a number_of_CPU_running counter (e.g. with a lock inc).

What I found is that some CPUs do restart when they receive the second SIPI; and on some computers that number_of_CPU_running counter would be incremented twice (e.g. with BSP and 3 AP CPUs, the number_of_CPU_running counter could end up being 7 and not 4).

Ever since I've been using memory synchronization to avoid the problem. Specifically, the sending CPU sets a variable (state = 0) before trying to start the receiving CPU, if/when the receiving CPU starts it changes the variable (state = 1) and waits for the variable to be changed again, and when the sending CPU sees that the variable was changed (by receiving CPU) it changes the variable (state = 2) to allow the receiving CPU to continue.

In addition; to improve performance, during the delay after sending the first SIPI the sending CPU monitors that variable, and if the receiving CPU changes the variable it will cancel the delay and won't send a second IPI at all. I also significantly increase the last delay, because it only expires if there's a failure (and you do not want to assume the CPU failed to start when it started too late, and end up with a CPU doing who-knows-what as the OS changes the contents of memory, etc. later).

In other words, I mostly ignore Intel's "Application Processor Startup" procedure (e.g. from section B.4 of Intel's MultiProcessor Specification) and my code for the sending CPU does:

```<code>    set synchronization variable (state = 0)
    send INIT IPI
    wait 10 milliseconds
    send SIPI IPI
    calculate time-out value ("now + 200 microseconds")
    while time-out hasn't expired {
        if the synchronization variable was changed jump to the "CPU_started" code
    }
    send a second SIPI IPI
    calculate time-out value ("now + 500 milliseconds")
    while time-out hasn't expired {
        if the synchronization variable was changed jump to the "CPU_started" code
    }
    do "CPU failed to start" error handling and return

CPU_started:
    set synchronization variable (state = 2) to let the started CPU know it can continue
</code>```

My code for the receiving CPU does this:

```<code>    get info from trampoline (address of stack this CPU needs to use, etc), because sending CPU may change the info after it knows this CPU started
    set synchronization variable (state = 1)
    while synchronization variable remains unchanged (state == 1) {
        pause (can't continue until sending CPU knows this CPU started)
    }
    initialize the CPU (setup protected mode or long mode, etc) and enter the kernel
</code>```

Note 1: Depending on the surrounding code (e.g. if the synchronization variable is in the trampoline and the OS recycles the trampoline to start other CPUs soon after); the sending CPU might need to wait for the receiving CPU to change the synchronization variable one last time (so that the sending CPU knows that it's safe to recycle/reset the synchronization variable).

Note 2: a CPU "almost always" starts on the first SIPI, and it's reasonable to assume that the second SIPI only exists in case the first SIPI got lost/corrupted and reasonable to assume that the 200 microsecond delay is a conservative worst case. For these reasons, my "cancel the time-out and skip the second SIPI" approach is likely to reduce the pair of 200 millisecond delays by a factor of 4 (e.g. 100 uS instead of 400 uS). The 10 millisecond delay (between INIT IPI and first SIPI) can be amortized (e.g. send INIT to N CPUs, then delay for 10 milliseconds, then do the remaining stuff for each of the N CPUs one at a time); and you can "snowball" the AP CPU startup (e.g. use BSP to start a group of N CPUs, then use 1+N CPUs in parallel to start (1+N)*M CPUs, then use 1+N*M CPUs to start (1+N*M)*L CPUs, etc. In other words; starting 255 CPUs with Intel's method adds up to 2.64 seconds of delays; but with sufficiently advanced code this can be reduced to less than 0.05 seconds.

Note 3: The "broadcast INIT-SIPI-SIPI" approach is broken and should never be used by an OS (because it makes detecting "CPU failed to start" hard, because it can start CPUs that are faulty, and because it can start CPUs that were disabled for other reasons - e.g. hyper-threading disabled by the user in the firmware's settings). Sadly, Intel's manual has some example code that describes the "broadcast INIT-SIPI-SIPI" approach that is intended for firmware developers (where the "broadcast INIT-SIPI-SIPI" approach makes sense and is safe), and beginners see this example and (incorrectly) assume that OS can use this approach.

Body:
Short Answer

Some CPUs do restart on the second SIPI

I don't know which CPUs restart on the second SIPI because I've been guarding against it for too long

I haven't checked, but I don't think Intel's documentation specifies the behavior for the "SIPI received by running CPU" case

If Intel's documentation does specify the behavior for Intel CPUs, then that doesn't mean CPUs from other vendors (AMD, VIA, SiS, Cyrix, ...) behave the same as Intel CPUs. Intel's manual is only "guaranteed" (excluding errata/specification updates) to apply to Intel's CPUs.

Longer Answer

When I first started implementing multi-CPU support (over 10 years ago) I followed Intel's startup procedure (from Intel'sMultiProcessor  Specification, with the time delays between INIT, SIPI and SIPI), and after the AP started it incremented a number_of_CPU_running counter (e.g. with a lock inc).

What I found is that some CPUs do restart when they receive the second SIPI; and on some computers that number_of_CPU_running counter would be incremented twice (e.g. with BSP and 3 AP CPUs, the number_of_CPU_running counter could end up being 7 and not 4).

Ever since I've been using memory synchronization to avoid the problem. Specifically, the sending CPU sets a variable (state = 0) before trying to start the receiving CPU, if/when the receiving CPU starts it changes the variable (state = 1) and waits for the variable to be changed again, and when the sending CPU sees that the variable was changed (by receiving CPU) it changes the variable (state = 2) to allow the receiving CPU to continue.

In addition; to improve performance, during the delay after sending the first SIPI the sending CPU monitors that variable, and if the receiving CPU changes the variable it will cancel the delay and won't send a second IPI at all. I also significantly increase the last delay, because it only expires if there's a failure (and you do not want to assume the CPU failed to start when it started too late, and end up with a CPU doing who-knows-what as the OS changes the contents of memory, etc. later).

In other words, I mostly ignore Intel's "Application Processor Startup" procedure (e.g. from section B.4 of Intel's MultiProcessor Specification) and my code for the sending CPU does:

    set synchronization variable (state = 0)
    send INIT IPI
    wait 10 milliseconds
    send SIPI IPI
    calculate time-out value ("now + 200 microseconds")
    while time-out hasn't expired {
        if the synchronization variable was changed jump to the "CPU_started" code
    }
    send a second SIPI IPI
    calculate time-out value ("now + 500 milliseconds")
    while time-out hasn't expired {
        if the synchronization variable was changed jump to the "CPU_started" code
    }
    do "CPU failed to start" error handling and return

CPU_started:
    set synchronization variable (state = 2) to let the started CPU know it can continue

My code for the receiving CPU does this:

    get info from trampoline (address of stack this CPU needs to use, etc), because sending CPU may change the info after it knows this CPU started
    set synchronization variable (state = 1)
    while synchronization variable remains unchanged (state == 1) {
        pause (can't continue until sending CPU knows this CPU started)
    }
    initialize the CPU (setup protected mode or long mode, etc) and enter the kernel

Note 1: Depending on the surrounding code (e.g. if the synchronization variable is in the trampoline and the OS recycles the trampoline to start other CPUs soon after); the sending CPU might need to wait for the receiving CPU to change the synchronization variable one last time (so that the sending CPU knows that it's safe to recycle/reset the synchronization variable).

Note 2: a CPU "almost always" starts on the first SIPI, and it's reasonable to assume that the second SIPI only exists in case the first SIPI got lost/corrupted and reasonable to assume that the 200 microsecond delay is a conservative worst case. For these reasons, my "cancel the time-out and skip the second SIPI" approach is likely to reduce the pair of 200 millisecond delays by a factor of 4 (e.g. 100 uS instead of 400 uS). The 10 millisecond delay (between INIT IPI and first SIPI) can be amortized (e.g. send INIT to N CPUs, then delay for 10 milliseconds, then do the remaining stuff for each of the N CPUs one at a time); and you can "snowball" the AP CPU startup (e.g. use BSP to start a group of N CPUs, then use 1+N CPUs in parallel to start (1+N)*M CPUs, then use 1+N*M CPUs to start (1+N*M)*L CPUs, etc. In other words; starting 255 CPUs with Intel's method adds up to 2.64 seconds of delays; but with sufficiently advanced code this can be reduced to less than 0.05 seconds.

Note 3: The "broadcast INIT-SIPI-SIPI" approach is broken and should never be used by an OS (because it makes detecting "CPU failed to start" hard, because it can start CPUs that are faulty, and because it can start CPUs that were disabled for other reasons - e.g. hyper-threading disabled by the user in the firmware's settings). Sadly, Intel's manual has some example code that describes the "broadcast INIT-SIPI-SIPI" approach that is intended for firmware developers (where the "broadcast INIT-SIPI-SIPI" approach makes sense and is safe), and beginners see this example and (incorrectly) assume that OS can use this approach.


问:
How does one access the ISBNDB using Java to find info on a book? Is it possible to use the ISBNDB api without using Maven or Gradle?
I'm trying to access the ISBNDB and get information about all the relavent data about a book so I can make a bibliography from that data for a school project. But, I'm having trouble accessing the ISBNDB and using the ISBNDB API through Java. I have never used Maven or Gradle before, so is it possible to use the ISBNDB API without using Maven or Gradle? And if so, can I get some example code to see how to use the ISBNDB API in Java?

I've tried using the example code from the ISBNDB API and plugging that in to my Java project, but it didn't compile or work correctly. It doesn't seem like the colon is supposed to be in the setRequestProperty method because when I tried putting the exact code into my compiler (IntelliJ), it wouldn't compile and it would just be angry with me. I've made a Rest Key on the ISBNDB website and put that into my code, which it was "YOUR_REST_KEY". I did not change it from the example. I tried changing the colon to a comma, but that didn't help compile the code.

```<code>private static HttpURLConnection con;

public static void main(String[] args) throws MalformedURLException,
        ProtocolException, IOException {

    String url = "https://api2.isbndb.com/book/9781934759486";

    try {

        URL myurl = new URL(url);
        con = (HttpURLConnection) myurl.openConnection();
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization": "YOUR_REST_KEY");
        con.setRequestMethod("GET");

        StringBuilder content;

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

            String line;
            content = new StringBuilder();

            while ((line = in.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
        }

        System.out.println(content.toString());

    } finally {

        con.disconnect();
    }
}
</code>```

I expected that the content that was meant to be printed was all the info about the book from the ISBN (like author, title, publisher, publish date, etc.), but only a compile error came up and nothing was outputted to the console.

答: I figured out what was wrong and that was the fact that in order to use this API, you have to pay for it and I did not realize this when I tried using it. I thought it was free, but turns out it was not so I didn't have the authority to use the API.</p>

Body:
I'm trying to access the ISBNDB and get information about all the relavent data about a book so I can make a bibliography from that data for a school project. But, I'm having trouble accessing the ISBNDB and using the ISBNDB API through Java. I have never used Maven or Gradle before, so is it possible to use the ISBNDB API without using Maven or Gradle? And if so, can I get some example code to see how to use the ISBNDB API in Java?

I've tried using the example code from the ISBNDB API and plugging that in to my Java project, but it didn't compile or work correctly. It doesn't seem like the colon is supposed to be in the setRequestProperty method because when I tried putting the exact code into my compiler (IntelliJ), it wouldn't compile and it would just be angry with me. I've made a Rest Key on the ISBNDB website and put that into my code, which it was "YOUR_REST_KEY". I did not change it from the example. I tried changing the colon to a comma, but that didn't help compile the code.

private static HttpURLConnection con;

public static void main(String[] args) throws MalformedURLException,
        ProtocolException, IOException {

    String url = "https://api2.isbndb.com/book/9781934759486";

    try {

        URL myurl = new URL(url);
        con = (HttpURLConnection) myurl.openConnection();
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization": "YOUR_REST_KEY");
        con.setRequestMethod("GET");

        StringBuilder content;

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {

            String line;
            content = new StringBuilder();

            while ((line = in.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
        }

        System.out.println(content.toString());

    } finally {

        con.disconnect();
    }
}

I expected that the content that was meant to be printed was all the info about the book from the ISBN (like author, title, publisher, publish date, etc.), but only a compile error came up and nothing was outputted to the console.


问:
Grep and inserting a string
I have a text file with a bunch of file paths such as -

```<code>web/index.erb

web/contact.erb

...
</code>```

etc. I need to append before the

```<code></head>
</code>```

a line of code, to every single file, I'm trying to figure out how to do this without opening each file of course. I've heard sed, but I've never used it before..was hoping there would be a grep command maybe?

Thanks

答:
xargs can be used to apply sed (or any other command) to each filename or argument in a list. So combining that with Rom1's answer gives:</p>

```<code>xargs sed -i 's/<\/html>/myline\n<\/html>/g' < fileslist.txt
</code>```

Title: Grep and inserting a string

Body:
I have a text file with a bunch of file paths such as -

web/index.erb

web/contact.erb

...

etc. I need to append before the

a line of code, to every single file, I'm trying to figure out how to do this without opening each file of course. I've heard sed, but I've never used it before..was hoping there would be a grep command maybe?

Thanks

Body:
xargs can be used to apply sed (or any other command) to each filename or argument in a list. So combining that with Rom1's answer gives:

xargs sed -i 's/<\/html>/myline\n<\/html>/g' < fileslist.txt


问:
Gravity Forms - Drop Down based of entries from Database
I am new to WordPress and I work with the plugin Gravityforms.

I would like to know how to retrieve the data from a table in my database in a Dropdown, so that when I open my page there is a Dropdown field whose data comes from my database.

If anyone has an idea of how I can go about it, or write the code etc. It would be really helpful.

Thanks in advance.

答:
Gravity Forms has a great example of how to populate Drop Down fields dynamically via hooks in the link below. In your case, you would need to fetch your entries via the GFAPI::get_entries() method rather than WordPress' get_posts() function.

https://docs.gravityforms.com/dynamically-populating-drop-down-fields/

If you don't feel comfortable customizing the code examples, Gravity Forms Populate Anything provides point-and-click UI for populating any choice-based fields (including Drop Downs) and support for filtering which entries get populated.

https://gravitywiz.com/documentation/gravity-forms-populate-anything/


答:
An Object is something in any Object Oriented language including Python, C#, Java and even JavaScript these days. Objects are also prevalent in 3d modeling software but are not per se the same thing.

An Object is an INSTANTIATED class. A class is a blueprint for creating object. Almost everything in Python is an object.

In reference to how you seem to be regarding to exclusivity of objects in python, yes, there is an object class. C# has them too and possibly others where you would use it not dissimilar to creating a string or int.