问:
NodaTime with MongoDB: Value class NodaTime.ZonedDateTime cannot be deserialized
I'm using latest versions of NodaTime and Mongo DB Official Driver. I have a simple POCO class which uses NodaTime's ZonedDateTime as a replacement for the .NET DateTime in a few Properties.

```<code>public class MyPOCO
{
    [BsonId]
    [Key]
    public ObjectId SomeId { get; set; }

    public string SomeProperty { get; set; }

    public ZonedDateTime SomeDateTime { get; set; }
}
</code>```

I can put the Model into the collection easily, but when I try to read queried Models, I get the following MongoDB.Bson.BsonSerializationException:

Value class NodaTime.ZonedDateTime cannot be deserialized

What`s a good or the best practice to solve/work around this issue?

UPDATE

After posting my solution to the problem, I'm facing a possible new issue... When I query the collection and use the DateTime in my query, like where SomeDateTime < now' (wherenowis a variable I create from system time) it seems that each document must be deserialized using myZonedDateTimeSerializer` before the where clause can be evaluated. This looks like a big performance issue, doesn't it? I really have to think about going back to the BCL DateTime again, even if it hurts.

UPDATE 2

I'm accepting my solution using ZonedDateTimeSerializer, but I'm not feeling comfortable with NodaTime in combination with MongoDB, while both are great individual solutions. But they just don't work well together at the moment without heavy manipulation.

答:
Here is a modified version of thmshd´s class, that stores the timezone information as well:

```<code>public class ZonedDateTimeSerializer : IBsonSerializer<ZonedDateTime>
{
    public static ZonedDateTimeSerializer Instance { get; } = new ZonedDateTimeSerializer();

    object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return Deserialize(context, args);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ZonedDateTime value)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        var zonedDateTime = value;

        SerializeAsDocument(context, zonedDateTime);
    }

    private static void SerializeAsDocument(BsonSerializationContext context, ZonedDateTime zonedDateTime)
    {
        context.Writer.WriteStartDocument();
        context.Writer.WriteString("tz", zonedDateTime.Zone.Id);
        context.Writer.WriteInt64("ticks", zonedDateTime.ToInstant().Ticks);
        context.Writer.WriteEndDocument();
    }

    public ZonedDateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var bsonType = context.Reader.GetCurrentBsonType();

        if (bsonType != BsonType.Document)
        {
            throw new InvalidOperationException($"Cannot deserialize ZonedDateTime from BsonType {bsonType}.");
        }

        context.Reader.ReadStartDocument();
        var timezoneId = context.Reader.ReadString("tz");
        var ticks = context.Reader.ReadInt64("ticks");
        var timezone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezoneId);

        if (timezone == null)
        {
            throw new Exception($"Unknown timezone id: {timezoneId}");
        }

        context.Reader.ReadEndDocument();

        return new Instant(ticks).InZone(timezone);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        var zonedDateTime = (ZonedDateTime)value;

        SerializeAsDocument(context, zonedDateTime);
    }

    public Type ValueType => typeof(ZonedDateTime);
}
</code>```

It can be globally registered like so:

```<code>BsonSerializer.RegisterSerializer(ZonedDateTimeSerializer.Instance);
</code>```

Edit:
Instead of serializing to a subdocument, it might be better to utilize NodaTimes built-in string parsing.

Serialize:

```<code>context.Writer.WriteString(ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb).Format(zonedDateTime));
</code>```

Deserialize:

```<code>        var zonedDateTimeString = context.Reader.ReadString();
        var parseResult = ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb)n.Parse(zonedDateTimeString);

        if (!parseResult.Success)
        {
            throw parseResult.Exception;
        }

        return parseResult.Value;
</code>```

Body:
I'm using latest versions of NodaTime and Mongo DB Official Driver. I have a simple POCO class which uses NodaTime's ZonedDateTime as a replacement for the .NET DateTime in a few Properties.

public class MyPOCO
{
    [BsonId]
    [Key]
    public ObjectId SomeId { get; set; }

    public string SomeProperty { get; set; }

    public ZonedDateTime SomeDateTime { get; set; }
}

I can put the Model into the collection easily, but when I try to read queried Models, I get the following MongoDB.Bson.BsonSerializationException:

Value class NodaTime.ZonedDateTime cannot be deserialized

What`s a good or the best practice to solve/work around this issue?

UPDATE

After posting my solution to the problem, I'm facing a possible new issue... When I query the collection and use the DateTime in my query, like where SomeDateTime < now' (wherenowis a variable I create from system time) it seems that each document must be deserialized using myZonedDateTimeSerializer` before the where clause can be evaluated. This looks like a big performance issue, doesn't it? I really have to think about going back to the BCL DateTime again, even if it hurts.

UPDATE 2

I'm accepting my solution using ZonedDateTimeSerializer, but I'm not feeling comfortable with NodaTime in combination with MongoDB, while both are great individual solutions. But they just don't work well together at the moment without heavy manipulation.

Body:
Here is a modified version of thmshd´s class, that stores the timezone information as well:

public class ZonedDateTimeSerializer : IBsonSerializer<ZonedDateTime>
{
    public static ZonedDateTimeSerializer Instance { get; } = new ZonedDateTimeSerializer();

    object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return Deserialize(context, args);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ZonedDateTime value)
    {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        var zonedDateTime = value;

        SerializeAsDocument(context, zonedDateTime);
    }

    private static void SerializeAsDocument(BsonSerializationContext context, ZonedDateTime zonedDateTime)
    {
        context.Writer.WriteStartDocument();
        context.Writer.WriteString("tz", zonedDateTime.Zone.Id);
        context.Writer.WriteInt64("ticks", zonedDateTime.ToInstant().Ticks);
        context.Writer.WriteEndDocument();
    }

    public ZonedDateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var bsonType = context.Reader.GetCurrentBsonType();

        if (bsonType != BsonType.Document)
        {
            throw new InvalidOperationException($"Cannot deserialize ZonedDateTime from BsonType {bsonType}.");
        }

        context.Reader.ReadStartDocument();
        var timezoneId = context.Reader.ReadString("tz");
        var ticks = context.Reader.ReadInt64("ticks");
        var timezone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezoneId);

        if (timezone == null)
        {
            throw new Exception($"Unknown timezone id: {timezoneId}");
        }

        context.Reader.ReadEndDocument();

        return new Instant(ticks).InZone(timezone);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        if (value == null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        var zonedDateTime = (ZonedDateTime)value;

        SerializeAsDocument(context, zonedDateTime);
    }

    public Type ValueType => typeof(ZonedDateTime);
}

It can be globally registered like so:

BsonSerializer.RegisterSerializer(ZonedDateTimeSerializer.Instance);

Edit:
Instead of serializing to a subdocument, it might be better to utilize NodaTimes built-in string parsing.

Serialize:

context.Writer.WriteString(ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb).Format(zonedDateTime));

Deserialize:

        var zonedDateTimeString = context.Reader.ReadString();
        var parseResult = ZonedDateTimePattern.CreateWithInvariantCulture("G", DateTimeZoneProviders.Tzdb)n.Parse(zonedDateTimeString);

        if (!parseResult.Success)
        {
            throw parseResult.Exception;
        }

        return parseResult.Value;


来源: stackexchange

问:
How to use tf.train.MonitoredTrainingSession to restore only certain variables
How does one tell a tf.train.MonitoredTrainingSession to restore only a subset of the variables, and perform intialization on the rest?

Starting with the cifar10 tutorial ..
https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_train.py

.. I created lists of the variables to restore and initialize, and specified them using a Scaffold that I pass to the MonitoredTrainingSession:

```<code>  restoration_saver = Saver(var_list=restore_vars)
  restoration_scaffold = Scaffold(init_op=variables_initializer(init_vars),
                                  ready_op=constant([]),
                                  saver=restoration_saver)
</code>```

but this gives the following error:

RuntimeError: Init operations did not make model ready for local_init.  Init op: group_deps, init fn: None, error: Variables not initialized: conv2a/T, conv2b/T, [...]

.. where the uninitialized variables listed in the error message are the variables in my "init_vars" list.

The exception is raised by SessionManager.prepare_session(). The source code for that method seems to indicate that if the session is restored from a checkpoint, then the init_op is not run. So it looks like you can either have restored variables or initialized variables, but not both.

答: You can solve this with the local_init_op argument, which does get run after loading from a checkpoint.

ContentLicense: CC BY-SA 3.0

Body:
How does one tell a tf.train.MonitoredTrainingSession to restore only a subset of the variables, and perform intialization on the rest?

Starting with the cifar10 tutorial ..
https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_train.py

.. I created lists of the variables to restore and initialize, and specified them using a Scaffold that I pass to the MonitoredTrainingSession:

  restoration_saver = Saver(var_list=restore_vars)
  restoration_scaffold = Scaffold(init_op=variables_initializer(init_vars),
                                  ready_op=constant([]),
                                  saver=restoration_saver)

but this gives the following error:

RuntimeError: Init operations did not make model ready for local_init.  Init op: group_deps, init fn: None, error: Variables not initialized: conv2a/T, conv2b/T, [...]

.. where the uninitialized variables listed in the error message are the variables in my "init_vars" list.

The exception is raised by SessionManager.prepare_session(). The source code for that method seems to indicate that if the session is restored from a checkpoint, then the init_op is not run. So it looks like you can either have restored variables or initialized variables, but not both.


问:
Xcode - find inheritance 'tree' for an object
Is there a way in Xcode to find out who implements or extends a given class or protocol?

ex.

```<code>class Car {
     ...
}
class GoCart {
    ...
}
extension Car: Drivable {
    ...
}
extension GoCart: Drivable {
    ...
}
protocol Drivable {
    func steer(vector: Point)
}
</code>```

I would like to search for Drivable and get Car and GoCart, possibly in the symbol navigator.

答:
You can try using the is keyword - i.e.:

```<code>switch car {
case car where car is GoCart:
case car where car is Drivable:
}

or you can try

if car is Drivable {

} else if car is GoCart {

}
</code>```

Body:
Is there a way in Xcode to find out who implements or extends a given class or protocol?

ex.

class Car {
     ...
}
class GoCart {
    ...
}
extension Car: Drivable {
    ...
}
extension GoCart: Drivable {
    ...
}
protocol Drivable {
    func steer(vector: Point)
}

I would like to search for Drivable and get Car and GoCart, possibly in the symbol navigator.

Body:
You can try using the is keyword - i.e.:

switch car {
case car where car is GoCart:
case car where car is Drivable:
}

or you can try

if car is Drivable {

} else if car is GoCart {

}


问:
Load svg dinamically as a react component
My app should render about 30000 svg elements, depending on routes.
If route is like www.myapp.com/svg-data/person it should render person.svg.

Later on (same route), this svg could be modified: add background color, some text, or some predefined layers.
I guess I should load the svg as a react component. I'm having a look at library https://github.com/boopathi/react-svg-loader but I don't think it really fit my purpose.

