问:
Perspective projection for a polygon Using OpenGL
I'm trying to implement a perspective projection using open-GL
But when I apply gluPerspective(0,0.5,0.5,5) method, the polygon is not shown in a perspective view and shown in orthogonal view instead
here is the output

Anyone can help
my code:

```<code>#include<GL/glut.h>
float angle = 2;
void myinit(void)
{
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 5);
    //glFrustum(-0.5, 2.4, -0.5, 0.5, -0.5, 0.5);
    //glFrustum(-5.0, 5.0, -5.0, 5.0, 5, 100);
    gluPerspective(0,0.5,0.5,5);
}

void polygon(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0, 0.0, 1.0);
    //glLineWidth(2);
    //glRotatef(angle, 0.0, 0.0, 1.0);
    glBegin(GL_POLYGON);
    glVertex3f(0.25, 0.25, 0.0);
    glVertex3f(0.75, 0.25, 0.0);
    glVertex3f(0.75, 0.75, 0.0);
    glVertex3f(0.25, 0.75, 0.0);
    //glVertex3f(0, 0.5, 0.0);
    glEnd();
    glFlush();
}
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(50, 100);
    glutInitWindowSize(1000, 1000);
    glutCreateWindow("Open Gl 2D Geometric Transformation");
    myinit();
    glutDisplayFunc(polygon);
    glutMainLoop();

    return 0;
}
</code>```

答:
the first argument to to gluPerspective is wrong:

gluPerspective(0,0.5,0.5,5);
```
</blockquote>

<p>The first argument to <code>gluPerspective</code> is the vertical field of view angle in degrees. The value has to be greater than 0.0 and less than 180. 0.0 is an invalid argument and causes undefined behavior.
Probably the instruction doesn't set the matrix at all.</p>

<p>Anyway, if you set a correct angle, then the geometry will be clipped. The perspective projection matrix defines a Viewing frustum. All the geometry which is not in between the near and fare plane is clipped. In your case the near plane is 0.5 and the far plane 5.0. </p>

<p><img src="https://i.stack.imgur.com/NhaeB.gif" alt=""></p>

<p>Set a view matrix and translate the geometry in between the near and far plane, by shifting the geometry along the negative z axis. For instance (0, 0, -2.5).</p>

<p>The 2nd argument of <code>gluPerspective</code> is the aspect ration. Since the size of the window is 1000x1000, the aspect ratio has to be 1.0: </p>

<pre class="lang-cpp prettyprint-override"><code>void myinit(void)
{
    glClearColor(1.0, 1.0, 1.0, 0.0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLdouble fov = 90.0; // 90 degrees
    GLdouble aspect = 1.0;
    GLdouble near_dist = 0.5;
    GLdouble far_dist = 5.0;
    gluPerspective(fov, aspect, near_dist, far_dist);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -2.5f); // near_dist < 2.5 < far_dist
}
</code>```

Body:
I'm trying to implement a perspective projection using open-GL
But when I apply gluPerspective(0,0.5,0.5,5) method, the polygon is not shown in a perspective view and shown in orthogonal view instead
here is the output

Anyone can help
my code:

#include<GL/glut.h>
float angle = 2;
void myinit(void)
{
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 5);
    //glFrustum(-0.5, 2.4, -0.5, 0.5, -0.5, 0.5);
    //glFrustum(-5.0, 5.0, -5.0, 5.0, 5, 100);
    gluPerspective(0,0.5,0.5,5);
}

void polygon(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0, 0.0, 1.0);
    //glLineWidth(2);
    //glRotatef(angle, 0.0, 0.0, 1.0);
    glBegin(GL_POLYGON);
    glVertex3f(0.25, 0.25, 0.0);
    glVertex3f(0.75, 0.25, 0.0);
    glVertex3f(0.75, 0.75, 0.0);
    glVertex3f(0.25, 0.75, 0.0);
    //glVertex3f(0, 0.5, 0.0);
    glEnd();
    glFlush();
}
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(50, 100);
    glutInitWindowSize(1000, 1000);
    glutCreateWindow("Open Gl 2D Geometric Transformation");
    myinit();
    glutDisplayFunc(polygon);
    glutMainLoop();

    return 0;
}

Body:
the first argument to to gluPerspective is wrong:

gluPerspective(0,0.5,0.5,5);

The first argument to gluPerspective is the vertical field of view angle in degrees. The value has to be greater than 0.0 and less than 180. 0.0 is an invalid argument and causes undefined behavior.
Probably the instruction doesn't set the matrix at all.

Anyway, if you set a correct angle, then the geometry will be clipped. The perspective projection matrix defines a Viewing frustum. All the geometry which is not in between the near and fare plane is clipped. In your case the near plane is 0.5 and the far plane 5.0.

Set a view matrix and translate the geometry in between the near and far plane, by shifting the geometry along the negative z axis. For instance (0, 0, -2.5).

The 2nd argument of gluPerspective is the aspect ration. Since the size of the window is 1000x1000, the aspect ratio has to be 1.0:

void myinit(void)
{
    glClearColor(1.0, 1.0, 1.0, 0.0);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLdouble fov = 90.0; // 90 degrees
    GLdouble aspect = 1.0;
    GLdouble near_dist = 0.5;
    GLdouble far_dist = 5.0;
    gluPerspective(fov, aspect, near_dist, far_dist);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -2.5f); // near_dist < 2.5 < far_dist
}


来源: stackexchange

问:
Get object from another part of a python script without activating the whole script
I have two python scripts: one script which triggers an API, and another script which I want to read information from the API call. That is, let's say script1 has a variable "word" that it grabs during its API call and I want script2 to be able to read it and print it.

I tried using the method of importing (this is pseudo-code):

```<code>import script1
print script1.word
</code>```

The problem is the first API is a "polling" script, which activates and stays on. So, when I called the import, as soon I did anything in script2 related to the import from script1, the polling function was activated as part of script2's run. So, then I have two scripts running the API.

What I want is for script1 to just store the variable and for script2 to print it (or be able to use it however I want as a normal variable/object in script2).

I hope this makes sense. I can't come up with a simple example to past here because of the API. So, I'm having difficulty making this question more clear and I'd be happy to answer any questions,

答:
Your first script needs to put its actual polling in a block like this:

```<code>if __name__ == '__main__':
    # do polling stuff
</code>```

to have that logic execute when the script itself is executed but not also when it's imported.

ContentLicense: CC BY-SA 4.0

Body:
I have two python scripts: one script which triggers an API, and another script which I want to read information from the API call. That is, let's say script1 has a variable "word" that it grabs during its API call and I want script2 to be able to read it and print it.

I tried using the method of importing (this is pseudo-code):

import script1
print script1.word

The problem is the first API is a "polling" script, which activates and stays on. So, when I called the import, as soon I did anything in script2 related to the import from script1, the polling function was activated as part of script2's run. So, then I have two scripts running the API.

What I want is for script1 to just store the variable and for script2 to print it (or be able to use it however I want as a normal variable/object in script2).

I hope this makes sense. I can't come up with a simple example to past here because of the API. So, I'm having difficulty making this question more clear and I'd be happy to answer any questions,

Body:
Your first script needs to put its actual polling in a block like this:

if __name__ == '__main__':
    # do polling stuff

to have that logic execute when the script itself is executed but not also when it's imported.


问:
How to specify the correct return type of SQLiteDatabase.query
Android Studio has me running in circles! With the following code

```<code>fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}
</code>```

Android Studio marks an error at the closing } , saying

A 'return' expression required in a function with a block body.

The suggested Quick Fix is

Remove explicitly specified return type of enclosing function 'DBAdapter.fetchAllPOIs'

If I accept the quick fix the code looks like

```<code>    fun fetchAllPOIs() {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}
</code>```

with most of the function underlined. The suggested Quick Fix is

Change return type of enclosing function to 'Cursor?'

When I accept this I get back to square one!

How do I get out of this?

答:
Let's go back to your original source:

```<code>fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}
</code>```

What is supposed to be returned if myDbHelper.myDataBase == null? The compiler does not know, because you have not told it what to return.

Let's pretend that you want to return null.

You have three possible solutions. The Java-style solution is:

```<code>fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null) {
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
    } else {
      return null
    }
}
</code>```

You have the more Kotlin-y "lift the return out of the if/else" approach:

```<code>fun fetchAllPOIs(): Cursor? {
    return if (myDbHelper.myDataBase != null) {
      myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
    } else {
      null
    }
}
</code>```

And you have the very Kotlin-y safe call approach:

```<code>fun fetchAllPOIs(): Cursor? {
    return myDbHelper.myDataBase?.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
}
</code>```