My last thought is about fetching svg data as string and render it inside a component which returns an svg among other things...

I should build a generic component, that renders whatever svg that comes as a parameter:

```<code>  componentDidMount() {
    if (this.props.params.searchText) {
      this.props.requestSVG(this.props.params.searchText)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.params.searchText !== nextProps.params.searchText) {
      this.props.requestSVG(nextProps.params.searchText)
    }
  }
</code>```

This component would render something like:

```<code>render() {
   const {svgData, textForSVGData} = this.props
   let svgText=null

   if (textForSVGData) {
     svgText= <text x='250' y='150' font-size='55'> {textForSVGData} </text>
   }

   return (
      <svg>
        {this.props.svgData}
        {svgText}
      </svg>
   )

}
</code>```

Depending on props it should add text, or any other things on demand. Do I miss something? This is the good way to do it?

答:
I recommend you, a couple of things:

Create each SVG in a single component, this will help you to isolate your SVG's behavior, styles, props and so on

Use higher order component to create the generic component, and use it as a proxy to pass dynamics props to your SVG components and add common SVG behavior if needed

Regarding the routers, you can have a mapper Router - Icon or directly set the SVG component as the router component to render

The main goal of the SvgRendering is to act as a higher order component and render the given component with the given props.

```<code>class SvgRenderer extends React.Component {
  constructor(props) {
    super(props);

    this.state = { invert: true };
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({ inverted: !this.state.inverted });
  }

  render() {
    const { Svg, svgProps } = this.props;
    const { inverted } = this.state;

    return (
      <div>
        <button onClick={this.toggle}>toggle inverted svg</button>
        <div><Svg {...svgProps} inverted={inverted}/></div>
      </div>
    );
  }
}
</code>```

Meanwhile PlayIcon (the SVG) aims setting custom styles, text, shapes, etc.

```<code>const PlayIcon = (props) => {
  const { className, inverted } = props;
  const classes = className ? ['icon', 'logo', 'className'] : ['icon', 'logo'];

  if (inverted) classes.push('inverted');

  return (
    <div className={classes.join(' ')}>
      <svg
        version="1.1"
        viewBox="0 0 512 512">
        <path d="M256.000,512.000 C114.615,512.000 0.000,397.385 0.000,256.000 C0.000,114.615 114.615,0.000 256.000,0.000 C397.385,0.000 512.000,114.615 512.000,256.000 C512.000,397.385 397.385,512.000 256.000,512.000 ZM151.172,128.000 L151.172,384.000 L406.907,256.000 L151.172,128.000 Z" />
      </svg>
    </div>
  );
};
</code>```

I'm being very generic with this suggestion and as result of these recommendations I have created and example of implementation in this fiddle:

https://jsfiddle.net/69z2wepo/82451/

Let me know if you have any question.

Body:
My app should render about 30000 svg elements, depending on routes.
If route is like www.myapp.com/svg-data/person it should render person.svg.

Later on (same route), this svg could be modified: add background color, some text, or some predefined layers.
I guess I should load the svg as a react component. I'm having a look at library https://github.com/boopathi/react-svg-loader but I don't think it really fit my purpose.

My last thought is about fetching svg data as string and render it inside a component which returns an svg among other things...

I should build a generic component, that renders whatever svg that comes as a parameter:

  componentDidMount() {
    if (this.props.params.searchText) {
      this.props.requestSVG(this.props.params.searchText)
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.params.searchText !== nextProps.params.searchText) {
      this.props.requestSVG(nextProps.params.searchText)
    }
  }

This component would render something like:

render() {
   const {svgData, textForSVGData} = this.props
   let svgText=null

   if (textForSVGData) {
     svgText= <text x='250' y='150' font-size='55'> {textForSVGData} </text>
   }

   return (
      <svg>
        {this.props.svgData}
        {svgText}
      </svg>
   )

}

Depending on props it should add text, or any other things on demand. Do I miss something? This is the good way to do it?

Body:
I recommend you, a couple of things:

Create each SVG in a single component, this will help you to isolate your SVG's behavior, styles, props and so on

Use higher order component to create the generic component, and use it as a proxy to pass dynamics props to your SVG components and add common SVG behavior if needed

Regarding the routers, you can have a mapper Router - Icon or directly set the SVG component as the router component to render

The main goal of the SvgRendering is to act as a higher order component and render the given component with the given props.

class SvgRenderer extends React.Component {
  constructor(props) {
    super(props);

    this.state = { invert: true };
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({ inverted: !this.state.inverted });
  }

  render() {
    const { Svg, svgProps } = this.props;
    const { inverted } = this.state;

    return (
      <div>
        <button onClick={this.toggle}>toggle inverted svg</button>
        <div><Svg {...svgProps} inverted={inverted}/></div>
      </div>
    );
  }
}

Meanwhile PlayIcon (the SVG) aims setting custom styles, text, shapes, etc.

const PlayIcon = (props) => {
  const { className, inverted } = props;
  const classes = className ? ['icon', 'logo', 'className'] : ['icon', 'logo'];

  if (inverted) classes.push('inverted');

  return (
    <div className={classes.join(' ')}>
      <svg
        version="1.1"
        viewBox="0 0 512 512">
        <path d="M256.000,512.000 C114.615,512.000 0.000,397.385 0.000,256.000 C0.000,114.615 114.615,0.000 256.000,0.000 C397.385,0.000 512.000,114.615 512.000,256.000 C512.000,397.385 397.385,512.000 256.000,512.000 ZM151.172,128.000 L151.172,384.000 L406.907,256.000 L151.172,128.000 Z" />
      </svg>
    </div>
  );
};

I'm being very generic with this suggestion and as result of these recommendations I have created and example of implementation in this fiddle:

https://jsfiddle.net/69z2wepo/82451/

Let me know if you have any question.


问:
Kind of applications that can be based on dotnet framework alone
i am intend to do a web application and host it. Since i have some knowledge
in Asp.Netand C#, i decided to develop using DotNet.

I am not sure about the licencing from microsoft for dotnet.

My question is :

Is it possible to use only dotnet framework which is free and use MySql as
backend to develop a webapplication and host it without buying licence ?
If so what editor can i use to develop the application ?

Pls suggest me some ideas. Thanks.

答:
You don't need any runtime licenses at all unless you use SQL Server.

For development, you can use the free Visual Web Developer Express Edition.

ContentLicense: CC BY-SA 2.5


问:
Zscore Normalize column in Dataframe using groupby
I have a dataframe representing customers orders with many columns, two of those being 'user_id' and 'dollar'.

for example :

```<code>    user_id   dollar
0  1  0.34592  5
1  1  0.02857  7
2  1  0.26672  6
3  1  0.34592  5
4  1  0.02857  9
5  1  0.26672  10
6  1  0.34592  6
      [...]
7  40  0.02857  20
8  40  0.26672  19
9  40  0.34592  8
10 40  0.02857  18
11 40  0.26672  26
</code>```

I want to normalize the value of dollar with respect to the other values in each users row. I want the following result for the previous example:

```<code> user_id   dollar norm_dollar
0  1  0.34592  5  -1.02774024
1  1  0.02857  7  0.07905694
2  1  0.26672  6  -0.47434165
3  1  0.34592  5  -1.02774024
4  1  0.02857  9  1.18585412
5  1  0.26672  10  1.73925271
6  1  0.34592  6  -0.47434165
      [...]
7  40  0.02857  20  0.7787612
8  40  0.26672  19  0.57109154
9  40  0.34592  8   -1.71327463
10 40  0.02857  18  0.36342189
</code>```

EDIT:

I would like each results to be normalized wrt each user individually and not the values of the whole column, so for example  with user2,[20,19,8,18] should be normalized as if the mean is the mean of user2 orders, here for example the mean is 16,25 and not the mean of the whole dataframe column.

I know how to do it with one user:

```<code>user1 = data.loc[data['user_id']==1]
data.loc[data['user_id']==1]['norm_dollar'] = sp.stats.mstats.zscore(user1['dollar'])
</code>```

I tried to do it this way for all the users:

```<code>data.dollar.div(sp.stats.mstats.zscore(data.groupby('user_id').dollar))
</code>```

But I got an error, do you have any idea on how to proceed?

Thank you

答:
That should work for you: </p>

```<code>def apply_zscores(x):
    x['norm_dollar'] = zscore(x['dollar'])
    return x

df = df.groupby('id').apply(lambda x: apply_zscores(x))
</code>```

Body:
I have a dataframe representing customers orders with many columns, two of those being 'user_id' and 'dollar'.

for example :

    user_id   dollar
0  1  0.34592  5
1  1  0.02857  7
2  1  0.26672  6
3  1  0.34592  5
4  1  0.02857  9
5  1  0.26672  10
6  1  0.34592  6
      [...]
7  40  0.02857  20
8  40  0.26672  19
9  40  0.34592  8
10 40  0.02857  18
11 40  0.26672  26

I want to normalize the value of dollar with respect to the other values in each users row. I want the following result for the previous example:

 user_id   dollar norm_dollar
0  1  0.34592  5  -1.02774024
1  1  0.02857  7  0.07905694
2  1  0.26672  6  -0.47434165
3  1  0.34592  5  -1.02774024
4  1  0.02857  9  1.18585412
5  1  0.26672  10  1.73925271
6  1  0.34592  6  -0.47434165
      [...]
7  40  0.02857  20  0.7787612
8  40  0.26672  19  0.57109154
9  40  0.34592  8   -1.71327463
10 40  0.02857  18  0.36342189

EDIT:

I would like each results to be normalized wrt each user individually and not the values of the whole column, so for example  with user2,[20,19,8,18] should be normalized as if the mean is the mean of user2 orders, here for example the mean is 16,25 and not the mean of the whole dataframe column.

I know how to do it with one user:

user1 = data.loc[data['user_id']==1]
data.loc[data['user_id']==1]['norm_dollar'] = sp.stats.mstats.zscore(user1['dollar'])

I tried to do it this way for all the users:

data.dollar.div(sp.stats.mstats.zscore(data.groupby('user_id').dollar))

But I got an error, do you have any idea on how to proceed?

Thank you

Body:
That should work for you:

def apply_zscores(x):
    x['norm_dollar'] = zscore(x['dollar'])
    return x

df = df.groupby('id').apply(lambda x: apply_zscores(x))


问:
How to generate a QR Code for Google Authenticator that correctly shows Issuer displayed above the OTP?

Warning:  sharing your TOTP seed with third-parties breaks the very basic assumption of multi-factor authentication that the TOTP
  seed is secret.

So, I'm aware of the documentation on this, found here: Google Authenticator Key URI Format

When I follow this example from that page:

```<code>otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example
</code>```

And I 'splice' it into a Google Charts URL, thus:

```<code>https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example
</code>```

It will display a valid QR code, and if I scan it with my Google Authenticator app on my phone, it will begin to generate valid OTPs.

However, in the display on the phone, for the entry created by the QR code, I get the OTP, and under it, I get 'Example:alice@google.com'.  What I want, is to have 'Example' displayed above the OTP, and 'alice@google.com' displayed below the OTP.  I can't help but notice that's the way all the professionally produced apps do it.  For example, Google, Wordpress, Amazon, etc.  The company name is above the OTP, and the username is displayed below the OTP.  Yes, this is purely a cosmetic issue, but I want to get it right.

Can anyone offer me a clue?

答:
Just want to note, newer versions for Google Authenticator will use the issuer parameter, documented here:

https://github.com/google/google-authenticator/wiki/Key-Uri-Format#issuer

e.g:

https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=otpauth%3A//totp/User%2540Realm%3Fsecret%3DKO5DE2YD3Q2ZXEOO%26issuer%3DIssuer%2520Name&choe=UTF-8

ContentLicense: CC BY-SA 4.0

Body:
Warning:  sharing your TOTP seed with third-parties breaks the very basic assumption of multi-factor authentication that the TOTP
  seed is secret.

So, I'm aware of the documentation on this, found here: Google Authenticator Key URI Format

When I follow this example from that page:

otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

And I 'splice' it into a Google Charts URL, thus:

https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

It will display a valid QR code, and if I scan it with my Google Authenticator app on my phone, it will begin to generate valid OTPs.

However, in the display on the phone, for the entry created by the QR code, I get the OTP, and under it, I get 'Example:alice@google.com'.  What I want, is to have 'Example' displayed above the OTP, and 'alice@google.com' displayed below the OTP.  I can't help but notice that's the way all the professionally produced apps do it.  For example, Google, Wordpress, Amazon, etc.  The company name is above the OTP, and the username is displayed below the OTP.  Yes, this is purely a cosmetic issue, but I want to get it right.

Can anyone offer me a clue?


问:
Storing passwords in Jupyter notebooks
Is there a way to store secrets/access secrets/passwords in notebooks? I have an api endpoint where I pull data from, and I dont want to expose the apiKey to everyone who can view the notebook. </p>

答:
Store your credentials in a JSON or YAML, and have your notebook parse the necessary parts.

```<code>import json

with open('credentials.json') as f:
    data = json.load(f)
    username = data['username']
    password = data['password']
</code>```

You should avoid printing the secrets in the cell outputs, for otherwise any technique you choose will be foiled.

Title: Storing passwords in Jupyter notebooks

Body:
Store your credentials in a JSON or YAML, and have your notebook parse the necessary parts.

import json

with open('credentials.json') as f:
    data = json.load(f)
    username = data['username']
    password = data['password']

You should avoid printing the secrets in the cell outputs, for otherwise any technique you choose will be foiled.


问:
Why does swift substring with range require a special type of Range
Consider this function to build a string of random characters:

```<code>func makeToken(length: Int) -> String {
    let chars: String = "abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    var result: String = ""
    for _ in 0..<length {
        let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
        let idxEnd = idx + 1
        let range: Range = idx..<idxEnd
        let char = chars.substring(with: range)
        result += char
    }
    return result
}
</code>```

This throws an error on the substring method:

```<code>Cannot convert value of type 'Range<Int>' to expected argument
type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')
</code>```

I'm confused why I can't simply provide a Range with 2 integers, and why it's making me go the roundabout way of making a Range<String.Index>.

So I have to change the Range creation to this very over-complicated way:

```<code>let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
let start = chars.index(chars.startIndex, offsetBy: idx)
let end = chars.index(chars.startIndex, offsetBy: idx + 1)
let range: Range = start..<end
</code>```

Why isn't it good enough for Swift for me to simply create a range with 2 integers and the half-open range operator? (..<)

Quite the contrast to "swift", in javascript I can simply do chars.substr(idx, 1)

答:
Swift takes great care to provide a fully Unicode-compliant, type-safe, String abstraction.

Indexing a given Character, in an arbitrary Unicode string, is far from a trivial task. Each Character is a sequence of one or more Unicode scalars that (when combined) produce a single human-readable character. In particular, hiding all this complexity behind a simple Int based indexing scheme might result in the wrong performance mental model for programmers.

Having said that, you can always convert your string to a Array<Character> once for easy (and fast!) indexing. For instance:

```<code>let chars: String = "abcdefghijklmnop"
var charsArray = Array(chars.characters)
...
let resultingString = String(charsArray)
</code>```

Body:
Consider this function to build a string of random characters:

func makeToken(length: Int) -> String {
    let chars: String = "abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    var result: String = ""
    for _ in 0..<length {
        let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
        let idxEnd = idx + 1
        let range: Range = idx..<idxEnd
        let char = chars.substring(with: range)
        result += char
    }
    return result
}

This throws an error on the substring method:

Cannot convert value of type 'Range<Int>' to expected argument
type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')

I'm confused why I can't simply provide a Range with 2 integers, and why it's making me go the roundabout way of making a Range<String.Index>.

So I have to change the Range creation to this very over-complicated way:

let idx =  Int(arc4random_uniform(UInt32(chars.characters.count)))
let start = chars.index(chars.startIndex, offsetBy: idx)
let end = chars.index(chars.startIndex, offsetBy: idx + 1)
let range: Range = start..<end

Why isn't it good enough for Swift for me to simply create a range with 2 integers and the half-open range operator? (..<)

Quite the contrast to "swift", in javascript I can simply do chars.substr(idx, 1)

Body:
Swift takes great care to provide a fully Unicode-compliant, type-safe, String abstraction.

Indexing a given Character, in an arbitrary Unicode string, is far from a trivial task. Each Character is a sequence of one or more Unicode scalars that (when combined) produce a single human-readable character. In particular, hiding all this complexity behind a simple Int based indexing scheme might result in the wrong performance mental model for programmers.

Having said that, you can always convert your string to a Array<Character> once for easy (and fast!) indexing. For instance:

let chars: String = "abcdefghijklmnop"
var charsArray = Array(chars.characters)
...
let resultingString = String(charsArray)


问:
ffmpeg records 5 frames per second on a device that cheese records at 20 fps
Running the following ffmpeg capture on my built in webcam:

```<code>ffmpeg -f v4l2 -framerate 30 -video_size 1920x1080 -i /dev/video0 output.mkv
</code>```

I get only 5 fps and see this message:

```<code>The driver changed the time per frame from 1/30 to 1/5
</code>```

When I record using cheese I get what looks like 20 fps on that device. And v4l2 seems to claim it can do 30 fps.

```<code>v4l2-ctl --list-formats-ext
ioctl: VIDIOC_ENUM_FMT
    Index       : 0
    Type        : Video Capture
    Pixel Format: 'MJPG' (compressed)
    Name        : Motion-JPEG
        Size: Discrete 1920x1080
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 1280x720
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 800x600
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x360
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 160x120
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 320x240
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)

    Index       : 1
    Type        : Video Capture
    Pixel Format: 'YUYV'
    Name        : YUYV 4:2:2
        Size: Discrete 1920x1080
            Interval: Discrete 0.200s (5.000 fps)
        Size: Discrete 1280x720
            Interval: Discrete 0.100s (10.000 fps)
        Size: Discrete 800x600
            Interval: Discrete 0.050s (20.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x360
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 160x120
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 320x240
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
</code>```

When I run ffmpeg:

```<code>Output #0, mjpeg, to 'output.mjpg':
  Metadata:
    encoder         : Lavf56.40.101
    Stream #0:0: Video: mjpeg, yuvj422p(pc), 1920x1080, q=2-31, 200 kb/s, 5 fps, 5 tbn, 5 tbc
    Metadata:
      encoder         : Lavc56.60.100 mjpeg
</code>```

My guess is that it's recording in raw form from the device and doing the encoding in ffmpeg. If this is correct, how would I get ffmpeg to use the mjpeg native format?

答:
I needed to record in the native compressed motion jpeg format supported by my webcam. Once I got that configured (see below) it records at 30 fps at full resolution.

```<code>ffmpeg -f v4l2 -framerate 30 -video_size 1920x1080 -c:v mjpeg -i /dev/video0 -c:v copy output.mov
</code>```

Note the -c:v (video codec) before the -i (input) indicates what recording codec the device should be using (mjpeg is supported natively on my webcam), and the -c:v (video codec) after the -i (input) indicates what recording codec ffmpeg should convert to. copy does not change the codec, it simply copies the bytes that were provided by the device.

Body:
Running the following ffmpeg capture on my built in webcam:

ffmpeg -f v4l2 -framerate 30 -video_size 1920x1080 -i /dev/video0 output.mkv

I get only 5 fps and see this message:

The driver changed the time per frame from 1/30 to 1/5

When I record using cheese I get what looks like 20 fps on that device. And v4l2 seems to claim it can do 30 fps.