?. is the "safe call" operator. If myDbHelper.myDataBase is not null, it calls query(). If myDbHelper.myDataBase is null, ?. skips the query() call and evaluates to null.

If you were planning on returning something else other than null, then some of this will need revising.

Body:
Android Studio has me running in circles! With the following code

fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}

Android Studio marks an error at the closing } , saying

A 'return' expression required in a function with a block body.

The suggested Quick Fix is

Remove explicitly specified return type of enclosing function 'DBAdapter.fetchAllPOIs'

If I accept the quick fix the code looks like

    fun fetchAllPOIs() {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}

with most of the function underlined. The suggested Quick Fix is

Change return type of enclosing function to 'Cursor?'

When I accept this I get back to square one!

How do I get out of this?

Body:
Let's go back to your original source:

fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null)
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null
    )
}

What is supposed to be returned if myDbHelper.myDataBase == null? The compiler does not know, because you have not told it what to return.

Let's pretend that you want to return null.

You have three possible solutions. The Java-style solution is:

fun fetchAllPOIs(): Cursor? {
    if (myDbHelper.myDataBase != null) {
        return myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
    } else {
      return null
    }
}

You have the more Kotlin-y "lift the return out of the if/else" approach:

fun fetchAllPOIs(): Cursor? {
    return if (myDbHelper.myDataBase != null) {
      myDbHelper.myDataBase!!.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
    } else {
      null
    }
}

And you have the very Kotlin-y safe call approach:

fun fetchAllPOIs(): Cursor? {
    return myDbHelper.myDataBase?.query(
        "POIs", arrayOf(
            "Name", "Type",
            "Latitude", "Longitude", "_id"
        ), null, null, null, null, null)
}

?. is the "safe call" operator. If myDbHelper.myDataBase is not null, it calls query(). If myDbHelper.myDataBase is null, ?. skips the query() call and evaluates to null.

If you were planning on returning something else other than null, then some of this will need revising.


问:
How to make service registration dependent on configuration?
I would like to wire the services in the configuration file, something like

```<code>builder.Services.AddTransient<MyService>(s => s.GetServiceFromSetting<MyAppSetting>("MyServiceA"));
</code>```