v4l2-ctl --list-formats-ext
ioctl: VIDIOC_ENUM_FMT
    Index       : 0
    Type        : Video Capture
    Pixel Format: 'MJPG' (compressed)
    Name        : Motion-JPEG
        Size: Discrete 1920x1080
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 1280x720
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 800x600
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x360
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 160x120
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 320x240
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)

    Index       : 1
    Type        : Video Capture
    Pixel Format: 'YUYV'
    Name        : YUYV 4:2:2
        Size: Discrete 1920x1080
            Interval: Discrete 0.200s (5.000 fps)
        Size: Discrete 1280x720
            Interval: Discrete 0.100s (10.000 fps)
        Size: Discrete 800x600
            Interval: Discrete 0.050s (20.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x360
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 160x120
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 320x240
            Interval: Discrete 0.033s (30.000 fps)
        Size: Discrete 640x480
            Interval: Discrete 0.033s (30.000 fps)

When I run ffmpeg:

Output #0, mjpeg, to 'output.mjpg':
  Metadata:
    encoder         : Lavf56.40.101
    Stream #0:0: Video: mjpeg, yuvj422p(pc), 1920x1080, q=2-31, 200 kb/s, 5 fps, 5 tbn, 5 tbc
    Metadata:
      encoder         : Lavc56.60.100 mjpeg

My guess is that it's recording in raw form from the device and doing the encoding in ffmpeg. If this is correct, how would I get ffmpeg to use the mjpeg native format?

Body:
I needed to record in the native compressed motion jpeg format supported by my webcam. Once I got that configured (see below) it records at 30 fps at full resolution.

ffmpeg -f v4l2 -framerate 30 -video_size 1920x1080 -c:v mjpeg -i /dev/video0 -c:v copy output.mov

Note the -c:v (video codec) before the -i (input) indicates what recording codec the device should be using (mjpeg is supported natively on my webcam), and the -c:v (video codec) after the -i (input) indicates what recording codec ffmpeg should convert to. copy does not change the codec, it simply copies the bytes that were provided by the device.


问:
OCCI - setDataBuffer + vector<struct>
Trying to minimize amount of lines for an OCCI array fetch by storing a struct containing a char buffer into a vector, code below:

```<code>    struct Columns { char buffer[1000][300]; };

    int i = 1;
    Columns col;
    ub4* ub = NULL;
    results->setDataBuffer( i++, col.buffer, OCCI_SQLT_STR, sizeof( col.buffer[ 0 ] ), ub );
        vec.push_back( col );

    cout << "Before, vec size: " << vec.size( ) << "\n"; // prints 1, as expected
    while ( results->next( 1000 ) ) {
        for ( size_t j = 0; j < results->getNumArrayRows( ); ++j ) {
            cout << vec[ 0 ].buffer[ j ] << endl;
        }
</code>```

Now for some reason, this doesnt work. However, if instead of using col.buffer, I create a char buffer[1000][300] and toss that into setDataBuffer then in the cout part do:
    cout << buffer[j] << endl;

that works just fine. So I'm not really sure where I'm screwing up?

the char buffer is the exact same thing as col.buffer, is it not?

I don't think it matters but struct Columns is defined in the header file.

答:
I guess the setDataBuffer fills the buffer you pass as parameter (which is col.buffer here), then you push it into the vector, so a new struct Columns is allocated by vec and it copy col content. Now col and vec[0] are two different objects.

Then you call some methods which fills the buffer you first passed to it. So it fills col.buffer, and you read vec[0].buffer, which are different because they are 2 different objects.

One solution would instead be to do vec.emplace_back(); to create one instance, and then pass vec[0].buffer to setDataBuffer. But be careful with addresses of elements in vectors. If you modify the vector (adding or removing elements) it can reallocate it's content, and the element addresses might change.

Title: OCCI - setDataBuffer + vector<struct>

Body:
Trying to minimize amount of lines for an OCCI array fetch by storing a struct containing a char buffer into a vector, code below:

    struct Columns { char buffer[1000][300]; };

    int i = 1;
    Columns col;
    ub4* ub = NULL;
    results->setDataBuffer( i++, col.buffer, OCCI_SQLT_STR, sizeof( col.buffer[ 0 ] ), ub );
        vec.push_back( col );

    cout << "Before, vec size: " << vec.size( ) << "\n"; // prints 1, as expected
    while ( results->next( 1000 ) ) {
        for ( size_t j = 0; j < results->getNumArrayRows( ); ++j ) {
            cout << vec[ 0 ].buffer[ j ] << endl;
        }

Now for some reason, this doesnt work. However, if instead of using col.buffer, I create a char buffer[1000][300] and toss that into setDataBuffer then in the cout part do:
    cout << buffer[j] << endl;

that works just fine. So I'm not really sure where I'm screwing up?

the char buffer is the exact same thing as col.buffer, is it not?

I don't think it matters but struct Columns is defined in the header file.


问:
Change UIAlertController Background Tint
Yes, I know. You can't change the appearance of a UIAlertController. I don't want to change the background of the UIAlertController itself, I want to change the tint of the view's background. You know how it's like a transparent black color? I want to change that color to clear. How would I do this?

答:
No you cannot change the transparent background color. That does not belong to part of UIAlertController variable that you can control.

You will have to fix it by presenting a new view controller with a transparent background and a faked alert-controller-like UI element.

To further approve you does not have control for the alert controller, create another view with frame origin on 0,0 and then add to your alert controller's view. It will show on the top left corner of your pop up window, not the window of your window


问:
Python Boolean and Logical Operators
Given two input boolean values I want to print out the following results:

True True ->  False

  True False -> False

  False True -> False

  False False ->  True

I tried doing this:

```<code>if boolInput1 and boolInput2 == True:
    print(False)
elif boolInput1 == True and boolInput2 == False:
    print(False)
elif boolInput1 == False and boolInput2 == True:
    print(False)
elif boolInput1 and boolInput2 == False:
    print(True)
</code>```

but it doesn't work as this is the output:

```<code>Test  Input    Expected Actual
1   True True   False   False
2   True False  False   False
3   False True  False   False
4   False False True    False
</code>```

I've tried searching for an answer online but can't find anything.

答:
How about this?

```<code>print(not boolInput1 and not boolInput2)
</code>```

The issue with your code is here:

```<code>elif boolInput1 and boolInput2 == False:
    print(True)
</code>```

That would work if it read:

```<code>elif boolInput1 == False and boolInput2 == False:
    print(True)
</code>```

This line works fine despite having the same kind of issue, because the if boolInput1 does roughly what you want (checks for a truthy value).

```<code>if boolInput1 and boolInput2 == True:
</code>```

It might be better to write it this way to be more consistent with your other checks:

```<code>if boolInput1 == True and boolInput2 == True:
</code>```

Title: Python Boolean and Logical Operators

Body:
Given two input boolean values I want to print out the following results:

True True ->  False

  True False -> False

  False True -> False

  False False ->  True

I tried doing this:

if boolInput1 and boolInput2 == True:
    print(False)
elif boolInput1 == True and boolInput2 == False:
    print(False)
elif boolInput1 == False and boolInput2 == True:
    print(False)
elif boolInput1 and boolInput2 == False:
    print(True)

but it doesn't work as this is the output:

Test  Input    Expected Actual
1   True True   False   False
2   True False  False   False
3   False True  False   False
4   False False True    False

I've tried searching for an answer online but can't find anything.

Body:
How about this?

print(not boolInput1 and not boolInput2)

The issue with your code is here:

elif boolInput1 and boolInput2 == False:
    print(True)

That would work if it read:

elif boolInput1 == False and boolInput2 == False:
    print(True)

This line works fine despite having the same kind of issue, because the if boolInput1 does roughly what you want (checks for a truthy value).

if boolInput1 and boolInput2 == True:

It might be better to write it this way to be more consistent with your other checks:

if boolInput1 == True and boolInput2 == True:


问:
MYSQL query Alter table engine only if engine not innodb
I would like to run one query that alter table's engine (ALTER TABLE table1 ENGINE = INNODB) only if the current engine is not INNODB.

How can I do that?

Update:
I got a case of a query trying to alter the table's engine while its already innodb.

答:
http://mysql.rjweb.org/doc.php/myisam2innodb#generating_alters provides several tips about converting from MyISAM to InnoDB, including:

To generate all the ALTERs to convert all the MyISAM tables to InnoDB:

```<code>SELECT  CONCAT('USE ', table_schema, ';  ALTER TABLE ', table_name, ' ENGINE=InnoDB;')
    FROM  information_schema.tables
    WHERE  engine = 'MyISAM'
      AND  table_schema NOT IN ('mysql', 'information_schema', 'performance_schema');
</code>```

Then copy and paste the output into the mysql commandline tool.

Body:
http://mysql.rjweb.org/doc.php/myisam2innodb#generating_alters provides several tips about converting from MyISAM to InnoDB, including:

To generate all the ALTERs to convert all the MyISAM tables to InnoDB:

SELECT  CONCAT('USE ', table_schema, ';  ALTER TABLE ', table_name, ' ENGINE=InnoDB;')
    FROM  information_schema.tables
    WHERE  engine = 'MyISAM'
      AND  table_schema NOT IN ('mysql', 'information_schema', 'performance_schema');

Then copy and paste the output into the mysql commandline tool.


答:
boolInput1 and boolInput2 == False doesn't do what you think. The == binds more tightly than the and, so you're testing "is boolInput1 (truthy), and is boolInput2 equal to False", when you want "is boolInput1 False and boolInput2 False too?", which would be expressed boolInput1 == False and boolInput2 == False or more Pythonically, not boolInput1 and not boolInput2.

Really, you're making this harder than it needs to be. All of your code could simplify to just:

```<code>print(not boolInput1 and not boolInput2)
</code>```

or extracting the not if you prefer it:

```<code>print(not (boolInput1 or boolInput2))
</code>```

No if, elif, else or any other blocks required.

Generally speaking, explicitly comparing to True or False is not Pythonic; just use implicit "truthiness" testing to work with any types. Since you need not here anyway, the end result will always be True or False, even if the inputs aren't booleans at all, where directly comparing to True or False will make inputs like 2, None, or [] behave differently from the way they traditionally behave in "truthiness testing" (they'd be truthy, falsy and falsy respectively).

Title: Python Boolean and Logical Operators

Body:
boolInput1 and boolInput2 == False doesn't do what you think. The == binds more tightly than the and, so you're testing "is boolInput1 (truthy), and is boolInput2 equal to False", when you want "is boolInput1 False and boolInput2 False too?", which would be expressed boolInput1 == False and boolInput2 == False or more Pythonically, not boolInput1 and not boolInput2.

Really, you're making this harder than it needs to be. All of your code could simplify to just:

print(not boolInput1 and not boolInput2)

or extracting the not if you prefer it:

print(not (boolInput1 or boolInput2))

No if, elif, else or any other blocks required.

Generally speaking, explicitly comparing to True or False is not Pythonic; just use implicit "truthiness" testing to work with any types. Since you need not here anyway, the end result will always be True or False, even if the inputs aren't booleans at all, where directly comparing to True or False will make inputs like 2, None, or [] behave differently from the way they traditionally behave in "truthiness testing" (they'd be truthy, falsy and falsy respectively).


问:
js setAttribute with Array
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

```<code>AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }
</code>```

答:
Lot of people suggesting:
 el.setAttribute("rotation", 'x'+'y' + 'z');
 method, as far as i know, it's a bit more efficient to omit the parsing ( 'x y z' to {x,y,z} ) and use the object in the first place :
el.setAttribute("rotation", {x:gradRoll,y:0,z:0});

Title: js setAttribute with Array

Body:
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }


问:
Create huge page shared memory for IPC in linux
I have the following huge page create source code in linux:

```<code>int iTotalByte = sizeof(datafeed)* ARRAYSIZE ;
conf =  (datafeed*) mmap(0, iTotalByte , (PROT_READ | PROT_WRITE), MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE|MAP_HUGETLB , -1  , 0) ;
if(conf  == MAP_FAILED)
{
    printf(" mmap error ....\n")  ;
    exit( 0 ) ;
}
</code>```

and it works well, numastat -m will see the huge page table how many MB the application create.

The following is the source I create shared memory used for IPC:

```<code>int shm_fd;
if((shm_fd = shm_open(THE_FILE, (O_CREAT | O_EXCL | O_RDWR),
                   (S_IREAD | S_IWRITE))) > 0 ) {
    ; /* We are the first instance */
}
else if((shm_fd = shm_open(THE_FILE, (O_CREAT | O_RDWR),
                    (S_IREAD | S_IWRITE))) < 0)
{
    printf("Could not create shm object. %s\n", strerror(errno));
    exit( 0 ) ;
}
int iTotalByte = sizeof(datafeed)*ARRAYSIZE ;
ftruncate(shm_fd, iTotalByte );
conf =  (datafeed*) mmap(0, iTotalByte , (PROT_READ | PROT_WRITE), MAP_SHARED, shm_fd, 0) ;
if(conf  == MAP_FAILED)
{
    printf(" mmap error ....\n")  ;
    exit( 0 ) ;
}
</code>```

This source will create a shared memory THE_FILE used for IPC in /dev/shm/, many processes can do IPC through THE_FILE shared memory.

I wonder if there exist a method  that  I can mmap shared memory to
/dev/shm/  and  it is huge page at the same time ?! means I like
this hugepages memory to be used for IPC among processes,
not just used for threads in the same process.

Edit :

https://lwn.net/Articles/375098/

http://lxr.free-electrons.com/source/Documentation/vm/hugetlbpage.txt?v=2.6.32

have the sample code work as expected .

https://lwn.net/Articles/374424/

https://lwn.net/Articles/375096/

https://lwn.net/Articles/376606/

https://lwn.net/Articles/378641/

https://lwn.net/Articles/379748/

also help a lot for understanding huge pages .

答:
Given you've done the right thing setting up pages, page sizes etc.

```<code>sysctl vm.nr_hugepages=1024
</code>```

checking it with:

```<code>cat /proc/meminfo | grep Huge
AnonHugePages:         0 kB
HugePages_Total:    1024
HugePages_Free:      986
HugePages_Rsvd:      261
HugePages_Surp:        0
Hugepagesize:       2048 kB
</code>```

Put something like this in your /etc/fstab:

```<code>hugetlbfs   /mnt/hugepages  hugetlbfs   gid=2000,uid=2000   0   0
</code>```

Then use /mnt/hugepages in place of /dev/shm and you're doing IPC through shared memory backed by 2M superpages.

Body:
I have the following huge page create source code in linux:

int iTotalByte = sizeof(datafeed)* ARRAYSIZE ;
conf =  (datafeed*) mmap(0, iTotalByte , (PROT_READ | PROT_WRITE), MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE|MAP_HUGETLB , -1  , 0) ;
if(conf  == MAP_FAILED)
{
    printf(" mmap error ....\n")  ;
    exit( 0 ) ;
}

and it works well, numastat -m will see the huge page table how many MB the application create.

The following is the source I create shared memory used for IPC:

int shm_fd;
if((shm_fd = shm_open(THE_FILE, (O_CREAT | O_EXCL | O_RDWR),
                   (S_IREAD | S_IWRITE))) > 0 ) {
    ; /* We are the first instance */
}
else if((shm_fd = shm_open(THE_FILE, (O_CREAT | O_RDWR),
                    (S_IREAD | S_IWRITE))) < 0)
{
    printf("Could not create shm object. %s\n", strerror(errno));
    exit( 0 ) ;
}
int iTotalByte = sizeof(datafeed)*ARRAYSIZE ;
ftruncate(shm_fd, iTotalByte );
conf =  (datafeed*) mmap(0, iTotalByte , (PROT_READ | PROT_WRITE), MAP_SHARED, shm_fd, 0) ;
if(conf  == MAP_FAILED)
{
    printf(" mmap error ....\n")  ;
    exit( 0 ) ;
}

This source will create a shared memory THE_FILE used for IPC in /dev/shm/, many processes can do IPC through THE_FILE shared memory.

I wonder if there exist a method  that  I can mmap shared memory to
/dev/shm/  and  it is huge page at the same time ?! means I like
this hugepages memory to be used for IPC among processes,
not just used for threads in the same process.

Edit :

https://lwn.net/Articles/375098/

http://lxr.free-electrons.com/source/Documentation/vm/hugetlbpage.txt?v=2.6.32

have the sample code work as expected .

https://lwn.net/Articles/374424/

https://lwn.net/Articles/375096/

https://lwn.net/Articles/376606/

https://lwn.net/Articles/378641/

https://lwn.net/Articles/379748/

also help a lot for understanding huge pages .

Body:
Given you've done the right thing setting up pages, page sizes etc.

sysctl vm.nr_hugepages=1024

checking it with:

cat /proc/meminfo | grep Huge
AnonHugePages:         0 kB
HugePages_Total:    1024
HugePages_Free:      986
HugePages_Rsvd:      261
HugePages_Surp:        0
Hugepagesize:       2048 kB

Put something like this in your /etc/fstab:

hugetlbfs   /mnt/hugepages  hugetlbfs   gid=2000,uid=2000   0   0

Then use /mnt/hugepages in place of /dev/shm and you're doing IPC through shared memory backed by 2M superpages.


问:
can a Ruby cloud instance handle the same amount of traffic a node instance would do?
We're going to work on revamping a cms based website for a tv channel that we expect to serve at least 10+ million unique user/month, about 400+ million requests/month and an average of 40 terabytes of bandwidth/month that's their CloudFlare stats from their old website and they expecting even more.

the team stack is mainly ruby/rails with react for the frontend, so we're planning to build the backend as rest API that serves a frontend react and another react app for the cms admin panel, we're arguing between Ruby and node and some says that node is faster and will be cheaper in terms of resources consumption, will Ruby be efficient vs node?, can a Ruby cloud instance handle the same amount of traffic a node instance would do? any advice on is it worth the shift to node?

答:
Generally CMS applications heavily use caching, and I mean really heavily, like 99.999% of your requests must be cached and served by Apache/Nginx or a dedicated cache server. And thus the performance of your web framework doesn't matter too much.

Without caching that level of load on moderate hardware can create quite a lot of trouble both for Node and for Rails. For Rails that kind of load (400M/mo = 150 rps on average + 10–100x spikes) will require quite a few decent dedicated servers. Node should be about 2–5 times faster, depending on how SQL-heavy your requests are.


问:
PHP char coding, #==0, 0==NULL, #!=NULL
I need to use a special character as a stop/break signal for my program. I was trying out '#' '&' '@' and kept on receiving errors.

After some messing around, I discovered that all characters including the ones above all had the numeric value 0! I did so by comparing their values with numerics, because at first I thought it used ASCII codes.

Wait a minute, that's not right, because NULL also equals to 0! But the characters definitely does not equal to NULL!

So, what kind of char coding does PHP use? Is it impossible to compare chars with numbers?

Thanks in advance!

答:
It has nothing to do with ascii or char coding, it is just php implicit casting while comparisons.

http://www.php.net/manual/en/language.operators.comparison.php

Title: PHP char coding, #==0, 0==NULL, #!=NULL


问:
Using webpack, threejs examples, and typescript?
I'm having a lot of trouble getting stuff in threejs's examples (like EffectComposer or Detector) to work with webpack and typescript.

First off the relevant *.d.ts files are all present and installed via tsd.  My problem is getting webpack to actually include files outside of the default threejs build (namely things in examples/js/).

With three installed from npm I can do something like

```<code>import THREE = require('three');
</code>```

Which works fine but lacks any of the aforementioned goodies.  There are a few other threejs packages on npm that bundle plugins but I don't think they work with typescript (since require('three-js')(['EffectComposer']) is rejected by the typescript compiler.

Has anyone gotten something in this package (like postprocessing) to work with typescript?

答:
I managed to find a pretty clean way to set this up in webpack.config.js.

As per Dan's answer:

$ npm install --save-dev imports-loader

It turns out we don't actually need exports-loader, since the three.js examples add their constructors to the THREE object.

Then, in webpack.config.js, we can add a rule to add var THREE = require('three'); to an imported module if the module's path resolves to anything containing three/examples/js:

```<code>module: {
  rules: [
    ...
    {
      test: /three\/examples\/js/,
      use: 'imports-loader?THREE=three'
    }
  ]
}
</code>```

Now the example modules will find the THREE global when they expect it.

Then, to make importing examples a little less verbose:

```<code>resolve: {
  alias: {
    'three-examples': path.join(__dirname, './node_modules/three/examples/js')
  },
  ...
},
</code>```

This assumes that webpack.config.js is in the same directory as node_modules, adjust accordingly.

Now, we can use the example files like so:

```<code>import * as THREE from 'three';
import 'three-examples/controls/OrbitControls';
</code>```

to import the module for its side-effects.

If you're using this with Typescript and/or Babel and are getting warnings about the example module not being found on THREE, you may find this issue on the imports-loader repository useful to reference.

Body:
I'm having a lot of trouble getting stuff in threejs's examples (like EffectComposer or Detector) to work with webpack and typescript.

First off the relevant *.d.ts files are all present and installed via tsd.  My problem is getting webpack to actually include files outside of the default threejs build (namely things in examples/js/).

With three installed from npm I can do something like

import THREE = require('three');

Which works fine but lacks any of the aforementioned goodies.  There are a few other threejs packages on npm that bundle plugins but I don't think they work with typescript (since require('three-js')(['EffectComposer']) is rejected by the typescript compiler.

Has anyone gotten something in this package (like postprocessing) to work with typescript?

Body:
I managed to find a pretty clean way to set this up in webpack.config.js.

As per Dan's answer:

$ npm install --save-dev imports-loader

It turns out we don't actually need exports-loader, since the three.js examples add their constructors to the THREE object.

Then, in webpack.config.js, we can add a rule to add var THREE = require('three'); to an imported module if the module's path resolves to anything containing three/examples/js:

module: {
  rules: [
    ...
    {
      test: /three\/examples\/js/,
      use: 'imports-loader?THREE=three'
    }
  ]
}

Now the example modules will find the THREE global when they expect it.

Then, to make importing examples a little less verbose:

resolve: {
  alias: {
    'three-examples': path.join(__dirname, './node_modules/three/examples/js')
  },
  ...
},

This assumes that webpack.config.js is in the same directory as node_modules, adjust accordingly.

Now, we can use the example files like so:

import * as THREE from 'three';
import 'three-examples/controls/OrbitControls';

to import the module for its side-effects.

If you're using this with Typescript and/or Babel and are getting warnings about the example module not being found on THREE, you may find this issue on the imports-loader repository useful to reference.


问:
Race condition appending to mutable Map in future
I need to append to a Map structure from within a future, and I couldn't find a way to make the Map immutable (See below). I'm afraid that if the Map is mutable then I will have a race condition. How to fix the code below?

```<code>object TestFutures extends App {

  val m = collection.mutable.Map[Int,String]()

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val f2 = Future { 2 }
  val f3 = Future { 3 }
  val f4 = Future { 4 }

  val fx = Seq(f0,f1,f2,f3,f4)

  fx.map {
     i =>
       i.map {
         x =>
           val s = x + ""
           m += ( x -> s )
     }
  }

  Thread.sleep(5000)
  println(m)
}
</code>```

答:
I don't think you should use mutable map for this, because you can't know when these futures are done. you only can do by checking the map's size to check whether match the futures size, but if there is a key is override, you never know when the futures is finished.