I could instead use reflection to get the type (although I am not sure if the configuration is available in Startup already, at least with Azure functions there is an issue: https://github.com/Azure/azure-webjobs-sdk/issues/2406).

I was wondering, if there is a better way to get this done.

答:
Presumably your configuration won't change while the application is running. Your configuration is loaded at startup. Dependencies are registered at startup. So startup is an ideal place to decide which implementation you'll use based on configuration.

Assume you've read some value from configuration. You could use a string, a boolean, whatever. An enum might be a good choice if there are numerous possibilities.

You've got your value, whatever it is, read from startup. In this case I'll use a boolean.

```<code>if(someFlag)
{
    builder.Services.AddTransient<ISomeService, SomeImplementation>();
}
else
{
    builder.Services.AddTransient<ISomeService, SomeOtherImplementation>();
}
</code>```

Now instead of having code that reads from configuration at runtime (as opposed to startup) the decision is made once. After all, why keep checking a value over and over at runtime if it's determined by a configuration value that doesn't change at runtime?

You could use the actual type name as a setting:

```<code>var serviceTypeName = Configuration.GetValue<string>("serviceType");
var serviceType = Type.GetType(serviceTypeName);
if (typeof(IMyService).IsAssignableFrom(serviceType))
{
    services.AddTransient<IMyService>(provider => (IMyService)provider.GetRequiredService(serviceType));
}
else
{
    throw new Exception("The type name specified in settings doesn't implement IMyService.");
}
</code>```

which in turn can be packaged as a reusable exension:

```<code>public static class RegisterServiceFromConfigurationExtension
{
    public static IServiceCollection RegisterTransientFromConfiguration<TService>(
        this IServiceCollection serviceCollection,
        IConfiguration configuration,
        string typeSettingName)
    {
        var serviceTypeName = configuration.GetValue<string>(typeSettingName);
        var serviceType = Type.GetType(serviceTypeName);
        if (typeof(IMyService).IsAssignableFrom(serviceType))
        {
            serviceCollection.AddTransient<IMyService>(provider =>
                (IMyService)provider.GetRequiredService(serviceType));
        }
        else
        {
            throw new Exception($"The type name {serviceTypeName} does not implement {typeof(TService)}.");
        }

        return serviceCollection;
    }
}
</code>```

so now the whole thing would be boiled down to

```<code>services.RegisterTransientFromConfiguration<ISomeService>(configuration, "settingName");
</code>```

where "settingName" is the key for the settings value.

Body:
I would like to wire the services in the configuration file, something like

builder.Services.AddTransient<MyService>(s => s.GetServiceFromSetting<MyAppSetting>("MyServiceA"));

I could instead use reflection to get the type (although I am not sure if the configuration is available in Startup already, at least with Azure functions there is an issue: https://github.com/Azure/azure-webjobs-sdk/issues/2406).

I was wondering, if there is a better way to get this done.

Body:
Presumably your configuration won't change while the application is running. Your configuration is loaded at startup. Dependencies are registered at startup. So startup is an ideal place to decide which implementation you'll use based on configuration.

Assume you've read some value from configuration. You could use a string, a boolean, whatever. An enum might be a good choice if there are numerous possibilities.

You've got your value, whatever it is, read from startup. In this case I'll use a boolean.

if(someFlag)
{
    builder.Services.AddTransient<ISomeService, SomeImplementation>();
}
else
{
    builder.Services.AddTransient<ISomeService, SomeOtherImplementation>();
}

Now instead of having code that reads from configuration at runtime (as opposed to startup) the decision is made once. After all, why keep checking a value over and over at runtime if it's determined by a configuration value that doesn't change at runtime?

You could use the actual type name as a setting:

var serviceTypeName = Configuration.GetValue<string>("serviceType");
var serviceType = Type.GetType(serviceTypeName);
if (typeof(IMyService).IsAssignableFrom(serviceType))
{
    services.AddTransient<IMyService>(provider => (IMyService)provider.GetRequiredService(serviceType));
}
else
{
    throw new Exception("The type name specified in settings doesn't implement IMyService.");
}

which in turn can be packaged as a reusable exension:

public static class RegisterServiceFromConfigurationExtension
{
    public static IServiceCollection RegisterTransientFromConfiguration<TService>(
        this IServiceCollection serviceCollection,
        IConfiguration configuration,
        string typeSettingName)
    {
        var serviceTypeName = configuration.GetValue<string>(typeSettingName);
        var serviceType = Type.GetType(serviceTypeName);
        if (typeof(IMyService).IsAssignableFrom(serviceType))
        {
            serviceCollection.AddTransient<IMyService>(provider =>
                (IMyService)provider.GetRequiredService(serviceType));
        }
        else
        {
            throw new Exception($"The type name {serviceTypeName} does not implement {typeof(TService)}.");
        }

        return serviceCollection;
    }
}

so now the whole thing would be boiled down to

services.RegisterTransientFromConfiguration<ISomeService>(configuration, "settingName");

where "settingName" is the key for the settings value.


问:
True/false buttons for mchoice questions with exams2moodle
I am using R exams to create mchoice questions. I really would like to know if it's possible to obtain a "true" button and "false" button next to each statement with exams2moodle as in the following image:

答:
This is on our wishlist but, currently, it is not implemented in exams2moodle(). There are two alternatives, though:

You can ask the question as a standard multiple-choice question with a single check box for each statement. Then, checking the box corresponds to "true" and not checking the box corresponds to "false".

Alternatively, you can ask a cloze question with several schoice sub-questions. In each sub-question you could offer two options true/false. Especially when combining this with exams2moodle(..., cloze = list(cloze_mchoice_display = "MULTICHOICE_H")) you will get a similar formatting to the True/False item from your question.


问:
Build json from ValueObjects in Rails 3?
i was wondering how i can build a json response from a value object?

Situation?

I want to return clear json, only the field i need in the front-end. Which means: All associations should be included in the json. But again: only the fields I need. This i why i would like to use a special value object (defining the field) on top of my models.

Problem?

Is this a good idea? How to build value objects (VOs) with rails?

Thanks for helping

答:
This one sounds interesting:
http://fabrik42.github.com/acts_as_api/</p>

ContentLicense: CC BY-SA 3.0


问:
Vanilla JS - How To Stop Sub-Element's OnClick Method From Calling Parent Elements OnClick Method
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

```<code><script>
function chooseImage() {
  alert("chooseImage");
}

function deleteImage() {
  alert("deleteImage");
}
</script>

<style>
body {
  background: black;
}
</style>

<div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option" onclick="chooseImage()">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="">
        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div>
</code>```

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?

答:
function chooseImage() {
  alert("chooseImage");
}

function deleteImage(e) {
  e.stopPropagation();
  alert("deleteImage");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option" onclick="chooseImage()">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="">
        <button class="mod-del-btn" onclick="deleteImage(event)">Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div></code>```

Firstly you need to call delete image with event. Then only stopPropagation would work.

```<code><button class="mod-del-btn" onclick="deleteImage(event)">Delete</button>

function deleteImage(e) {
  e.stopPropagation();
  alert("deleteImage");
}
</code>```

Body:
Having to use VanillaJS (don't ask me why).

Struggling to wrap my head around this simple thing.

Here is my code:

        <input type="radio" id="img-1" name="images" checked="">

        <button class="mod-del-btn" onclick="deleteImage()">>Delete</button>

And view it on a codepen here: https://codepen.io/jacksonjack/pen/MWKgQQK

Now two things should happen:

user should click image and it should popup with an alert "chooseImage".

This works as expected.

However the second thing does not work as expected.

user should click image and it should popup with an alert "deleteImage".

However it shows "deleteImage" then the "chooseImage".

How do I stop this?

Body:
function chooseImage() {
  alert("chooseImage");
}

function deleteImage(e) {
  e.stopPropagation();
  alert("deleteImage");
}

<div class="mod-c-tab-col">
    <div class="mod-c-tab-img del-option" onclick="chooseImage()">
        <input type="radio" id="img-1" name="images" checked="">
        <label for="img-1"></label>
        <img src="https://public-assets.envato-static.com/assets/logos/envato_market-a5ace93f8482e885ae008eb481b9451d379599dfed24868e52b6b2d66f5cf633.svg" alt="">
        <button class="mod-del-btn" onclick="deleteImage(event)">Delete</button>
    </div><!-- /.mod-c-tab-img -->
</div>

Firstly you need to call delete image with event. Then only stopPropagation would work.

<button class="mod-del-btn" onclick="deleteImage(event)">Delete</button>

function deleteImage(e) {
  e.stopPropagation();
  alert("deleteImage");
}


问:
Get Offset of the other Location in Javascript
I am in Asia and I want to calculate the offset of Australia. I know how to calculate the value of the offset the code is written below:

```<code>var timezone_offset = new Date().getTimezoneOffset();
</code>```

But how to calculate it for the other locations? Anyone can guide me??

答:
While this can be done in a short function, it would be best to use a library as there are many quirks to overcome. The offset can be determined using the timezone options of toLocaleString or Intl.DateTimeFormat.

However, if the language used for formatting matches the language of the location, it returns the timezone abbreviation instead of the offset. To deal with that, the following function first uses English and if that returns the abbreviation rather than an offset, it uses French. English offsets start with GMT, French offsets start with UTC. Where the offset is +0, they return just "GMT" or "UTC".

It's been tested with all IANA locations listed by wikipedia and seems to work for all of them but it should be tested more widely. Also, there should be feature tests before attempting to run it (i.e. support for Int.DateTimeFormat constructor, formatToParts method and the timeZoneName option).

// Return offset on date for loc in ±H[:mm] format. Minutes only included if not zero
function getTimezoneOffset(date, loc) {
  // Try English to get offset. If get abbreviation, use French
  let offset;
  ['en','fr'].some(lang => {
    // Get parts - can't get just timeZoneName, must get one other part at least
    let parts = new Intl.DateTimeFormat(lang, {
      minute: 'numeric',
      timeZone: loc,
      timeZoneName:'short'
    }).formatToParts(date);
    // Get offset from parts
    let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
    // timeZoneName starting with GMT or UTC is offset - keep and stop looping
    // Otherwise it's an abbreviation, keep looping
    if (/^(GMT|UTC)/.test(tzName[0].value)) {
      offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
      return true;
    }
  });
  // Format offset as ±HH:mm
  // Normalise minus sign as ASCII minus (charCode 45)
  let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
  let [h, m] = offset.substring(1).split(':');
  return sign + h.padStart(2, '0') + ':' + (m || '00');
}

let d = new Date();
console.log('Current offset for following locations:');
['Australia/Yancowinna',
 'Australia/Lord_Howe',
 'Australia/Canberra',
 'Pacific/Honolulu',
 'Europe/London',
 'Canada/Eastern'
].forEach( loc =>
  console.log(loc + ': ' + getTimezoneOffset(d, loc))
);```

I don't suggest you use this function, it's really to show how messy getting the offset for a specific location can be.

Note that Australia has a number of offsets and some places observe daylight saving and others don't.

Body:
I am in Asia and I want to calculate the offset of Australia. I know how to calculate the value of the offset the code is written below:

var timezone_offset = new Date().getTimezoneOffset();

But how to calculate it for the other locations? Anyone can guide me??

Body:
While this can be done in a short function, it would be best to use a library as there are many quirks to overcome. The offset can be determined using the timezone options of toLocaleString or Intl.DateTimeFormat.

However, if the language used for formatting matches the language of the location, it returns the timezone abbreviation instead of the offset. To deal with that, the following function first uses English and if that returns the abbreviation rather than an offset, it uses French. English offsets start with GMT, French offsets start with UTC. Where the offset is +0, they return just "GMT" or "UTC".

It's been tested with all IANA locations listed by wikipedia and seems to work for all of them but it should be tested more widely. Also, there should be feature tests before attempting to run it (i.e. support for Int.DateTimeFormat constructor, formatToParts method and the timeZoneName option).

// Return offset on date for loc in ±H[:mm] format. Minutes only included if not zero
function getTimezoneOffset(date, loc) {
  // Try English to get offset. If get abbreviation, use French
  let offset;
  ['en','fr'].some(lang => {
    // Get parts - can't get just timeZoneName, must get one other part at least
    let parts = new Intl.DateTimeFormat(lang, {
      minute: 'numeric',
      timeZone: loc,
      timeZoneName:'short'
    }).formatToParts(date);
    // Get offset from parts
    let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
    // timeZoneName starting with GMT or UTC is offset - keep and stop looping
    // Otherwise it's an abbreviation, keep looping
    if (/^(GMT|UTC)/.test(tzName[0].value)) {
      offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
      return true;
    }
  });
  // Format offset as ±HH:mm
  // Normalise minus sign as ASCII minus (charCode 45)
  let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
  let [h, m] = offset.substring(1).split(':');
  return sign + h.padStart(2, '0') + ':' + (m || '00');
}

let d = new Date();
console.log('Current offset for following locations:');
['Australia/Yancowinna',
 'Australia/Lord_Howe',
 'Australia/Canberra',
 'Pacific/Honolulu',
 'Europe/London',
 'Canada/Eastern'
].forEach( loc =>
  console.log(loc + ': ' + getTimezoneOffset(d, loc))
);

I don't suggest you use this function, it's really to show how messy getting the offset for a specific location can be.

Note that Australia has a number of offsets and some places observe daylight saving and others don't.


问:
IntentService is deprecated, how do I replace it with JobIntentService?
Following FetchAddressIntentService implementation with IntentService (in kotlin):

```<code>class FetchAddressIntentService  //Constructor of this service
    : IntentService(INTENTTAG) {
    //Receiver where results are forwarded from this service
    protected var resultReceiver: ResultReceiver? = null

    private val TAG by lazy { this::class.java.simpleName }

    //Intent Service handler
    override fun onHandleIntent(intent: Intent?) { //Errormessages
        var errorMessage = ""
        if (intent != null) {
            resultReceiver =
                intent.getParcelableExtra(RECEIVER)
        }
        //Checks if receiver was properly registered
        if (resultReceiver == null) {
            Log.wtf(
                TAG,
                "No reciever received. There is nowhere to send the results !!"
            )
            return
        }
        //Get the location passed to this service through an extra.
        var location: Location? = null
        if (intent != null) {
            location =
                intent.getParcelableExtra(LOCATION_DATA_EXTRA)
        }
        //Make sure the location is really sent
        if (location == null) {
            errorMessage = getString(R.string.gis_error_no_location_data_provided)
            Log.wtf(TAG, errorMessage)
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
            return
        }
        //Setting locale
        val geocoder = Geocoder(this, Locale.ROOT)
        //Address found
        var addresses: List<Address>? = null
        try {
            addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)
            Log.i(TAG,"rec: address = ${addresses[0]}")
        } catch (ioException: IOException) { //Catches network or i/o problems
            errorMessage = getString(R.string.gis_error_service_not_available)
            Log.e(TAG, errorMessage, ioException)
        } catch (illegalArgumentException: IllegalArgumentException) { //Error in latitude or longitude data
            errorMessage = getString(R.string.gis_error_invalid_lat_long_used)
            Log.e(
                TAG,
                errorMessage + ". Latitude = " + location.latitude +
                        ", Longitude = " + location.longitude,
                illegalArgumentException
            )
        }
        //Handles cases where no addresses where found
        if (addresses == null || addresses.isEmpty()) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.gis_error_no_address_found)
                Log.e(TAG, errorMessage)
            }
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
        } else {
            val address = addresses[0]
            //deliverAddressToReceiver(SUCCESS_RESULT, address)
            deliverAddressToReceiver2(SUCCESS_ADDRESS,address)
        }
    }

    private fun deliverAddressToReceiver2(
        resultCode: Int,
        address: Address
    ){
        val bundle = Bundle()
        bundle.putParcelable("address",address)
        resultReceiver?.send(resultCode,bundle)
    }

    private fun deliverResultToReceiver(resultCode: Int, message: String) {
        val bundle = Bundle()
        bundle.putString(RESULT_DATA_KEY, message)
        resultReceiver!!.send(resultCode, bundle)
    }

    companion object {
        private const val INTENTTAG = "FetchAddressIS"
    }
}

</code>```

Do anyone have a suggestion how I can replace IntentService with JobIntentService in a good way ?

IntentService is deprecated in Android-R / Android-11.

I have tried following some posts on this, but no one is directing the correct path how to change the usability of the IntentService call to JobIntentService call in the way this AddressFetchIntentService is using IntentService.

RG

答:
```<code>class FetchAddressIntentService : JobIntentService() {

    // This method is called when service starts instead of onHandleIntent
    override fun onHandleWork(intent: Intent) {
        onHandleIntent(intent)
    }

    // remove override and make onHandleIntent private.
   private fun onHandleIntent(intent: Intent?) {}

    // convenient method for starting the service.
    companion object {
        fun enqueueWork(context: Context, intent: Intent) {
            enqueueWork(context, FetchAddressIntentService::class.java, 1, intent)
        }
    }
}
</code>```

You can start the service as

```<code>    val intent = Intent(this, FetchAddressIntentService::class.java)
    FetchAddressIntentService.enqueueWork(this, intent)
</code>```

Important:

You need to add permissions to manifest.

<uses-permission android:name="android.permission.WAKE_LOCK" /> // needed for pre-oreo devices

also

```<code><service
    android:name=".FetchAddressIntentService"
    android:permission="android.permission.BIND_JOB_SERVICE" // needed for oreo and above
    android:exported="true"/>
</code>```

Read more here

ADDED 2020.06.02 19:20 GMT By Roar Grønmo

I changed my code to:

```<code>class FetchAddressJobIntentService:JobIntentService()
{
    private val TAG by lazy { this::class.java.simpleName }

    protected var resultReceiver: ResultReceiver? = null

    /*
    override fun onHandleWork(intent: Intent) {
        onHandleIntent(intent)
    }*/

    override fun onHandleWork(intent: Intent) { //Errormessages
        var errorMessage = ""

        resultReceiver = intent.getParcelableExtra(RECEIVER)

        //Checks if receiver was properly registered
        if (resultReceiver == null) {
            Log.wtf(
                TAG,
                "No reciever received. There is nowhere to send the results !!"
            )
            return
        }
        //Get the location passed to this service through an extra.
        var location: Location? = null

        location = intent.getParcelableExtra(LOCATION_DATA_EXTRA)

        //Make sure the location is really sent
        if (location == null) {
            errorMessage = getString(R.string.gis_error_no_location_data_provided)
            Log.wtf(TAG, errorMessage)
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
            return
        }
        //Setting locale
        val geocoder = Geocoder(this, Locale.ROOT)
        //Address found
        var addresses: List<Address>? = null
        try {
            addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)
            Log.i(TAG,"rec: address = ${addresses[0]}")
        } catch (ioException: IOException) { //Catches network or i/o problems
            errorMessage = getString(R.string.gis_error_service_not_available)
            Log.e(TAG, errorMessage, ioException)
        } catch (illegalArgumentException: IllegalArgumentException) { //Error in latitude or longitude data
            errorMessage = getString(R.string.gis_error_invalid_lat_long_used)
            Log.e(
                TAG,
                errorMessage + ". Latitude = " + location.latitude +
                        ", Longitude = " + location.longitude,
                illegalArgumentException
            )
        }
        //Handles cases where no addresses where found
        if (addresses == null || addresses.isEmpty()) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.gis_error_no_address_found)
                Log.e(TAG, errorMessage)
            }
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
        } else {
            val address = addresses[0]
            //deliverAddressToReceiver(SUCCESS_RESULT, address)
            deliverAddressToReceiver2(SUCCESS_ADDRESS,address)
        }
    }

    private fun deliverAddressToReceiver2(
        resultCode: Int,
        address: Address
    ){
        val bundle = Bundle()
        bundle.putParcelable("address",address)
        resultReceiver?.send(resultCode,bundle)
    }

    private fun deliverResultToReceiver(resultCode: Int, message: String) {
        val bundle = Bundle()
        bundle.putString(RESULT_DATA_KEY, message)
        resultReceiver!!.send(resultCode, bundle)
    }

    companion object{
        fun enqueueWork(context: Context, intent: Intent){
            enqueueWork(context,FetchAddressJobIntentService::class.java, 1, intent)
        }
    }

}

</code>```

Body:
Following FetchAddressIntentService implementation with IntentService (in kotlin):

class FetchAddressIntentService  //Constructor of this service
    : IntentService(INTENTTAG) {
    //Receiver where results are forwarded from this service
    protected var resultReceiver: ResultReceiver? = null

    private val TAG by lazy { this::class.java.simpleName }

    //Intent Service handler
    override fun onHandleIntent(intent: Intent?) { //Errormessages
        var errorMessage = ""
        if (intent != null) {
            resultReceiver =
                intent.getParcelableExtra(RECEIVER)
        }
        //Checks if receiver was properly registered
        if (resultReceiver == null) {
            Log.wtf(
                TAG,
                "No reciever received. There is nowhere to send the results !!"
            )
            return
        }
        //Get the location passed to this service through an extra.
        var location: Location? = null
        if (intent != null) {
            location =
                intent.getParcelableExtra(LOCATION_DATA_EXTRA)
        }
        //Make sure the location is really sent
        if (location == null) {
            errorMessage = getString(R.string.gis_error_no_location_data_provided)
            Log.wtf(TAG, errorMessage)
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
            return
        }
        //Setting locale
        val geocoder = Geocoder(this, Locale.ROOT)
        //Address found
        var addresses: List<Address>? = null
        try {
            addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)
            Log.i(TAG,"rec: address = ${addresses[0]}")
        } catch (ioException: IOException) { //Catches network or i/o problems
            errorMessage = getString(R.string.gis_error_service_not_available)
            Log.e(TAG, errorMessage, ioException)
        } catch (illegalArgumentException: IllegalArgumentException) { //Error in latitude or longitude data
            errorMessage = getString(R.string.gis_error_invalid_lat_long_used)
            Log.e(
                TAG,
                errorMessage + ". Latitude = " + location.latitude +
                        ", Longitude = " + location.longitude,
                illegalArgumentException
            )
        }
        //Handles cases where no addresses where found
        if (addresses == null || addresses.isEmpty()) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.gis_error_no_address_found)
                Log.e(TAG, errorMessage)
            }
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
        } else {
            val address = addresses[0]
            //deliverAddressToReceiver(SUCCESS_RESULT, address)
            deliverAddressToReceiver2(SUCCESS_ADDRESS,address)
        }
    }

    private fun deliverAddressToReceiver2(
        resultCode: Int,
        address: Address
    ){
        val bundle = Bundle()
        bundle.putParcelable("address",address)
        resultReceiver?.send(resultCode,bundle)
    }

    private fun deliverResultToReceiver(resultCode: Int, message: String) {
        val bundle = Bundle()
        bundle.putString(RESULT_DATA_KEY, message)
        resultReceiver!!.send(resultCode, bundle)
    }

    companion object {
        private const val INTENTTAG = "FetchAddressIS"
    }
}

Do anyone have a suggestion how I can replace IntentService with JobIntentService in a good way ?

IntentService is deprecated in Android-R / Android-11.

I have tried following some posts on this, but no one is directing the correct path how to change the usability of the IntentService call to JobIntentService call in the way this AddressFetchIntentService is using IntentService.

RG

Body:
class FetchAddressIntentService : JobIntentService() {

    // This method is called when service starts instead of onHandleIntent
    override fun onHandleWork(intent: Intent) {
        onHandleIntent(intent)
    }

    // remove override and make onHandleIntent private.
   private fun onHandleIntent(intent: Intent?) {}

    // convenient method for starting the service.
    companion object {
        fun enqueueWork(context: Context, intent: Intent) {
            enqueueWork(context, FetchAddressIntentService::class.java, 1, intent)
        }
    }
}

You can start the service as

    val intent = Intent(this, FetchAddressIntentService::class.java)
    FetchAddressIntentService.enqueueWork(this, intent)

Important:

You need to add permissions to manifest.

<uses-permission android:name="android.permission.WAKE_LOCK" /> // needed for pre-oreo devices

also

<service
    android:name=".FetchAddressIntentService"
    android:permission="android.permission.BIND_JOB_SERVICE" // needed for oreo and above
    android:exported="true"/>