So I think you can convert Seq[Future[Int]] of fx to Future[Seq[Int]] and map it to Future[Map[Int, String]], so you can know when these futures is done and do some other thing, like:

```<code>val res: Future[Map[Int, String]] = Future.sequence(fx).map(s => s.map(i => (i, i.toString)).toMap) // this will generate a immutable variable
val r: Map[Int, String] = Await.wait(res, Duration.Inf) //!!! Await just for test purpose
</code>```

Body:
I need to append to a Map structure from within a future, and I couldn't find a way to make the Map immutable (See below). I'm afraid that if the Map is mutable then I will have a race condition. How to fix the code below?

object TestFutures extends App {

  val m = collection.mutable.Map[Int,String]()

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val f2 = Future { 2 }
  val f3 = Future { 3 }
  val f4 = Future { 4 }

  val fx = Seq(f0,f1,f2,f3,f4)

  fx.map {
     i =>
       i.map {
         x =>
           val s = x + ""
           m += ( x -> s )
     }
  }

  Thread.sleep(5000)
  println(m)
}

Body:
I don't think you should use mutable map for this, because you can't know when these futures are done. you only can do by checking the map's size to check whether match the futures size, but if there is a key is override, you never know when the futures is finished.

So I think you can convert Seq[Future[Int]] of fx to Future[Seq[Int]] and map it to Future[Map[Int, String]], so you can know when these futures is done and do some other thing, like:

val res: Future[Map[Int, String]] = Future.sequence(fx).map(s => s.map(i => (i, i.toString)).toMap) // this will generate a immutable variable
val r: Map[Int, String] = Await.wait(res, Duration.Inf) //!!! Await just for test purpose


问:
Get the row(s) which have the max value in groups using groupby
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?

Example 1: the following DataFrame:

```<code>   Sp   Mt Value   count
0  MM1  S1   a     **3**
1  MM1  S1   n       2
2  MM1  S3   cb    **5**
3  MM2  S3   mk    **8**
4  MM2  S4   bg    **10**
5  MM2  S4   dgd     1
6  MM4  S2   rd      2
7  MM4  S2   cb      2
8  MM4  S2   uyi   **7**
</code>```

Expected output is to get the result rows whose count is max in each group, like this:

```<code>   Sp   Mt   Value  count
0  MM1  S1   a      **3**
2  MM1  S3   cb     **5**
3  MM2  S3   mk     **8**
4  MM2  S4   bg     **10**
8  MM4  S2   uyi    **7**
</code>```

Example 2:

```<code>   Sp   Mt   Value  count
4  MM2  S4   bg     10
5  MM2  S4   dgd    1
6  MM4  S2   rd     2
7  MM4  S2   cb     8
8  MM4  S2   uyi    8
</code>```

Expected output:

```<code>   Sp   Mt   Value  count
4  MM2  S4   bg     10
7  MM4  S2   cb     8
8  MM4  S2   uyi    8
</code>```

答:
Easy solution would be to apply the idxmax() function to get indices of rows with max values.
This would filter out all the rows with max value in the group.

```<code>In [367]: df
Out[367]:
    sp  mt  val  count
0  MM1  S1    a      3
1  MM1  S1    n      2
2  MM1  S3   cb      5
3  MM2  S3   mk      8
4  MM2  S4   bg     10
5  MM2  S4  dgb      1
6  MM4  S2   rd      2
7  MM4  S2   cb      2
8  MM4  S2  uyi      7

# Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]
Out[368]:
    sp  mt  val  count
0  MM1  S1    a      3
2  MM1  S3   cb      5
3  MM2  S3   mk      8
4  MM2  S4   bg     10
8  MM4  S2  uyi      7

# Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values
Out[369]: array([0, 2, 3, 4, 8])
</code>```

Body:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?

Example 1: the following DataFrame:

   Sp   Mt Value   count
0  MM1  S1   a     **3**
1  MM1  S1   n       2
2  MM1  S3   cb    **5**
3  MM2  S3   mk    **8**
4  MM2  S4   bg    **10**
5  MM2  S4   dgd     1
6  MM4  S2   rd      2
7  MM4  S2   cb      2
8  MM4  S2   uyi   **7**

Expected output is to get the result rows whose count is max in each group, like this:

   Sp   Mt   Value  count
0  MM1  S1   a      **3**
2  MM1  S3   cb     **5**
3  MM2  S3   mk     **8**
4  MM2  S4   bg     **10**
8  MM4  S2   uyi    **7**

Example 2:

   Sp   Mt   Value  count
4  MM2  S4   bg     10
5  MM2  S4   dgd    1
6  MM4  S2   rd     2
7  MM4  S2   cb     8
8  MM4  S2   uyi    8

Expected output:

   Sp   Mt   Value  count
4  MM2  S4   bg     10
7  MM4  S2   cb     8
8  MM4  S2   uyi    8

Body:
Easy solution would be to apply the idxmax() function to get indices of rows with max values.
This would filter out all the rows with max value in the group.

In [367]: df
Out[367]:
    sp  mt  val  count
0  MM1  S1    a      3
1  MM1  S1    n      2
2  MM1  S3   cb      5
3  MM2  S3   mk      8
4  MM2  S4   bg     10
5  MM2  S4  dgb      1
6  MM4  S2   rd      2
7  MM4  S2   cb      2
8  MM4  S2  uyi      7

# Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]
Out[368]:
    sp  mt  val  count
0  MM1  S1    a      3
2  MM1  S3   cb      5
3  MM2  S3   mk      8
4  MM2  S4   bg     10
8  MM4  S2  uyi      7

# Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values
Out[369]: array([0, 2, 3, 4, 8])


问:
error when checking for nil in CKAsset
I'm working with CloudKit and when loading data I'm checking in code if CKAsset is nil or not such as:

```<code>let img = result.value(forKey: "Picture") as! CKAsset
if  img != nil {

}
</code>```

and getting following error:

"Comparing non-optional value type 'CKAsset' to nil always returns true

I know it has something to do with optionals but not able to find solution.

答:
img can't be nil because you are force-casting it to CKAsset. Of course your app will crash at runtime if result.value(forKey: "Picture") returns nil or it's not actually a CKAsset.

The proper way to code this is follows:

```<code>if let img = result.value(forKey: "Picture") as? CKAsset {
    // do something with img
} else {
    // there is no Picture value or it's not actually a CKAsset
}
</code>```

Title: error when checking for nil in CKAsset

Body:
I'm working with CloudKit and when loading data I'm checking in code if CKAsset is nil or not such as:

let img = result.value(forKey: "Picture") as! CKAsset
if  img != nil {

}

and getting following error:

"Comparing non-optional value type 'CKAsset' to nil always returns true

I know it has something to do with optionals but not able to find solution.

Body:
img can't be nil because you are force-casting it to CKAsset. Of course your app will crash at runtime if result.value(forKey: "Picture") returns nil or it's not actually a CKAsset.

The proper way to code this is follows:

if let img = result.value(forKey: "Picture") as? CKAsset {
    // do something with img
} else {
    // there is no Picture value or it's not actually a CKAsset
}


答:
This could be much simpler.

```<code>if bool1 or bool2:
    print(False)
else:
    print(True)
</code>```

You can also, I believe, do

```<code>print(not(bool1 or bool2))
</code>```

which is simpler still.

Title: Python Boolean and Logical Operators

Body:
This could be much simpler.

if bool1 or bool2:
    print(False)
else:
    print(True)

You can also, I believe, do

print(not(bool1 or bool2))

which is simpler still.


问:
C# probe for and capture Javascript Alert() and Confirm()
So I've been doing some research for a while and I'm at a dead end. I'm doing some IE automation. In C#/.NET, how do I probe for and consume a javascript alert() or confirm() so I can do things like grab its text and click the OK\Cancel buttons?

Update:

I need to reiterate: I need to be able to pull and verify the text from an alert() or confirm() as well as send it an OK or Cancel click. An example of such a test would be to make sure that, when I click on delete, the confirm() doesn't say "Are you sure you'd like to go to Mexico?" or anything else except the proper message.

Just in case, let me reiterate: For the purposes of this test, I have zero control over the source of the website in question.

Lastly, I'm using SHDocVw.InternetExplorer.

答:
FindWindow - will get you close; you do want a window handle but you won't for sure know how to find it.

Better would be do use EnumWindows.Here's an example of a routine you can run every second or two that will give you a ton of info about every single window on the system, then you can analyze it. You can check the type of window, the text in it, get the buttons, and send a click message to the right one. It will let you do everything you are hoping to be able to do.

To get the text you send a wm_gettext and for the button you may get away with wm_click.

Sorry for the C. the next best example I could find was in LISP. Take time to read the code, you will see what the idea is. The Matching functions help determine if the text is right without knowing it exactly.

If you can manage to do this in c# I am betting you will get a lot shorter solution. (can you use LINQ on the output of EnumWindows?;-)