Read more here

ADDED 2020.06.02 19:20 GMT By Roar Grønmo

I changed my code to:

class FetchAddressJobIntentService:JobIntentService()
{
    private val TAG by lazy { this::class.java.simpleName }

    protected var resultReceiver: ResultReceiver? = null

    /*
    override fun onHandleWork(intent: Intent) {
        onHandleIntent(intent)
    }*/

    override fun onHandleWork(intent: Intent) { //Errormessages
        var errorMessage = ""

        resultReceiver = intent.getParcelableExtra(RECEIVER)

        //Checks if receiver was properly registered
        if (resultReceiver == null) {
            Log.wtf(
                TAG,
                "No reciever received. There is nowhere to send the results !!"
            )
            return
        }
        //Get the location passed to this service through an extra.
        var location: Location? = null

        location = intent.getParcelableExtra(LOCATION_DATA_EXTRA)

        //Make sure the location is really sent
        if (location == null) {
            errorMessage = getString(R.string.gis_error_no_location_data_provided)
            Log.wtf(TAG, errorMessage)
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
            return
        }
        //Setting locale
        val geocoder = Geocoder(this, Locale.ROOT)
        //Address found
        var addresses: List<Address>? = null
        try {
            addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1)
            Log.i(TAG,"rec: address = ${addresses[0]}")
        } catch (ioException: IOException) { //Catches network or i/o problems
            errorMessage = getString(R.string.gis_error_service_not_available)
            Log.e(TAG, errorMessage, ioException)
        } catch (illegalArgumentException: IllegalArgumentException) { //Error in latitude or longitude data
            errorMessage = getString(R.string.gis_error_invalid_lat_long_used)
            Log.e(
                TAG,
                errorMessage + ". Latitude = " + location.latitude +
                        ", Longitude = " + location.longitude,
                illegalArgumentException
            )
        }
        //Handles cases where no addresses where found
        if (addresses == null || addresses.isEmpty()) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.gis_error_no_address_found)
                Log.e(TAG, errorMessage)
            }
            deliverResultToReceiver(FAILURE_RESULT, errorMessage)
        } else {
            val address = addresses[0]
            //deliverAddressToReceiver(SUCCESS_RESULT, address)
            deliverAddressToReceiver2(SUCCESS_ADDRESS,address)
        }
    }

    private fun deliverAddressToReceiver2(
        resultCode: Int,
        address: Address
    ){
        val bundle = Bundle()
        bundle.putParcelable("address",address)
        resultReceiver?.send(resultCode,bundle)
    }

    private fun deliverResultToReceiver(resultCode: Int, message: String) {
        val bundle = Bundle()
        bundle.putString(RESULT_DATA_KEY, message)
        resultReceiver!!.send(resultCode, bundle)
    }

    companion object{
        fun enqueueWork(context: Context, intent: Intent){
            enqueueWork(context,FetchAddressJobIntentService::class.java, 1, intent)
        }
    }

}


问:
Iterate through resource string table
I have a string table defined like this in my Win32 app:

```<code>STRINGTABLE
BEGIN
    IDS_STRING101           "myString1"
    IDS_STRING102           "myString2"
    IDS_STRING103           "myString3"
END
</code>```

Since I want all of these strings to be part of an array, is it possible to iterate through this table? Since LoadStringA() requires the macros IDS_STRING101 etc., it seems impossible to iterate through it.

For a practical example, how would I programatically move these strings to an array of strings (char* array in C, std::string array in C++) without using the obvious way of writing a long repetitive code of LoadStringA() calls with the second parameter IDS_STRINGXXX? If possible, I want to be able to add more strings to this table in the future without modifying anything in the code.

答:
There is no API to enumerate through the individual strings of a string table. You would have to load the entire string table resource as a whole into memory and then parse it manually per the documentation.

A simpler solution would be to just call LoadStringA() in a loop, since your string IDs are sequential, eg:

```<code>char myStrings[3][16] = {};
for (int idx = 0; idx < 3; ++idx) {
    LoadStringA(hInstance, IDS_STRING101 + idx, myStrings[idx], 16);
}
</code>```

Title: Iterate through resource string table

Body:
I have a string table defined like this in my Win32 app:

STRINGTABLE
BEGIN
    IDS_STRING101           "myString1"
    IDS_STRING102           "myString2"
    IDS_STRING103           "myString3"
END

Since I want all of these strings to be part of an array, is it possible to iterate through this table? Since LoadStringA() requires the macros IDS_STRING101 etc., it seems impossible to iterate through it.

For a practical example, how would I programatically move these strings to an array of strings (char* array in C, std::string array in C++) without using the obvious way of writing a long repetitive code of LoadStringA() calls with the second parameter IDS_STRINGXXX? If possible, I want to be able to add more strings to this table in the future without modifying anything in the code.

Body:
There is no API to enumerate through the individual strings of a string table. You would have to load the entire string table resource as a whole into memory and then parse it manually per the documentation.

A simpler solution would be to just call LoadStringA() in a loop, since your string IDs are sequential, eg:

char myStrings[3][16] = {};
for (int idx = 0; idx < 3; ++idx) {
    LoadStringA(hInstance, IDS_STRING101 + idx, myStrings[idx], 16);
}


问:
Links render as huge empty boxes in iPhones
I've just had a complaint from a customer who recently purchased an iPhone in place of her old Android phone: the links on the website I built for her appear as huge empty boxes.

This is her website.

Here are some screen shots she sent me that illustrate the problem:

She told me that she's had friends with (various models of) iPhones see if they were getting the same behaviour and they all get the same thing: big empty boxes where the links should be.

I don't have an iPhone myself and don't typically test my sites on iPhones, mostly because I've never heard a single complaint from an iPhone user. Naturally, I'm re-assessing that approach!

I've done some general googling and I've also searched here at Stack Overflow but found nothing specific about issues with links in iPhones. I'm surprised that this doesn't seem to be a well-known problem with known solutions. Or maybe my searching skills aren't what I thought they were.

Can anyone suggest why I'm getting this huge empty boxes and how to make them render as proper links, just like they do in my Windows laptop and Android phone? A solution that works on all current/popular versions of iPhone would be ideal. Feel free to examine my code in your browsers but I don't think I'm doing anything too exotic.

答:
This issue is visible in Safari, not just on an iPhone. It is related to this bit of css:

```<code>  a::before {
    content: url("../images/link-white_16x16.jpg") " ";
  }
</code>```

The image does not exist and the resulting URL takes you to a domain parking page. I guess Safari is just putting in the square because the image does not exist.

Body:
This issue is visible in Safari, not just on an iPhone. It is related to this bit of css:

  a::before {
    content: url("../images/link-white_16x16.jpg") " ";
  }

The image does not exist and the resulting URL takes you to a domain parking page. I guess Safari is just putting in the square because the image does not exist.


问:
Keras difference between generator and sequence
I'm using a deep CNN+LSTM network to perfom a classification on a dataset of 1D signals. I'm using keras 2.2.4 backed by tensorflow 1.12.0. Since I have a large dataset and limited resources, I'm using a generator to load the data into the memory during the training phase. First, I tried this generator:

```<code>def data_generator(batch_size, preproc, type, x, y):
    num_examples = len(x)
    examples = zip(x, y)
    examples = sorted(examples, key = lambda x: x[0].shape[0])
    end = num_examples - batch_size + 1
    batches = [examples[i:i + batch_size] for i in range(0, end, batch_size)]

    random.shuffle(batches)
    while True:
        for batch in batches:
            x, y = zip(*batch)
            yield preproc.process(x, y)
</code>```

Using the above method, I'm able to launch training with a mini-batch size up to 30 samples at a time. However, this kind of method does not guarantee that the network will only train once on each sample per epoch. Considering this comment from Keras's website:

Sequence is a safer way to do multiprocessing. This structure
guarantees that the network will only train once on each sample per
epoch which is not the case with generators.

I've tried another way of loading data using the following class:

```<code>class Data_Gen(Sequence):

def __init__(self, batch_size, preproc, type, x_set, y_set):
    self.x, self.y = np.array(x_set), np.array(y_set)
    self.batch_size = batch_size
    self.indices = np.arange(self.x.shape[0])
    np.random.shuffle(self.indices)
    self.type = type
    self.preproc = preproc

def __len__(self):
    # print(self.type + ' - len : ' + str(int(np.ceil(self.x.shape[0] / self.batch_size))))
    return int(np.ceil(self.x.shape[0] / self.batch_size))

def __getitem__(self, idx):
    inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
    batch_x = self.x[inds]
    batch_y = self.y[inds]
    return self.preproc.process(batch_x, batch_y)

def on_epoch_end(self):
    np.random.shuffle(self.indices)
</code>```

I can confirm that using this method the network is training once on each sample per epoch but this time when I put more than 7 samples in the mini-batch, I got out of memory error:

OP_REQUIRES failed at random_op.cc: 202: Resource exhausted: OOM when
allocating tensor with shape...............

I can confirm that I'm using the same model architecture, configuration, and machine to do this test. I'm wondering why would be a difference between these 2 ways of loading data??

Please don't hesitate to ask for more details in case needed.

Thanks in advance.

EDITED:

Here is the code I'm using to fit the model:

```<code>reduce_lr = keras.callbacks.ReduceLROnPlateau(
            factor=0.1,
            patience=2,
            min_lr=params["learning_rate"])

        checkpointer = keras.callbacks.ModelCheckpoint(
            filepath=str(get_filename_for_saving(save_dir)),
            save_best_only=False)

        batch_size = params.get("batch_size", 32)

        path = './logs/run-{0}'.format(datetime.now().strftime("%b %d %Y %H:%M:%S"))
        tensorboard = keras.callbacks.TensorBoard(log_dir=path, histogram_freq=0,
                                                  write_graph=True, write_images=False)
        if index == 0:
            print(model.summary())
            print("Model memory needed for batchsize {0} : {1} Gb".format(batch_size, get_model_memory_usage(batch_size, model)))

        if params.get("generator", False):
            train_gen = load.data_generator(batch_size, preproc, 'Train', *train)
            dev_gen = load.data_generator(batch_size, preproc, 'Dev', *dev)
            valid_metrics = Metrics(dev_gen, len(dev[0]) // batch_size, batch_size)
            model.fit_generator(
                train_gen,
                steps_per_epoch=len(train[0]) / batch_size + 1 if len(train[0]) % batch_size != 0 else len(train[0]) // batch_size,
                epochs=MAX_EPOCHS,
                validation_data=dev_gen,
                validation_steps=len(dev[0]) / batch_size + 1  if len(dev[0]) % batch_size != 0 else len(dev[0]) // batch_size,
                callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])

            # train_gen = load.Data_Gen(batch_size, preproc, 'Train', *train)
            # dev_gen = load.Data_Gen(batch_size, preproc, 'Dev', *dev)
            # model.fit_generator(
        #     train_gen,
        #     epochs=MAX_EPOCHS,
        #     validation_data=dev_gen,
        #     callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])
</code>```

答:
Those methods are roughly the same. It is correct to subclass
Sequence when your dataset doesn't fit in memory. But you shouldn't
run any preprocessing in any of the class' methods because that will
be reexecuted once per epoch wasting lots of computing resources.

It is probably also easier to shuffle the samples rather than their
indices. Like this:

from random import shuffle

```<code>class DataGen(Sequence):
    def __init__(self, batch_size, preproc, type, x_set, y_set):
        self.samples = list(zip(x, y))
        self.batch_size = batch_size
        shuffle(self.samples)
        self.type = type
        self.preproc = preproc

    def __len__(self):
        return int(np.ceil(len(self.samples) / self.batch_size))

    def __getitem__(self, i):
        batch = self.samples[i * self.batch_size:(i + 1) * self.batch_size]
        return self.preproc.process(*zip(batch))

    def on_epoch_end(self):
        shuffle(self.samples)
</code>```

I think it is impossible to say why you run out of memory without
knowing more about your data. My guess would be that your preproc
function is doing something wrong. You can debug it by running:

```<code>for e in DataGen(batch_size, preproc, *train):
    print(e)
for e in DataGen(batch_size, preproc, *dev):
    print(e)
</code>```

You will most likely run out of memory.

Body:
I'm using a deep CNN+LSTM network to perfom a classification on a dataset of 1D signals. I'm using keras 2.2.4 backed by tensorflow 1.12.0. Since I have a large dataset and limited resources, I'm using a generator to load the data into the memory during the training phase. First, I tried this generator:

def data_generator(batch_size, preproc, type, x, y):
    num_examples = len(x)
    examples = zip(x, y)
    examples = sorted(examples, key = lambda x: x[0].shape[0])
    end = num_examples - batch_size + 1
    batches = [examples[i:i + batch_size] for i in range(0, end, batch_size)]

    random.shuffle(batches)
    while True:
        for batch in batches:
            x, y = zip(*batch)
            yield preproc.process(x, y)

Using the above method, I'm able to launch training with a mini-batch size up to 30 samples at a time. However, this kind of method does not guarantee that the network will only train once on each sample per epoch. Considering this comment from Keras's website:

Sequence is a safer way to do multiprocessing. This structure
guarantees that the network will only train once on each sample per
epoch which is not the case with generators.

I've tried another way of loading data using the following class:

class Data_Gen(Sequence):

def __init__(self, batch_size, preproc, type, x_set, y_set):
    self.x, self.y = np.array(x_set), np.array(y_set)
    self.batch_size = batch_size
    self.indices = np.arange(self.x.shape[0])
    np.random.shuffle(self.indices)
    self.type = type
    self.preproc = preproc

def __len__(self):
    # print(self.type + ' - len : ' + str(int(np.ceil(self.x.shape[0] / self.batch_size))))
    return int(np.ceil(self.x.shape[0] / self.batch_size))

def __getitem__(self, idx):
    inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
    batch_x = self.x[inds]
    batch_y = self.y[inds]
    return self.preproc.process(batch_x, batch_y)

def on_epoch_end(self):
    np.random.shuffle(self.indices)

I can confirm that using this method the network is training once on each sample per epoch but this time when I put more than 7 samples in the mini-batch, I got out of memory error:

OP_REQUIRES failed at random_op.cc: 202: Resource exhausted: OOM when
allocating tensor with shape...............

I can confirm that I'm using the same model architecture, configuration, and machine to do this test. I'm wondering why would be a difference between these 2 ways of loading data??

Please don't hesitate to ask for more details in case needed.

Thanks in advance.

EDITED:

Here is the code I'm using to fit the model:

reduce_lr = keras.callbacks.ReduceLROnPlateau(
            factor=0.1,
            patience=2,
            min_lr=params["learning_rate"])

        checkpointer = keras.callbacks.ModelCheckpoint(
            filepath=str(get_filename_for_saving(save_dir)),
            save_best_only=False)

        batch_size = params.get("batch_size", 32)

        path = './logs/run-{0}'.format(datetime.now().strftime("%b %d %Y %H:%M:%S"))
        tensorboard = keras.callbacks.TensorBoard(log_dir=path, histogram_freq=0,
                                                  write_graph=True, write_images=False)
        if index == 0:
            print(model.summary())
            print("Model memory needed for batchsize {0} : {1} Gb".format(batch_size, get_model_memory_usage(batch_size, model)))

        if params.get("generator", False):
            train_gen = load.data_generator(batch_size, preproc, 'Train', *train)
            dev_gen = load.data_generator(batch_size, preproc, 'Dev', *dev)
            valid_metrics = Metrics(dev_gen, len(dev[0]) // batch_size, batch_size)
            model.fit_generator(
                train_gen,
                steps_per_epoch=len(train[0]) / batch_size + 1 if len(train[0]) % batch_size != 0 else len(train[0]) // batch_size,
                epochs=MAX_EPOCHS,
                validation_data=dev_gen,
                validation_steps=len(dev[0]) / batch_size + 1  if len(dev[0]) % batch_size != 0 else len(dev[0]) // batch_size,
                callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])

            # train_gen = load.Data_Gen(batch_size, preproc, 'Train', *train)
            # dev_gen = load.Data_Gen(batch_size, preproc, 'Dev', *dev)
            # model.fit_generator(
        #     train_gen,
        #     epochs=MAX_EPOCHS,
        #     validation_data=dev_gen,
        #     callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])

Body:
Those methods are roughly the same. It is correct to subclass
Sequence when your dataset doesn't fit in memory. But you shouldn't
run any preprocessing in any of the class' methods because that will
be reexecuted once per epoch wasting lots of computing resources.

It is probably also easier to shuffle the samples rather than their
indices. Like this:

from random import shuffle