```<code>#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "resource.h"

#define ET_STARTUP 1
#define ET_WINDOWOPEN 2
#define ET_RUNEND 3
#define ET_USEREVENT 4
#define M_STAR 1
#define M_QUESTION 2

typedef struct WindowList_s
{
 int iScriptLine;
 HWND hwnd;
    char *stName;
 char *stTitle;
 char *stClassName;
 char *stParentName;
 struct WindowList_s *wlParentPtr;
 char *stChildName;
 struct WindowList_s *wlChildPtr;
 int bWarned;
 struct WindowList_s *next;
} WindowList_t;

////////////////

extern long g_runids[];
extern WindowList_t *g_windowlist;
extern EventList_t *g_eventlist;
char stWTx[2000];
char stWCl[200];
char stPTx[2500];
char stPCl[200];
int bEventEntry=0; // means we're inside of processing an event.
HWND LogWinParent;

void FixIt(char *buf,unsigned int siz)
{
 int i,j,bump;
 int ir;
 char cr;
 char hex[10];
 // keep special characters from screwing up script by
 // replacing w/ single-character wildcard
    for (i=0;buf[i];i++)
 {
  cr='\0';
  ir=0;
  bump=1;
  switch(buf[i])
  {
  case '\0':cr='0';break;
  case '\\':cr='\\';break;
  case '\n':cr='n';break;
  case '\t':cr='t';break;
  case '\a':cr='a';break;
  case '\b':cr='b';break;
  case '\f':cr='f';break;
  case '\r':cr='r';break;
  case M_STAR:cr='*';break;
  case M_QUESTION:cr='*';break;
  case '"':cr='"';break;
  default:
   if (buf[i]<32 || buf[i]>=127)
   {
    bump=2;
    ir=buf[i];
   }
   else
    bump=0;
  }
  if (bump)
  {
   for (j=strlen(buf)+bump+1>=siz-1?siz-1:strlen(buf)+1;
    j>i;j--)
     buf[j+bump]=buf[j];
   buf[siz-1]='\0';
   if (cr)
   {
    buf[i++]='\\';
    buf[i]=cr;
   }
   if (ir)
   {
    sprintf(hex,"\\x%00H",ir);
    memcpy(buf+i,hex,4);
    i+=4;
   }
  }
 }
}
void LogWin(HWND hw)
{
 static long ParentNum=0,ChildNum=0;

 GetWindowText(hw,stWTx,sizeof(stWTx)-1);
 GetClassName(hw,stWCl,sizeof(stWCl)-1);
 FixIt(stWTx,sizeof(stWTx));
 FixIt(stWCl,sizeof(stWCl));
 if (GetParent(hw)==LogWinParent)
 {
  ChildNum++;
  sprintf(stPTx,"        WindowObject %ld.%ld \"%s\" \"%s\" "
   "Parent %ld",ParentNum,ChildNum,stWTx,stWCl,ParentNum);
 }
 else if (hw==LogWinParent)
 {
  ChildNum=0;
  ParentNum++;
  sprintf(stPTx,"    WindowObject %ld \"%s\" \"%s\"",
   ParentNum,stWTx,stWCl);
 }
 else
 {
  ChildNum++;
  sprintf(stPTx,"            WindowObject %ld.%ld \"%s\" \"%s\" GRANDCHILD",
   ParentNum,ChildNum,stWTx,stWCl);
 }
 log_it(stPTx);
}

BOOL CALLBACK EnumChildProc4Logging(  HWND hwnd,LPARAM lParam )
{
    LogWin(hwnd);
 return 1;
}

void LogCurrentWindows(void)
{
 static int bEntry=0;
 static HWND hwCurrentFocus = 0;

 if (bEntry)
  return;
 bEntry=1;
    LogWinParent=GetForegroundWindow();
 if (LogWinParent!=hwCurrentFocus)
 {
  hwCurrentFocus=LogWinParent;
  LogWin(LogWinParent);
  EnumChildWindows(LogWinParent,EnumChildProc4Logging,0);
 }
 bEntry=0;
}

/******************************************************************/
/* match() - parse wildcard strings .                             */
/******************************************************************/
int match(char *pattern,char *str)
{
    int patt,st;

    patt=0;
    st=0;
    while(pattern[patt] || str[st])  /* go until both at '\0' */
    {
        if ((!pattern[patt] || !str[st]) && pattern[patt]!=M_STAR)
            return 0;  /* fail if one at '\0' */
        if (pattern[patt]==M_STAR)
        {
            patt++;
            while (str[st] && !match(pattern+patt,str+st))
            st++;
        }
        else if (pattern[patt]!=M_QUESTION && pattern[patt]!=str[st])
            return 0;  /* Oh, No!! no match. */
        else
        {
            patt++;
            st++;
        }
    }
    return 1;  /* successful match */
}
void CheckWindowList(HWND hwnd)
{
 WindowList_t *wl;
 HWND hwndParent,hwndTarget;
 static char buf[600];
 // Get the window's class and text
 GetWindowText(hwnd,stWTx,sizeof(stWTx)-1);
 GetClassName(hwnd,stWCl,sizeof(stWCl)-1);
 // Get the Parent Window's class and text
 hwndParent=GetParent(hwnd);
 GetWindowText(hwndParent,stPTx,sizeof(stPTx)-1);
 GetClassName(hwndParent,stPCl,sizeof(stPCl)-1);

 // search thru window objects, fill in
 // matching hwnds as appropriate
 for (wl=g_windowlist;wl;wl=wl->next)
 {
  hwndTarget=NULL; // separate variable enables
                // warning on duplicate matches
  if (wl->wlChildPtr==NULL && wl->wlParentPtr==NULL)
  { // no parent/child requirements
   if (match(wl->stClassName,stWCl) &&
     match(wl->stTitle,stWTx) )
       hwndTarget=hwnd;
  }
  else if (wl->wlParentPtr)
  { // parent requirement - if I (hwnd) match the
    // wl's class/title and the parent (hwndParent)
          // matches the wl's parentptr's class/title then
    // set 'me' as the window that matches and has
    // the proper parent requirement.
   if (match(wl->stClassName,stWCl) &&
     match(wl->stTitle,stWTx) &&
     match(wl->wlParentPtr->stClassName,stPCl) &&
     match(wl->wlParentPtr->stTitle,stPTx) )
       hwndTarget=hwnd;
  }
  else
  { // child requirement - if I (hwnd) match the child
    // requirement's stuff and the parent(hwndParent)
    // matches the wl's stuff then set the parent
    // as that wl's hwnd.
   if (match(wl->stClassName,stPCl) &&
     match(wl->stTitle,stPTx) &&
     match(wl->wlChildPtr->stClassName,stWCl) &&
     match(wl->wlChildPtr->stTitle,stWTx) )
       hwndTarget=hwndParent;
  }
  if (hwndTarget)
  {
   if (wl->hwnd && !wl->bWarned ) // log a warning on dup windows
   {
    sprintf(buf,"267.EnumChildProc4Search.10 "
     "Warning: more than one match for "
     "windowobject %s exists",wl->stName);
    log_it(buf);
    wl->bWarned =1;
   }
   else
    wl->hwnd=hwndTarget;
  }
 }
}
BOOL CALLBACK EnumChildProc4Search(  HWND hwnd,LPARAM lParam )
{
    CheckWindowList(hwnd);
    // return value of 1 means continue with rest of enumeration.
 return 1;
}

// to enumerate all... enumchild w/ NULL hwnd don't work???!
BOOL CALLBACK EnumWindowProc4Search(  HWND hwnd,LPARAM lParam )
{
    CheckWindowList(hwnd);
 EnumChildWindows(hwnd,EnumChildProc4Search,0);
 return 1;
}

// Check thru all windows and runIDs to see if a run is done
// or a window has opened. First emumerate the windows and running
// programs and then see which events should be run.
// this function must not run if blocked, 'once' countdown
// has run out, or stopscript=1, or entry = 1
void RunEvents(void)
{
// Please keep in mind this program's error philosphoy when
// extending it, namely, catch all possible script errors
// when loading script, but do not display messageboxes for
// even the most serious errors when doing events, because
// the idea is to catch errors during development and avoid
// errors at run time or in production!!
 static bEventEntry=0;
 WindowList_t *wl;
 EventList_t *el;
 ParmList_t *pl;
 char *st;
 int i;
 long lExitCode;

 // exit this routine if we shouldn't be here
    if (g_iStopScript || bEventEntry)
  return;
 bEventEntry=1;
 // clear all of the window handles in windowobject list
 for (wl=g_windowlist;wl;wl=wl->next)
 {
  wl->hwnd=NULL;
  wl->bWarned = 0;
 }

 // enumerate all windows in the system; repopulate all of
 // the window handles in the windowobject list
 EnumWindows(EnumWindowProc4Search,0);

 // go thru event list, calling any events that must
 // be called; windows handles for any subsequent actions
 // will have been set by above code. Check for runs ending
 // to process runend events and search the windowobject list
 // to process windowopen events.
 for (el=g_eventlist;g_eventlist && el;el=el->next)
 {
  pl=MakeParms(el->stEventTypeSourceLine);
  st=ParmValue(pl,2); // event name
  // check for windowopen events
  if (el->iEventType==ET_WINDOWOPEN)
  { // search for their open windows!!
   for (wl=g_windowlist;wl;wl=wl->next)
   {
    if (0==_stricmp(wl->stName,st) && wl->hwnd)
     RunActions(el);
    if (g_iStopScript)
     return; // quit doing actions/events ASAP.  }
   }
  }
  if (el->iEventType==ET_RUNEND)
  {
   sscanf(st,"%ld",&i);
   if (g_runids[i]!=-1 && g_runids[i]!=0)
   {
    GetExitCodeProcess((HANDLE)g_runids[i],&lExitCode);
    if (lExitCode != STILL_ACTIVE)
    {
     RunActions(el);
     g_runids[i]=0;
    }
   }
  }
  KillParms(pl);
 }
 bEventEntry=0;
}

void RunStartup(void)
{
 EventList_t *el;

    if (bEventEntry)
  return;
 bEventEntry=1;
 // check stopscript in case of endscript in startup event!
 for (el=g_eventlist;g_eventlist && el && !g_iStopScript;el=el->next)
 {
  if (el->iEventType==ET_STARTUP)
   RunActions(el);
 }
 bEventEntry=0;
}
</code>```

Body:
FindWindow - will get you close; you do want a window handle but you won't for sure know how to find it.

Better would be do use EnumWindows.Here's an example of a routine you can run every second or two that will give you a ton of info about every single window on the system, then you can analyze it. You can check the type of window, the text in it, get the buttons, and send a click message to the right one. It will let you do everything you are hoping to be able to do.

To get the text you send a wm_gettext and for the button you may get away with wm_click.

Sorry for the C. the next best example I could find was in LISP. Take time to read the code, you will see what the idea is. The Matching functions help determine if the text is right without knowing it exactly.

If you can manage to do this in c# I am betting you will get a lot shorter solution. (can you use LINQ on the output of EnumWindows?;-)

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "resource.h"

#define ET_STARTUP 1
#define ET_WINDOWOPEN 2
#define ET_RUNEND 3
#define ET_USEREVENT 4
#define M_STAR 1
#define M_QUESTION 2

typedef struct WindowList_s
{
 int iScriptLine;
 HWND hwnd;
    char *stName;
 char *stTitle;
 char *stClassName;
 char *stParentName;
 struct WindowList_s *wlParentPtr;
 char *stChildName;
 struct WindowList_s *wlChildPtr;
 int bWarned;
 struct WindowList_s *next;
} WindowList_t;

////////////////

extern long g_runids[];
extern WindowList_t *g_windowlist;
extern EventList_t *g_eventlist;
char stWTx[2000];
char stWCl[200];
char stPTx[2500];
char stPCl[200];
int bEventEntry=0; // means we're inside of processing an event.
HWND LogWinParent;