class DataGen(Sequence):
    def __init__(self, batch_size, preproc, type, x_set, y_set):
        self.samples = list(zip(x, y))
        self.batch_size = batch_size
        shuffle(self.samples)
        self.type = type
        self.preproc = preproc

    def __len__(self):
        return int(np.ceil(len(self.samples) / self.batch_size))

    def __getitem__(self, i):
        batch = self.samples[i * self.batch_size:(i + 1) * self.batch_size]
        return self.preproc.process(*zip(batch))

    def on_epoch_end(self):
        shuffle(self.samples)

I think it is impossible to say why you run out of memory without
knowing more about your data. My guess would be that your preproc
function is doing something wrong. You can debug it by running:

for e in DataGen(batch_size, preproc, *train):
    print(e)
for e in DataGen(batch_size, preproc, *dev):
    print(e)

You will most likely run out of memory.


问:
React Native Stack & Drawer Navigation v5
I am new to react native and I am trying to create a menu, that would open on click and slide out, and on click outside the menu would slide back in.

It has been very hard for me to find any decent tutorial/explanation about how to have both stack and drawer navigation available for a page and functioning.

currently, my App.js looks like this:

```<code>    import 'react-native-gesture-handler';
import React from 'react';
import Home from './app/screens/Home/Home';
import ArtistListing from './app/screens/ArtistListing/ArtistListing';
import ArtPeriods from './app/screens/ArtPeriods/ArtPeriods';
import Login from './app/screens/Login/Login';
import Quiz from './app/screens/Quiz/Quiz';
import GuessWhen from './app/screens/GuessWhen/GuessWhen';
import { NavigationContainer, useLinking } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {Auth, Hub} from 'aws-amplify';
import {SetCurrentUser} from './src/model/User';
import LearnMore from './app/screens/LearnMore/LearnMore';
import {CreateAllArtistsWithDependencies} from './src/model/Artists';
import ExploreTimePeriod from './app/screens/ExploreTimePeriod/ExploreTimePeriod';
import ExploreArtist from './app/screens/ExploreArtist/ExploreArtist';
import PhotoGalleryScreen from './app/screens/PhotoGalleryScreen/PhotoGalleryScreen';
import ExploreTimePeriods from './app/screens/ExploreTimePeriods/ExploreTimePeriods';
import ExploreArtists from './app/screens/ExploreArtists/ExploreArtists';
import QuizSummary from './app/screens/QuizSummary/QuizSummary';
import ContactUs from './app/screens/ContactUs/ContactUs';
import Profile from './app/screens/Profile/Profile';
import Favorites from './app/screens/Favorites/Favorites';
const Stack = createStackNavigator();
const App = () => {
  return (
      <NavigationContainer>
          <Stack.Navigator initialRouteName="Login">
              <Stack.Screen name="Home" component={Home} options={{headerShown:false}} />
              <Stack.Screen name="Login" component={Login} options={{headerShown:false}} />
              <Stack.Screen name="ArtistListing" component={ArtistListing} options={{headerShown:false}}/>
              <Stack.Screen name="ArtPeriods" component={ArtPeriods} options={{headerShown:false}}/>
              <Stack.Screen name="GuessWhen" component={GuessWhen} options={{headerShown:false}}/>
              <Stack.Screen name="Quiz" component={Quiz} options={{headerShown:false}}/>
              <Stack.Screen name="LearnMore" component={LearnMore} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreTimePeriod" component={ExploreTimePeriod} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreTimePeriods" component={ExploreTimePeriods} options={{headerShown:false}}/>
              <Stack.Screen name="PhotoGalleryScreen" component={PhotoGalleryScreen} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreArtist" component={ExploreArtist} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreArtists" component={ExploreArtists} options={{headerShown:false}}/>
              <Stack.Screen name="QuizSummary" component={QuizSummary} options={{headerShown:false}}/>
              <Stack.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
              <Stack.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
              <Stack.Screen name="Favorites" component={Favorites} options={{headerShown:false}}/>
          </Stack.Navigator>
      </NavigationContainer>
  );
};

export default App;
</code>```

I would like to have a drawer navigator as well with the pages listed below. I know I might need a switch navigator, but everything is super hard to find for version 5. I bet I am not the only one searching for a clear answer on how to do this.

```<code>          <Drawer.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
      <Drawer.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
      <Drawer.Screen name="Favorites" component={Favorites} options={{headerShown:false}}/>
</code>```

If you have an idea about this, please give me a suggestion.

答:
Let'say your stack after login like

```<code>const Stack = createStackNavigator();
const App = () => {
return (
  <NavigationContainer>
  <Stack.Navigator initialRouteName="Home">
  <Stack.Screen name="Home" component={Home} options={{headerShown:false}} />
  <Stack.Screen name="ArtistListing" component={ArtistListing} options={{headerShown:false}}/>
  </Stack.Navigator>
  </NavigationContainer>
  );
  };
</code>```

Let's say this is your drawer navigation.

```<code>const Drawer = createDrawerNavigator();
function drawers(){
<Drawer.Screen name="Home" component={App} options={{headerShown:false}}/>
 <Drawer.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
  <Drawer.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
   }
</code>```

Now Drawer will be everywhere by default. And HomeScreen will be your first screen by default.

Now the part of AuthFlow.

```<code>const AuthFlowStack = createStackNavigator();
function AuthFlow(){
<AuthFlow.Screen name='LogIn' component={LogIn} />
}
</code>```

Main Stack Flow(which will act as SwitchNavigator)

```<code>const Main = createStackNavigator();
function MainFlow(){
{this.state.isLogin ? <Drawer/> :<AuthFlow/>}
}
export default {MainFlow};
</code>```

And set the value of isLogin to true when you login and send as parameter and set it false when logout.

Body:
I am new to react native and I am trying to create a menu, that would open on click and slide out, and on click outside the menu would slide back in.

It has been very hard for me to find any decent tutorial/explanation about how to have both stack and drawer navigation available for a page and functioning.

currently, my App.js looks like this:

    import 'react-native-gesture-handler';
import React from 'react';
import Home from './app/screens/Home/Home';
import ArtistListing from './app/screens/ArtistListing/ArtistListing';
import ArtPeriods from './app/screens/ArtPeriods/ArtPeriods';
import Login from './app/screens/Login/Login';
import Quiz from './app/screens/Quiz/Quiz';
import GuessWhen from './app/screens/GuessWhen/GuessWhen';
import { NavigationContainer, useLinking } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {Auth, Hub} from 'aws-amplify';
import {SetCurrentUser} from './src/model/User';
import LearnMore from './app/screens/LearnMore/LearnMore';
import {CreateAllArtistsWithDependencies} from './src/model/Artists';
import ExploreTimePeriod from './app/screens/ExploreTimePeriod/ExploreTimePeriod';
import ExploreArtist from './app/screens/ExploreArtist/ExploreArtist';
import PhotoGalleryScreen from './app/screens/PhotoGalleryScreen/PhotoGalleryScreen';
import ExploreTimePeriods from './app/screens/ExploreTimePeriods/ExploreTimePeriods';
import ExploreArtists from './app/screens/ExploreArtists/ExploreArtists';
import QuizSummary from './app/screens/QuizSummary/QuizSummary';
import ContactUs from './app/screens/ContactUs/ContactUs';
import Profile from './app/screens/Profile/Profile';
import Favorites from './app/screens/Favorites/Favorites';
const Stack = createStackNavigator();
const App = () => {
  return (
      <NavigationContainer>
          <Stack.Navigator initialRouteName="Login">
              <Stack.Screen name="Home" component={Home} options={{headerShown:false}} />
              <Stack.Screen name="Login" component={Login} options={{headerShown:false}} />
              <Stack.Screen name="ArtistListing" component={ArtistListing} options={{headerShown:false}}/>
              <Stack.Screen name="ArtPeriods" component={ArtPeriods} options={{headerShown:false}}/>
              <Stack.Screen name="GuessWhen" component={GuessWhen} options={{headerShown:false}}/>
              <Stack.Screen name="Quiz" component={Quiz} options={{headerShown:false}}/>
              <Stack.Screen name="LearnMore" component={LearnMore} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreTimePeriod" component={ExploreTimePeriod} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreTimePeriods" component={ExploreTimePeriods} options={{headerShown:false}}/>
              <Stack.Screen name="PhotoGalleryScreen" component={PhotoGalleryScreen} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreArtist" component={ExploreArtist} options={{headerShown:false}}/>
              <Stack.Screen name="ExploreArtists" component={ExploreArtists} options={{headerShown:false}}/>
              <Stack.Screen name="QuizSummary" component={QuizSummary} options={{headerShown:false}}/>
              <Stack.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
              <Stack.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
              <Stack.Screen name="Favorites" component={Favorites} options={{headerShown:false}}/>
          </Stack.Navigator>
      </NavigationContainer>
  );
};

export default App;

I would like to have a drawer navigator as well with the pages listed below. I know I might need a switch navigator, but everything is super hard to find for version 5. I bet I am not the only one searching for a clear answer on how to do this.

          <Drawer.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
      <Drawer.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
      <Drawer.Screen name="Favorites" component={Favorites} options={{headerShown:false}}/>

If you have an idea about this, please give me a suggestion.

Body:
Let'say your stack after login like

const Stack = createStackNavigator();
const App = () => {
return (
  <NavigationContainer>
  <Stack.Navigator initialRouteName="Home">
  <Stack.Screen name="Home" component={Home} options={{headerShown:false}} />
  <Stack.Screen name="ArtistListing" component={ArtistListing} options={{headerShown:false}}/>
  </Stack.Navigator>
  </NavigationContainer>
  );
  };

Let's say this is your drawer navigation.

const Drawer = createDrawerNavigator();
function drawers(){
<Drawer.Screen name="Home" component={App} options={{headerShown:false}}/>
 <Drawer.Screen name="ContactUs" component={ContactUs} options={{headerShown:false}}/>
  <Drawer.Screen name="Profile" component={Profile} options={{headerShown:false}}/>
   }

Now Drawer will be everywhere by default. And HomeScreen will be your first screen by default.

Now the part of AuthFlow.

const AuthFlowStack = createStackNavigator();
function AuthFlow(){
<AuthFlow.Screen name='LogIn' component={LogIn} />
}

Main Stack Flow(which will act as SwitchNavigator)

const Main = createStackNavigator();
function MainFlow(){
{this.state.isLogin ? <Drawer/> :<AuthFlow/>}
}
export default {MainFlow};

And set the value of isLogin to true when you login and send as parameter and set it false when logout.


问:
LinkedIn share post URL changed and gives error message: 'It's not you it's us, give it another try please.'
I have a wordpress website https:www.x-equo.nl and we have single job which we want to share with linkedin. If we click ont he share button, we get the error message:

'It's not you it's us, give it another try please.'.

When I have a look at the URL created:

https://www.linkedin.com/cws/share/?url=https%3A%2F%2Fwww.x-equo.nl%2Fvacature%2Ffinancieel-administratief-medewerker-6%2F

I see that the "css/share" part in the URL is different than another website we have in which the sharing does work.

What is going wrong here? How can we change the share link URL so linkedin will accept it?

Hope anyone can help us.

Thank you I advance

We tried reading a lot of other helpdesk but non of them seem logic.

答:
The following URL format works perfectly for me...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.x-equo.nl%2Fvacature%2Ffinancieel-administratief-medewerker-6%2F
</code>```

And the URL you have will simply redirect to the URL above.  You have correctly encoded the URL, so, that's not the problem.  But, yes, it definitely works:

Source: Official LinkedIn Shareable Documentation.

Not sure if your page is loading correctly?  Test it out by inserting your URL into the LinkedIn Post Inspector.

Body:
The following URL format works perfectly for me...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.x-equo.nl%2Fvacature%2Ffinancieel-administratief-medewerker-6%2F

And the URL you have will simply redirect to the URL above.  You have correctly encoded the URL, so, that's not the problem.  But, yes, it definitely works:

Source: Official LinkedIn Shareable Documentation.

Not sure if your page is loading correctly?  Test it out by inserting your URL into the LinkedIn Post Inspector.


问:
KeyError when trying to access a value in Tweepy response
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

```<code># Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)
</code>```

I've copied an extract of "image" at the bottom of the post

Then when I call:

```<code>image['id']
</code>```

I get: 892420643555336193, which is great :-)

But when I call:

```<code>image['media']
</code>```

I get the following error

```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'
</code>```

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

```<code># The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},
</code>```

答:
Looks like its inside entities

```<code>image['entities']['media']
</code>```

Body:
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

# Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)

I've copied an extract of "image" at the bottom of the post

Then when I call:

image['id']

I get: 892420643555336193, which is great :-)

But when I call:

image['media']

I get the following error

KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

# The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},

Body:
Looks like its inside entities

image['entities']['media']


问:
Bug Tracker Architecture
I am creating a Bug Tracker application (toy one) with DDD in mind. I have a BugRepository with methods like Add / Delete / Save and a user Repository having the same kind of methods (Actually both derive from IRepository). Now Bug has a Property called "Assigned To" which is a column in DB where the ID of the user is stored.

Now I need a method called "FindAssignee" or rather I want to know who the bug is assigned to. Where do i put that?

I was thinking that I could say --> In BugRepository add a method called "FindAssignee". But that would return a "USER" object. Is that OK? Aren't repositories for an aggregate root (Bug this case) supposed to return ONLY their entities (Bug again) ?

答:
Is that OK?

Yes.

Aren't repositories for an aggregate root (Bug this case) supposed to return ONLY their entities (Bug again) ?

Yes.

But your query isn't to a aggregate root.

Your query is against a specific Bug which has one or more Assignees.

Title: Bug Tracker Architecture


问:
In numbers with range of values, how to move the decimal point left until a single digit integer remains in Python
I'd like to take a number like: 12345678 and turn it into 1.2345678, leaving only a single digit integer and whatever decimal.

Multiplying 12345678 by 0.0000001 works for the above example, but not if the number is 1234. The numbers change so a static multiplier will not work.

Is there a method available that would help? Bonus if it can be done within a pandas dataframe.

答:
I can think on two ways.

```<code>A= Str (xxxxxxx)

B = float (A[0]+”.”+A[1:len(A)])
</code>```

Another way:

```<code>A=A / pow(10,len(str(A)-1)
</code>```

Body:
I can think on two ways.

A= Str (xxxxxxx)

B = float (A[0]+”.”+A[1:len(A)])

Another way:

A=A / pow(10,len(str(A)-1)


问:
Robot class- KeyEvent fails to upload document to the windows folder at KeyEvent.VK_V
I am working a specific scenario to upload a doc using selenium. After repeated failure I thought myself to debug the code. Here is my code and the error.

```<code>public void uploadFile(String imagePath) {
        StringSelection stringSelection = new StringSelection(imagePath);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        Robot robot = null;

        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        robot.delay(250);

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
</code>```

While debugging, I found the below result.

```<code>robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
</code>```

```<code>The below happens where the selected path gets printed in the code right next to Vk.Control
</code>```

```<code>  C:\SAF\GIT\TestImage\Tests.docx       robot.keyPress(KeyEvent.VK_CONTROL);
</code>```

```<code>        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

</code>```

Kindly let me know if there are any work around?

答:
Keep window maximized ,

```<code>  before robot.delay(250);
  driver.manage().window().maximize();
</code>```

if needed add a bit delay after keyevents ,as below

```<code>    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.delay(50); // it will slow down keyevent renderence and synchronize.
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
</code>```

Body:
I am working a specific scenario to upload a doc using selenium. After repeated failure I thought myself to debug the code. Here is my code and the error.

public void uploadFile(String imagePath) {
        StringSelection stringSelection = new StringSelection(imagePath);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        Robot robot = null;

        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        robot.delay(250);

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

While debugging, I found the below result.

robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

The below happens where the selected path gets printed in the code right next to Vk.Control

  C:\SAF\GIT\TestImage\Tests.docx       robot.keyPress(KeyEvent.VK_CONTROL);

        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

Kindly let me know if there are any work around?

Body:
Keep window maximized ,

  before robot.delay(250);
  driver.manage().window().maximize();

if needed add a bit delay after keyevents ,as below

    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.delay(50); // it will slow down keyevent renderence and synchronize.
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);


问:
problem with declaring variable in php?
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

```<code>for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}
</code>```

but its not working ?

is there any alternative solution for this

答:
This may be helpful to you:</p>

```<code>$srange0;
$srange1;
$srange2;
for($i=0;$i<=3;$i++) {
       $range = "srange".$i;
       $$range = $i;
}
echo $srange2."<br />";
exit;
</code>```

Title: problem with declaring variable in php?

Body:
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}

but its not working ?

is there any alternative solution for this

Body:
This may be helpful to you:

$srange0;
$srange1;
$srange2;
for($i=0;$i<=3;$i++) {
       $range = "srange".$i;
       $$range = $i;
}
echo $srange2."<br />";
exit;


答:
I get the following error

Right, because media isn't one of the keys of the dict loaded from the JSON; it's a key of the sub-dict under the entities key. So you need image['entities']['media']. Similarly to look into that dict and get the media_url: image['entities']['media']['media_url'].

It's just a dict. It doesn't matter that it came from a JSON file. The data is nested, so you access it one step at a time.

Title: KeyError when trying to access a value in Tweepy response