void FixIt(char *buf,unsigned int siz)
{
 int i,j,bump;
 int ir;
 char cr;
 char hex[10];
 // keep special characters from screwing up script by
 // replacing w/ single-character wildcard
    for (i=0;buf[i];i++)
 {
  cr='\0';
  ir=0;
  bump=1;
  switch(buf[i])
  {
  case '\0':cr='0';break;
  case '\\':cr='\\';break;
  case '\n':cr='n';break;
  case '\t':cr='t';break;
  case '\a':cr='a';break;
  case '\b':cr='b';break;
  case '\f':cr='f';break;
  case '\r':cr='r';break;
  case M_STAR:cr='*';break;
  case M_QUESTION:cr='*';break;
  case '"':cr='"';break;
  default:
   if (buf[i]<32 || buf[i]>=127)
   {
    bump=2;
    ir=buf[i];
   }
   else
    bump=0;
  }
  if (bump)
  {
   for (j=strlen(buf)+bump+1>=siz-1?siz-1:strlen(buf)+1;
    j>i;j--)
     buf[j+bump]=buf[j];
   buf[siz-1]='\0';
   if (cr)
   {
    buf[i++]='\\';
    buf[i]=cr;
   }
   if (ir)
   {
    sprintf(hex,"\\x%00H",ir);
    memcpy(buf+i,hex,4);
    i+=4;
   }
  }
 }
}
void LogWin(HWND hw)
{
 static long ParentNum=0,ChildNum=0;

 GetWindowText(hw,stWTx,sizeof(stWTx)-1);
 GetClassName(hw,stWCl,sizeof(stWCl)-1);
 FixIt(stWTx,sizeof(stWTx));
 FixIt(stWCl,sizeof(stWCl));
 if (GetParent(hw)==LogWinParent)
 {
  ChildNum++;
  sprintf(stPTx,"        WindowObject %ld.%ld \"%s\" \"%s\" "
   "Parent %ld",ParentNum,ChildNum,stWTx,stWCl,ParentNum);
 }
 else if (hw==LogWinParent)
 {
  ChildNum=0;
  ParentNum++;
  sprintf(stPTx,"    WindowObject %ld \"%s\" \"%s\"",
   ParentNum,stWTx,stWCl);
 }
 else
 {
  ChildNum++;
  sprintf(stPTx,"            WindowObject %ld.%ld \"%s\" \"%s\" GRANDCHILD",
   ParentNum,ChildNum,stWTx,stWCl);
 }
 log_it(stPTx);
}

BOOL CALLBACK EnumChildProc4Logging(  HWND hwnd,LPARAM lParam )
{
    LogWin(hwnd);
 return 1;
}

void LogCurrentWindows(void)
{
 static int bEntry=0;
 static HWND hwCurrentFocus = 0;

 if (bEntry)
  return;
 bEntry=1;
    LogWinParent=GetForegroundWindow();
 if (LogWinParent!=hwCurrentFocus)
 {
  hwCurrentFocus=LogWinParent;
  LogWin(LogWinParent);
  EnumChildWindows(LogWinParent,EnumChildProc4Logging,0);
 }
 bEntry=0;
}

/******************************************************************/
/* match() - parse wildcard strings .                             */
/******************************************************************/
int match(char *pattern,char *str)
{
    int patt,st;

    patt=0;
    st=0;
    while(pattern[patt] || str[st])  /* go until both at '\0' */
    {
        if ((!pattern[patt] || !str[st]) && pattern[patt]!=M_STAR)
            return 0;  /* fail if one at '\0' */
        if (pattern[patt]==M_STAR)
        {
            patt++;
            while (str[st] && !match(pattern+patt,str+st))
            st++;
        }
        else if (pattern[patt]!=M_QUESTION && pattern[patt]!=str[st])
            return 0;  /* Oh, No!! no match. */
        else
        {
            patt++;
            st++;
        }
    }
    return 1;  /* successful match */
}
void CheckWindowList(HWND hwnd)
{
 WindowList_t *wl;
 HWND hwndParent,hwndTarget;
 static char buf[600];
 // Get the window's class and text
 GetWindowText(hwnd,stWTx,sizeof(stWTx)-1);
 GetClassName(hwnd,stWCl,sizeof(stWCl)-1);
 // Get the Parent Window's class and text
 hwndParent=GetParent(hwnd);
 GetWindowText(hwndParent,stPTx,sizeof(stPTx)-1);
 GetClassName(hwndParent,stPCl,sizeof(stPCl)-1);

 // search thru window objects, fill in
 // matching hwnds as appropriate
 for (wl=g_windowlist;wl;wl=wl->next)
 {
  hwndTarget=NULL; // separate variable enables
                // warning on duplicate matches
  if (wl->wlChildPtr==NULL && wl->wlParentPtr==NULL)
  { // no parent/child requirements
   if (match(wl->stClassName,stWCl) &&
     match(wl->stTitle,stWTx) )
       hwndTarget=hwnd;
  }
  else if (wl->wlParentPtr)
  { // parent requirement - if I (hwnd) match the
    // wl's class/title and the parent (hwndParent)
          // matches the wl's parentptr's class/title then
    // set 'me' as the window that matches and has
    // the proper parent requirement.
   if (match(wl->stClassName,stWCl) &&
     match(wl->stTitle,stWTx) &&
     match(wl->wlParentPtr->stClassName,stPCl) &&
     match(wl->wlParentPtr->stTitle,stPTx) )
       hwndTarget=hwnd;
  }
  else
  { // child requirement - if I (hwnd) match the child
    // requirement's stuff and the parent(hwndParent)
    // matches the wl's stuff then set the parent
    // as that wl's hwnd.
   if (match(wl->stClassName,stPCl) &&
     match(wl->stTitle,stPTx) &&
     match(wl->wlChildPtr->stClassName,stWCl) &&
     match(wl->wlChildPtr->stTitle,stWTx) )
       hwndTarget=hwndParent;
  }
  if (hwndTarget)
  {
   if (wl->hwnd && !wl->bWarned ) // log a warning on dup windows
   {
    sprintf(buf,"267.EnumChildProc4Search.10 "
     "Warning: more than one match for "
     "windowobject %s exists",wl->stName);
    log_it(buf);
    wl->bWarned =1;
   }
   else
    wl->hwnd=hwndTarget;
  }
 }
}
BOOL CALLBACK EnumChildProc4Search(  HWND hwnd,LPARAM lParam )
{
    CheckWindowList(hwnd);
    // return value of 1 means continue with rest of enumeration.
 return 1;
}

// to enumerate all... enumchild w/ NULL hwnd don't work???!
BOOL CALLBACK EnumWindowProc4Search(  HWND hwnd,LPARAM lParam )
{
    CheckWindowList(hwnd);
 EnumChildWindows(hwnd,EnumChildProc4Search,0);
 return 1;
}

// Check thru all windows and runIDs to see if a run is done
// or a window has opened. First emumerate the windows and running
// programs and then see which events should be run.
// this function must not run if blocked, 'once' countdown
// has run out, or stopscript=1, or entry = 1
void RunEvents(void)
{
// Please keep in mind this program's error philosphoy when
// extending it, namely, catch all possible script errors
// when loading script, but do not display messageboxes for
// even the most serious errors when doing events, because
// the idea is to catch errors during development and avoid
// errors at run time or in production!!
 static bEventEntry=0;
 WindowList_t *wl;
 EventList_t *el;
 ParmList_t *pl;
 char *st;
 int i;
 long lExitCode;

 // exit this routine if we shouldn't be here
    if (g_iStopScript || bEventEntry)
  return;
 bEventEntry=1;
 // clear all of the window handles in windowobject list
 for (wl=g_windowlist;wl;wl=wl->next)
 {
  wl->hwnd=NULL;
  wl->bWarned = 0;
 }

 // enumerate all windows in the system; repopulate all of
 // the window handles in the windowobject list
 EnumWindows(EnumWindowProc4Search,0);

 // go thru event list, calling any events that must
 // be called; windows handles for any subsequent actions
 // will have been set by above code. Check for runs ending
 // to process runend events and search the windowobject list
 // to process windowopen events.
 for (el=g_eventlist;g_eventlist && el;el=el->next)
 {
  pl=MakeParms(el->stEventTypeSourceLine);
  st=ParmValue(pl,2); // event name
  // check for windowopen events
  if (el->iEventType==ET_WINDOWOPEN)
  { // search for their open windows!!
   for (wl=g_windowlist;wl;wl=wl->next)
   {
    if (0==_stricmp(wl->stName,st) && wl->hwnd)
     RunActions(el);
    if (g_iStopScript)
     return; // quit doing actions/events ASAP.  }
   }
  }
  if (el->iEventType==ET_RUNEND)
  {
   sscanf(st,"%ld",&i);
   if (g_runids[i]!=-1 && g_runids[i]!=0)
   {
    GetExitCodeProcess((HANDLE)g_runids[i],&lExitCode);
    if (lExitCode != STILL_ACTIVE)
    {
     RunActions(el);
     g_runids[i]=0;
    }
   }
  }
  KillParms(pl);
 }
 bEventEntry=0;
}

void RunStartup(void)
{
 EventList_t *el;

    if (bEventEntry)
  return;
 bEventEntry=1;
 // check stopscript in case of endscript in startup event!
 for (el=g_eventlist;g_eventlist && el && !g_iStopScript;el=el->next)
 {
  if (el->iEventType==ET_STARTUP)
   RunActions(el);
 }
 bEventEntry=0;
}


问:
Linux Shell, Awk : Merge 2 Variable Data by Column
The left part data (in variable) like :

```<code> echo "$lpart"

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"
</code>```

The right part data (in variable) like :

```<code>echo "$rpart"

"qhy2"
"qhy2"
"Apple Setup"
"qhy2"
</code>```

I would like to merge the 2 data by column, it is :

```<code> "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "Apple Setup"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"  "qhy2"
</code>```

This request is the same as the post : how to combine two variable column-by-column in bash, but my busybox does not support paste command.
I have tried the commands :

```<code> awk 'BEGIN{print ARGV[1], ARGV[2]}' "$lpart"  "$rpart"
 awk -v awk_lpart="$lpart" -v awk_rpart="$rpart" 'BEGIN{print awk_lpart awk_rpart }'
</code>```

those will merge by row..

Could you give me suggestion how I could achieve the request ? Thank you.

Body:
The left part data (in variable) like :

 echo "$lpart"

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"

The right part data (in variable) like :

echo "$rpart"

"qhy2"
"qhy2"
"Apple Setup"
"qhy2"

I would like to merge the 2 data by column, it is :

 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "qhy2"
 "2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55"  "Apple Setup"
 "2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55"  "qhy2"

This request is the same as the post : how to combine two variable column-by-column in bash, but my busybox does not support paste command.
I have tried the commands :

 awk 'BEGIN{print ARGV[1], ARGV[2]}' "$lpart"  "$rpart"
 awk -v awk_lpart="$lpart" -v awk_rpart="$rpart" 'BEGIN{print awk_lpart awk_rpart }'

those will merge by row..

Could you give me suggestion how I could achieve the request ? Thank you.

Body:
Building on one of your attempts:

awk -v awk_lpart="$lpart" -v awk_rpart="$rpart" 'BEGIN{
    split(awk_lpart,lp,/\n/)
    split(awk_rpart,rp,/\n/)
    for (i=1; i in lp; i++) {
        print lp[i], rp[i]
    }
}'
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "qhy2"
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "qhy2"
"2017-07-03 13:39:5", "-39dB", "7c:e9:d3:f1:61:55" "Apple Setup"
"2017-07-03 13:39:5", "-37dB", "7c:e9:d3:f1:61:55" "qhy2"

That will work with any awk in any shell on any UNIX box.