问:
Connect to oracle server using CDatabase from MFC
I try to connect to a oracle database, where server is installed on my laptop and run on port 1521 and the name is "orcl". First, I connect using Java and jdbc using this code:

```<code>private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USERNAME = "cosmin";
private static final String PASSWORD = "123456";
private static Connection conn;
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
</code>```

And now I try to connect using MFC and using CDatabase class but I can't connect.

```<code>    CDatabase db;
    TRY{
        db.OpenEx(L"ODBC;DRIVER={MICROSOFT ODBC FOR ORACLE};DSN=orcl;SERVER=@localhost:1521:orcl;UID=cosmin; PWD=123456");

        db.Close();
    } CATCH(CDBException, e) {
        AfxMessageBox(L"Database error: " + e->m_strError);
    }
</code>```

I receive the next error: Datasource name not found and no default driver specified. How can I resolve this problem?

Thanks!

答:
If you are going to us a data source name. Here is how to get to the tool.

And if you want to add the name in your program:

```<code>BOOL ret= SQLConfigDataSource(
    NULL,
    ODBC_ADD_DSN,
    (LPSTR) "Microsoft Access Driver (*.mdb)\0",
    (LPSTR) "DSN=MS Access Database\0"
    "Description=MS Access Database\0"
    );
if( ! ret )
{
    AfxMessageBox( _T("The 'Data Source Name' failed to install\nPlease call Tech Support\n800-123-4567") );
    return FALSE;
}
</code>```

On the other hand, (I have not tried it), you should be able to use a DSN-less connection string. But that means you can't DSN=orcl; as there is no such DSN.

Body:
I try to connect to a oracle database, where server is installed on my laptop and run on port 1521 and the name is "orcl". First, I connect using Java and jdbc using this code:

private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USERNAME = "cosmin";
private static final String PASSWORD = "123456";
private static Connection conn;
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

And now I try to connect using MFC and using CDatabase class but I can't connect.

    CDatabase db;
    TRY{
        db.OpenEx(L"ODBC;DRIVER={MICROSOFT ODBC FOR ORACLE};DSN=orcl;SERVER=@localhost:1521:orcl;UID=cosmin; PWD=123456");

        db.Close();
    } CATCH(CDBException, e) {
        AfxMessageBox(L"Database error: " + e->m_strError);
    }

I receive the next error: Datasource name not found and no default driver specified. How can I resolve this problem?

Thanks!

Body:
If you are going to us a data source name. Here is how to get to the tool.

And if you want to add the name in your program:

BOOL ret= SQLConfigDataSource(
    NULL,
    ODBC_ADD_DSN,
    (LPSTR) "Microsoft Access Driver (*.mdb)\0",
    (LPSTR) "DSN=MS Access Database\0"
    "Description=MS Access Database\0"
    );
if( ! ret )
{
    AfxMessageBox( _T("The 'Data Source Name' failed to install\nPlease call Tech Support\n800-123-4567") );
    return FALSE;
}

On the other hand, (I have not tried it), you should be able to use a DSN-less connection string. But that means you can't DSN=orcl; as there is no such DSN.


来源: stackexchange

问:
How can I add support for .NET web application virtual paths in gulp?
I am using gulp with a .NET Core web application and I have a Less file that contains paths to physical files like so:

```<code>background: @colour-background-darkest-base url(/content/slides/experience.jpg) no-repeat center top fixed;
</code>```

But when I run the web application in a virtual path the image can't be found. How can I provide support for virtual paths so that I can do the following:

```<code>background: @colour-background-darkest-base url(~/content/slides/experience.jpg) no-repeat center top fixed;
</code>```

(Note the ~ at the start of the path)

答:
This question has been answered in the following SO question:
Use Bower package version numbers in Razor views for CDN support

In a nutshell, combine gulp with Bundling and Minification with ASP.Net MVC

ContentLicense: CC BY-SA 3.0

Body:
I am using gulp with a .NET Core web application and I have a Less file that contains paths to physical files like so:

background: @colour-background-darkest-base url(/content/slides/experience.jpg) no-repeat center top fixed;

But when I run the web application in a virtual path the image can't be found. How can I provide support for virtual paths so that I can do the following:

background: @colour-background-darkest-base url(~/content/slides/experience.jpg) no-repeat center top fixed;

(Note the ~ at the start of the path)


问:
How to increase the size of the downloaded image from canvas with fabricjs?
I'm using the following to download my fabricjs canvas and it works great but I wondered how I might be able to make the downloaded image larger so that it's clearer when I print it? Thanks for any help in advance.

```<code>// Download as png
function download(url, name) {
  // make the link. set the href and download. emulate dom click
  $('<a>').attr({
    href: url,
    download: name
  })[0].click();
}

function downloadFabric(canvas, name) {
  //  convert the canvas to a data url and download it.
  download(canvas.toDataURL(), name + '.png');
}
</code>```

```<code><button onclick="downloadFabric(canvas,'save');">Save</button>
</code>```

答: This wound up being similar to this post. From there I was able to work that adding {multiplier: 4} to canvas.toDataURL(); worked splendidly.

Body:
I'm using the following to download my fabricjs canvas and it works great but I wondered how I might be able to make the downloaded image larger so that it's clearer when I print it? Thanks for any help in advance.

// Download as png
function download(url, name) {
  // make the link. set the href and download. emulate dom click
  $('').attr({
    href: url,
    download: name
  })[0].click();
}

function downloadFabric(canvas, name) {
  //  convert the canvas to a data url and download it.
  download(canvas.toDataURL(), name + '.png');
}

<button onclick="downloadFabric(canvas,'save');">Save</button>


问:
Rails 3 app will not match a route even though rake routes shows it
Here is a portion of my routes file:

resource :vendor do post 'modify_account' end

Running rake routes will generate the following line

```<code>           modify_account_vendor POST   /vendor/modify_account(.:format)                               {:action=>"modify_account", :controller=>"vendors"}
                          vendor POST   /vendor(.:format)                                              {:action=>"create", :controller=>"vendors"}
                      new_vendor GET    /vendor/new(.:format)                                          {:action=>"new", :controller=>"vendors"}
                     edit_vendor GET    /vendor/edit(.:format)                                         {:action=>"edit", :controller=>"vendors"}
                                 GET    /vendor(.:format)                                              {:action=>"show", :controller=>"vendors"}
                                 PUT    /vendor(.:format)                                              {:action=>"update", :controller=>"vendors"}
                                 DELETE /vendor(.:format)                                              {:action=>"destroy", :controller=>"vendors"}
                                        /vendor(.:format)                                              {:action=>"account", :controller=>"vendors"}
</code>```

I can load the form and verify the URL is correct in the form's action, but when I submit, the app throws an error:

No route matches "/vendor/modify_account"

Any suggestions as to what I can do to troubleshoot? Firebug verifies that the error page is of type POST.

答:
I had a simular issue with a singleton resource, check that you are passing in the url to the form_tag, we use simple_form and have the following</p>

```<code><%= simple_form_for @enterprise_account, :url => enterprise_account_path do |f| -%>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is a portion of my routes file:

resource :vendor do post 'modify_account' end

Running rake routes will generate the following line

           modify_account_vendor POST   /vendor/modify_account(.:format)                               {:action=>"modify_account", :controller=>"vendors"}
                          vendor POST   /vendor(.:format)                                              {:action=>"create", :controller=>"vendors"}
                      new_vendor GET    /vendor/new(.:format)                                          {:action=>"new", :controller=>"vendors"}
                     edit_vendor GET    /vendor/edit(.:format)                                         {:action=>"edit", :controller=>"vendors"}
                                 GET    /vendor(.:format)                                              {:action=>"show", :controller=>"vendors"}
                                 PUT    /vendor(.:format)                                              {:action=>"update", :controller=>"vendors"}
                                 DELETE /vendor(.:format)                                              {:action=>"destroy", :controller=>"vendors"}
                                        /vendor(.:format)                                              {:action=>"account", :controller=>"vendors"}

I can load the form and verify the URL is correct in the form's action, but when I submit, the app throws an error:

No route matches "/vendor/modify_account"

Any suggestions as to what I can do to troubleshoot? Firebug verifies that the error page is of type POST.

Body:
I had a simular issue with a singleton resource, check that you are passing in the url to the form_tag, we use simple_form and have the following

<%= simple_form_for @enterprise_account, :url => enterprise_account_path do |f| -%>


问:
Setting Range Results in Application Defined or Object Defined Error, two methods? VBA
When setting a range, and the active worksheet is not = to the reference I get an

Application Defined Object Defined Error

using this method below:

```<code>Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3))
</code>```

But why does it work when I use this method:

```<code>Set Rng = Range(Worksheets("Worksheet2").Cells(2,2),Worksheets("Worksheet2").Cells(2,3))
</code>```

Just trying to understand why exactly the last method works, but the first does not.

答:
You are breaking the range, as far as both Cells and Range should be refered to the same Parent. If you do not refer any of them, their parent is the activesheet:

Thus either refer the parent explicitly for both of them:

```<code>With Worksheets("worksheets2")
    Set Rng = .Range(.Cells(2, 2), .Cells(2, 3))
End With
</code>```

or leave it empty for both of them (thus it would be the ActiveSheet):

```<code>Set Rng = Range(Cells(2,2),Cells(2,3))
</code>```

To make this work Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3)), you have to make sure that Worksheets2 is your activesheet.

Body:
When setting a range, and the active worksheet is not = to the reference I get an

Application Defined Object Defined Error

using this method below:

Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3))

But why does it work when I use this method:

Set Rng = Range(Worksheets("Worksheet2").Cells(2,2),Worksheets("Worksheet2").Cells(2,3))

Just trying to understand why exactly the last method works, but the first does not.

Body:
You are breaking the range, as far as both Cells and Range should be refered to the same Parent. If you do not refer any of them, their parent is the activesheet:

Thus either refer the parent explicitly for both of them:

With Worksheets("worksheets2")
    Set Rng = .Range(.Cells(2, 2), .Cells(2, 3))
End With

or leave it empty for both of them (thus it would be the ActiveSheet):

Set Rng = Range(Cells(2,2),Cells(2,3))

To make this work Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3)), you have to make sure that Worksheets2 is your activesheet.


问:
Nested object destructuring: Duplicate declaration "fontSize"
I'm using ShevyJS with styled-components. The docs show an example that uses nested object deconstruction ...

```<code>const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  }
} = shevy
</code>```

and my styles ...

```<code>const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;
</code>```

It works fine. But, if I try to do the following I get an error Module build failed: Duplicate declaration "fontSize" ...

```<code>const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  },
  p: {
    fontSize
  }
} = shevy

const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${fontSize};
`;
</code>```

I've never worked with nested objects in this way before. I assumed the fontSize within the p would be scoped to p and the h1 to h1 so that styled.p knows which fontSize to use. It would certainly make sense but I highly doubt that's how it works.

Any ideas?

答:
Your destructuring statement is basically equivalent to

```<code>const fontSize = shevy.h1.fontSize,
      fontSize = shevy.p.fontSize;
</code>```

which is obviously invalid. If you want to destructure them, you need to assign them to different variables.

I assumed the fontSize within the p would be scoped to p and the h1 to h1 so that styled.p knows which fontSize to use.

No, there is no such scoping, and it doesn't have anything to do with nested objects. All the variables in the destructuring target are declared in the same scope - and they are just normal const variables, nothing with a namespace attached or so.

Remember that styled.p is just a template tag, it does not know anything about variable names or could be able to affect them in any way. The expressions in the interpolation sections of the template are evaluated as usual, before their result values are passed into the tag function.

If you want to do some namespacing, you need to do it yourself explicitly:

```<code>const {
  baseSpacing: bs,
  h1: {
    fontSize: h1Fontsize,
//          ^^^^^^^^^^^^
    lineHeight,
    marginBottom
  },
  p: {
    fontSize: pFontsize
//          ^^^^^^^^^^^
  }
} = new Shevy();

const Heading = styled.h1`
    font-size: ${h1FontSize};
/*               ^^ */
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${pFontSize};
/*               ^ */
`;
</code>```

Body:
I'm using ShevyJS with styled-components. The docs show an example that uses nested object deconstruction ...

const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  }
} = shevy

and my styles ...

const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

It works fine. But, if I try to do the following I get an error Module build failed: Duplicate declaration "fontSize" ...

const shevy = new Shevy()
const {
  baseSpacing: bs,
  h1: {
    fontSize,
    lineHeight,
    marginBottom
  },
  p: {
    fontSize
  }
} = shevy

const Heading = styled.h1`
    font-size: ${fontSize};
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${fontSize};
`;

I've never worked with nested objects in this way before. I assumed the fontSize within the p would be scoped to p and the h1 to h1 so that styled.p knows which fontSize to use. It would certainly make sense but I highly doubt that's how it works.

Any ideas?

Body:
Your destructuring statement is basically equivalent to

const fontSize = shevy.h1.fontSize,
      fontSize = shevy.p.fontSize;

which is obviously invalid. If you want to destructure them, you need to assign them to different variables.

I assumed the fontSize within the p would be scoped to p and the h1 to h1 so that styled.p knows which fontSize to use.

No, there is no such scoping, and it doesn't have anything to do with nested objects. All the variables in the destructuring target are declared in the same scope - and they are just normal const variables, nothing with a namespace attached or so.

Remember that styled.p is just a template tag, it does not know anything about variable names or could be able to affect them in any way. The expressions in the interpolation sections of the template are evaluated as usual, before their result values are passed into the tag function.

If you want to do some namespacing, you need to do it yourself explicitly:

const {
  baseSpacing: bs,
  h1: {
    fontSize: h1Fontsize,
//          ^^^^^^^^^^^^
    lineHeight,
    marginBottom
  },
  p: {
    fontSize: pFontsize
//          ^^^^^^^^^^^
  }
} = new Shevy();

const Heading = styled.h1`
    font-size: ${h1FontSize};
/*               ^^ */
    line-height: ${lineHeight};
    margin-bottom: ${marginBottom};
`;

const Byline = styled.p`
    font-size: ${pFontSize};
/*               ^ */
`;


问:
How do i bind two radiobuttons to a data model?
I have an account update form. In that form I can set whether the account is enabled or disabled. When the update form gets loaded I would like the radiobutton group to be checked according to the database value (enabled = true or false) retrieved from the database for that particular account. I have tried to accomplish it via this code:

```<code><label>Status</label>
<div class = "control-group">
<div class="controls radio-group" id="status" name = "status">
<label class="radio-inline">
  <input type="radio" [checked] = "account.enabled === true" name="optradio1" formControlName="status" [value] = "true">Actief
</label>
<label class="radio-inline">
  <input type="radio" [checked] = "account.enabled === false" name="optradio1" formControlName="status" [value] = "false">Inactief
</label>
</div>
</div>
</code>```

But it doesen't automatically check the radiobutton corresponding to the last saved radiobutton value.

Does anyone know how I can accomplish this?

答:
What you need is an event listener take a look at this stack overflow question that uses a loop to attach listeners to multiple radio buttons.

The listener will listen for a change of value to the button and will run a function when that occurs.

In that function set the radio button's new value to whatever you wish.

Body:
I have an account update form. In that form I can set whether the account is enabled or disabled. When the update form gets loaded I would like the radiobutton group to be checked according to the database value (enabled = true or false) retrieved from the database for that particular account. I have tried to accomplish it via this code:

Status

  <input type="radio" [checked] = "account.enabled === true" name="optradio1" formControlName="status" [value] = "true">Actief

  <input type="radio" [checked] = "account.enabled === false" name="optradio1" formControlName="status" [value] = "false">Inactief

But it doesen't automatically check the radiobutton corresponding to the last saved radiobutton value.

Does anyone know how I can accomplish this?


问:
Is it possible to use the instanceof operator in a switch statement?
I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

```<code>if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():
</code>```

How would it be implemented using switch...case?

答:
I personally like the following Java 1.8 code:

```<code>    mySwitch("YY")
            .myCase("AA", (o) -> {
                System.out.println(o+"aa");
            })
            .myCase("BB", (o) -> {
                System.out.println(o+"bb");
            })
            .myCase("YY", (o) -> {
                System.out.println(o+"yy");
            })
            .myCase("ZZ", (o) -> {
                System.out.println(o+"zz");
            });
</code>```

Will output:

```<code>YYyy
</code>```

The sample code uses Strings but you can use any object type, including Class. e.g. .myCase(this.getClass(), (o) -> ...

Needs the following snippet:

```<code>public Case mySwitch(Object reference) {
    return new Case(reference);
}

public class Case {

    private Object reference;

    public Case(Object reference) {
        this.reference = reference;
    }

    public Case myCase(Object b, OnMatchDo task) {
        if (reference.equals(b)) {
            task.task(reference);
        }
        return this;
    }
}

public interface OnMatchDo {
    public void task(Object o);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():

How would it be implemented using switch...case?

Body:
I personally like the following Java 1.8 code:

    mySwitch("YY")
            .myCase("AA", (o) -> {
                System.out.println(o+"aa");
            })
            .myCase("BB", (o) -> {
                System.out.println(o+"bb");
            })
            .myCase("YY", (o) -> {
                System.out.println(o+"yy");
            })
            .myCase("ZZ", (o) -> {
                System.out.println(o+"zz");
            });

Will output:

YYyy

The sample code uses Strings but you can use any object type, including Class. e.g. .myCase(this.getClass(), (o) -> ...

Needs the following snippet:

public Case mySwitch(Object reference) {
    return new Case(reference);
}

public class Case {

    private Object reference;

    public Case(Object reference) {
        this.reference = reference;
    }

    public Case myCase(Object b, OnMatchDo task) {
        if (reference.equals(b)) {
            task.task(reference);
        }
        return this;
    }
}

public interface OnMatchDo {
    public void task(Object o);
}


问:
Why does C manage the heap, instead of the operating system?
In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Assuming what I wrote in parentheses is true, why is it?

Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

答:
From the other answers, here's what I gathered the answer to be.

Most operating systems only allocate memory to processes in fixed sizes, called pages. When a process returns memory to the OS, it can only do so in pagefuls. A page is a sequence of memory of a fixed size. The start and end points of a page are fixed, so even if you've got a large enough amount of free memory, you won't be able to return it to the OS unless it's between the start and end points of a page.

On the other hand, you could imagine that there is no operating system (or that the operating system allocates memory to programs from its own heap). This helps me understand things better, because the operating system was getting in the way of my intuition, because it looked as if the freed memory was being dropped into a black hole, and the allocated memory was coming out of a similar black hole. Without any OS, all the memory in a computer could be pictured as belonging to a large sequence of cells. If you allocate all available memory in a computer, and then start freeing some memory, then you might not be able to find a large enough contiguous chunk of memory to fulfill a malloc request.


问:
Laravel - Integrity constraint violation: 1452 Cannot add or update a child row
I am importing some content from remote WP database to local DB with laravel. I have set up the tables inventories and contents.

Inventories table looks like this:

```<code>    Schema::create('inventories', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('remote_id')->unsigned();
        $table->integer('local_id')->unsigned();
        $table->string('local_type');
        $table->timestamps();

        $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
    });
</code>```

This is the contents table:

```<code>    Schema::create('contents', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->integer('ct_id')->unsigned();
        $table->foreign('ct_id')->references('id')->on('content_types');
        $table->integer('cms_id');
        $table->string('title');
        $table->string('slug');
        $table->text('excerpt');
        $table->mediumText('body');
        $table->string('password');
        $table->integer('parent_id');
        $table->timestamps();
    });
</code>```

I have made functions to import all and import single posts from remote WP DB. This is the import for all posts:

```<code>public function all()
{
    $include      = array_diff($this->indexable, ['folder']);
    $publishedPostsIDs = $this->import($include);
    $this->deleteOldContent($publishedPostsIDs);
}

private function import($include)
{
    $posts             = Post::where('post_status', 'publish')->whereIn('post_type', $include)->get();
    foreach ($posts as $post) {
        $publishedPostsIDs[] = $post->ID;
        $this->contentInterface->updateOrCreateInventory($post->ID);
    }

    return $publishedPostsIDs;
}

public function updateOrCreateInventory($remoteId)
{
    $this->contentInterface->updateOrCreateInventory($remoteId);
}

private function deleteOldContent($publishedPostsIDs)
{
    $contentToDelete = Content::whereNotIn('cms_id', $publishedPostsIDs)->get();

    if (count($contentToDelete) > 0) {
        foreach ($contentToDelete as $content) {
            $content->delete();
        }
    }
}
</code>```

So, when I am importing all, I just go to the route that goes to all function, and all the posts from remote WP DB that are not of post type folder are imported. If I want to import a single post from remote DB, then I have a route that goes directly to the updateOrCreateInventory function. I also have import for the posts of type folder, which is basically almost the same as the function all.

```<code>public function folder()
{
    $include = ['folder'];
    $importResult = $this->import($include);

    return $importResult['imported'];
}
</code>```

The problem I have is that when I am importing all folders at once I get an error:

QueryException in Connection.php line 729: SQLSTATE[23000]: Integrity
  constraint violation: 1452 Cannot add or update a child row: a foreign
  key constraint fails (middleton.inventories, CONSTRAINT
  inventories_local_id_foreign FOREIGN KEY (local_id) REFERENCES
  contents (id) ON DELETE CASCADE) (SQL: insert into inventories
  (remote_id, updated_at, created_at) values (7512, 2017-11-13
  15:33:17, 2017-11-13 15:33:17))

But, if I try to import that same folder individually , or to be more exact that same post of type folder, I don't get any error and the post is imported. How is that possible?

答:
You $this->contentInterface creates an Inventory model without the "local_id" field specified, but it is required by the foreign key.

Find the place where you create the Inventory model and provide a valid "local_id".

Body:
I am importing some content from remote WP database to local DB with laravel. I have set up the tables inventories and contents.

Inventories table looks like this:

    Schema::create('inventories', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('remote_id')->unsigned();
        $table->integer('local_id')->unsigned();
        $table->string('local_type');
        $table->timestamps();

        $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
    });

This is the contents table:

    Schema::create('contents', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->integer('ct_id')->unsigned();
        $table->foreign('ct_id')->references('id')->on('content_types');
        $table->integer('cms_id');
        $table->string('title');
        $table->string('slug');
        $table->text('excerpt');
        $table->mediumText('body');
        $table->string('password');
        $table->integer('parent_id');
        $table->timestamps();
    });

I have made functions to import all and import single posts from remote WP DB. This is the import for all posts:

public function all()
{
    $include      = array_diff($this->indexable, ['folder']);
    $publishedPostsIDs = $this->import($include);
    $this->deleteOldContent($publishedPostsIDs);
}

private function import($include)
{
    $posts             = Post::where('post_status', 'publish')->whereIn('post_type', $include)->get();
    foreach ($posts as $post) {
        $publishedPostsIDs[] = $post->ID;
        $this->contentInterface->updateOrCreateInventory($post->ID);
    }

    return $publishedPostsIDs;
}

public function updateOrCreateInventory($remoteId)
{
    $this->contentInterface->updateOrCreateInventory($remoteId);
}

private function deleteOldContent($publishedPostsIDs)
{
    $contentToDelete = Content::whereNotIn('cms_id', $publishedPostsIDs)->get();

    if (count($contentToDelete) > 0) {
        foreach ($contentToDelete as $content) {
            $content->delete();
        }
    }
}

So, when I am importing all, I just go to the route that goes to all function, and all the posts from remote WP DB that are not of post type folder are imported. If I want to import a single post from remote DB, then I have a route that goes directly to the updateOrCreateInventory function. I also have import for the posts of type folder, which is basically almost the same as the function all.

public function folder()
{
    $include = ['folder'];
    $importResult = $this->import($include);

    return $importResult['imported'];
}

The problem I have is that when I am importing all folders at once I get an error:

QueryException in Connection.php line 729: SQLSTATE[23000]: Integrity
  constraint violation: 1452 Cannot add or update a child row: a foreign
  key constraint fails (middleton.inventories, CONSTRAINT
  inventories_local_id_foreign FOREIGN KEY (local_id) REFERENCES
  contents (id) ON DELETE CASCADE) (SQL: insert into inventories
  (remote_id, updated_at, created_at) values (7512, 2017-11-13
  15:33:17, 2017-11-13 15:33:17))

But, if I try to import that same folder individually , or to be more exact that same post of type folder, I don't get any error and the post is imported. How is that possible?


问:
Wso2IS 5.3.0 Automated Configuration
I am trying to automate my Wso2 5.3.0 configuration so that it is easier to setup a Wso2 instance based on our needs.

Is it possible to configure service providers through some configuration file instead of doing it through the admin panel?

答:
Searching around i found the doc page about the service for handling policies. It is called EntitlementPolicyAdminService and the doc page can be found here .

Still too bad that this is not configurable by a config file or something but at least there is a workable solution.

Title: Wso2IS 5.3.0 Automated Configuration


问:
split table rows of data into multiple tables according to column obeying constraints
I have a source flat file with about 20 columns of data an roughly 11K records. Each record (row) contains info such as

patientID,PatietnSSN.PatientDOB,PatientSex,PatientName,Patientaddress,PatientPhone,PatientWorkPhone,PatientProvider,PatientReferrer,PatientPrimaryInsurance,PatientInsurancePolicyID.

My goal is to move this data to a sql database.

I have created a database with the below datamodel

I know want to do a bulk insert to move all the records however I am unsure how to do that as you can see there are and have to be constraints in order to ensure referential integrity. What should my approach be? am I going about this all wrong? thus far I have used SSIS to import the data into a single staging table and now I must figure out how to write the 11k plus records to the individual tables in which they belong... so record 1 of the staging table will create 1 record across almost all of the tables minus perhaps the ones where there are 1 to many relationships like "provider" and "Referrer" as one provider will be linked to many patients but one patient can only have one provider.

I hope I have explained this well enough. Please help!

答:
As the question is generic, I'll approach the answer in a generic way as well - in an attempt to at least get you asking the right questions.

Your goal is to get flat-file data into a relational database. This is a very common operation and is at least a subset of the ETL process. So you might want to start your search by reading more on ETL.

Your fundamental problem, as I see it, is two-fold. First, you have a large amount of data to insert. Second, you are inserting into a relational database.

Starting with the second problem first; Not all of your data can be inserted each time. For example, you have a provider table that holds a 1:many relationship with a patient. That means that you will have to ask the question of each patient row in your flat table as to whether the provider exists or needs creating. Also, you have seeded Ids, meaning that in some instance you have to maintain your order of creation so that you can reference the id of a created entry in the next created entry. What this means to you is that your effort will be more complex than a simple set of SQL inserts. You need to logic associated with the effort. There are several ways to approach this.

Pure SQL/TSQL; It can be accomplished but would be a lot of work and hard to debug/troubleshoot

Write a program: This gives you a lot of flexibility, but means you will have to know how to program and use programming tools for working with a database (such as an ORM)

Use an automated ETL tool

Use SQL Server's flat-file import abilities

Use an IDE with import capabilities - such as Toad, Datagrip, DBeaver, etc.

Each of these approaches will take some research and learning on your part -- this forum cannot teach you how to use them. And the decision as to which one you want to use will somewhat depend on how automated the process should be.

Concerning your first issue -- large data inserts. SQL has the facility for Bulk inserts docs, but you will have to condition your data first.

Personally (as per my comments), I am a .Net developer. But given this task, I would still script it up in Python. The learning curve is very kind in Python and it has lots of great tools for working with files and database. .Net and EF carry with it a lot of overhead with respect to what you need to know to get started that python doesn't -- but that is just me.

Hope this helps get you started.


问:
How to get individual values from ups api address validation response through rocketshipit in php
I have a response for ups address validation request as follows:

```<code>Array ( [meta] => Array ( [code] => 200 [error_message] => ) [data] => Array ( [city] => [errors] => Array ( [0] => Array ( [code] => [type] => [description] => The state is not supported in the Customer Integration Environment. ) ) [name] => [city_state_zip_match] => [residential] => [po_box] => [suggestions] => [zipcode] => [state] => [addr2] => [addr3] => [addr1] => [zipcode_addon] => [country] => [checks] => [match] => ) )
</code>```

in PHP, how I do I get individual values like..
 code and error_message name, residential, po_box, sate etc.

Thanks in advance

答:
Thank you.
It is working fine with the following code.</p>

```<code>$json = <response from ups through rocketship.it>
print_r($json['meta']['code']);
print_r($json['meta']['error_message']);
print_r($json['data']['name']);
print_r($json['data']['po_box']);
print_r($json['data']['errors'][0]['description']);
if ($json['data']['po_box']){
    echo "PO BOX: Yes";
}else{
    echo "PO BOX: No";
}
</code>```

Body:
I have a response for ups address validation request as follows:

Array ( [meta] => Array ( [code] => 200 [error_message] => ) [data] => Array ( [city] => [errors] => Array ( [0] => Array ( [code] => [type] => [description] => The state is not supported in the Customer Integration Environment. ) ) [name] => [city_state_zip_match] => [residential] => [po_box] => [suggestions] => [zipcode] => [state] => [addr2] => [addr3] => [addr1] => [zipcode_addon] => [country] => [checks] => [match] => ) )

in PHP, how I do I get individual values like..
 code and error_message name, residential, po_box, sate etc.

Thanks in advance

Body:
Thank you.
It is working fine with the following code.

$json = <response from ups through rocketship.it>
print_r($json['meta']['code']);
print_r($json['meta']['error_message']);
print_r($json['data']['name']);
print_r($json['data']['po_box']);
print_r($json['data']['errors'][0]['description']);
if ($json['data']['po_box']){
    echo "PO BOX: Yes";
}else{
    echo "PO BOX: No";
}


问:
Math needed for Sql Server
I've been working in Sql server jobs since 2 years now. Although I like it, sometimes I get the feeling that at certain times, I stall too much on some tasks, and I seem to be discouraged easily from things that involve relatively simple logic. It's like, at some point I must repeat a logical condition inside my head more than 2 or 3 times in order to understand it completely.

I have the feeling that this might be of my lack of math knowledge. Can anyone please let me know what area of mathematics I can study, that would improve my Sql server coding skills?

Thank you.

答: Set theory helped me somewhat. Studied it in college years before I got into SQL, but being able to think of a bunch of numbers as a semi-amorphous blob of data and not as an ordered list of items really helps.</p>

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Math needed for Sql Server


问:
angular's ng-init alternative in Angular 2
What is the alternative of ng-init="myText='Hello World!'" in Angular 2 to add in the template, not in the component

```<code> <div ng-app="" ng-init="myText='Hello World!'">
</code>```

the alternative in Angular 2

答:
Little Update!
In the latest versions of Angular this will not work:

```<code>@Directive({
 selector: 'ngInit',
 exportAs: 'ngInit'
})
</code>```

you should use '[]':

```<code>@Directive({
   selector: '[ngInit]',
   exportAs: 'ngInit'
})
</code>```

Body:
What is the alternative of ng-init="myText='Hello World!'" in Angular 2 to add in the template, not in the component

the alternative in Angular 2

Body:
Little Update!
In the latest versions of Angular this will not work:

@Directive({
 selector: 'ngInit',
 exportAs: 'ngInit'
})

you should use '[]':

@Directive({
   selector: '[ngInit]',
   exportAs: 'ngInit'
})


答:
You need to add PARTITION BY:

```<code>SELECT col1,
       col2,
       ROW_NUMBER() OVER (PARTITION BY col1 ORDER by col2) AS row_index
FROM TABLE
ORDER BY col2
</code>```

Well, it seems like you actually need:

```<code>SELECT col1,
       col2,
       DENSE_RANK() OVER (ORDER by col1) AS row_index
FROM TABLE
ORDER BY col2
</code>```

Title: Row_Number with Teradata GROUPBY

Body:
I am trying to determine how I can use the ROW_NUMBER() function with TERADATA using the result set below. Here is what i have tried:

select col1, col2, ROW_NUMBER() OVER (ORDER by col2  )
    FROM
     (select col1, col2
    from TABLE
    ORDER BY col2) A

Result Set

38  11/14/2016  1
38  11/15/2016  2
38  11/16/2016  3
38  11/17/2016  4
38  11/18/2016  5
38  11/19/2016  6
39  11/20/2016  7
39  11/21/2016  8
39  11/22/2016  9
39  11/23/2016  10
39  11/24/2016  11
39  11/25/2016  12

Expected:

Col1    Col2    Col3
38  11/14/2016  1
38  11/15/2016  1
38  11/16/2016  1
38  11/17/2016  1
38  11/18/2016  1
38  11/19/2016  1
39  11/20/2016  2
39  11/21/2016  2
39  11/22/2016  2
39  11/23/2016  2
39  11/24/2016  2
39  11/25/2016  2

Body:
You need to add PARTITION BY:

SELECT col1,
       col2,
       ROW_NUMBER() OVER (PARTITION BY col1 ORDER by col2) AS row_index
FROM TABLE
ORDER BY col2

Well, it seems like you actually need:

SELECT col1,
       col2,
       DENSE_RANK() OVER (ORDER by col1) AS row_index
FROM TABLE
ORDER BY col2


问:
Elegant Solution avoiding Global Variable
I am trying to find an elegant and still readable Way of getting rid of that global Var. But cannot find a way to do it. no jQuery please it should work without any imports.

```

答:
Just wrap all your code in an Immediate Invoked Function Expression. This is called the "module pattern" and is very common in JS because functions cause their own scope.

Next, this line:

```<code>window.onload = ajax(anfang);
</code>```

Will actually run ajax(anfang) as soon as it is encountered and not wait for the load event. The way it is written, it says: "Run this function right now and whatever function it returns is what should be registered as the function to call when window.load happens." Instead, you need to wrap that in a function that, itself becomes the handler.

Additionally, you should be using .addEventListener() to register event handlers instead of object properties, such as onload or .onreadystatechange.

```<code>(function(){
  var anzahlErg = 0; //<--- THIS IS NOW LOCAL TO THE IIFE

  function ajax(f) {
    var xhttp = new XMLHttpRequest();

    xhttp.addEventListener("readystatechange", function() {
      if (this.readyState == 4 && this.status == 200) {
        f(this.responseText);
      }
    });

    xhttp.open("POST", "ajax1.php", true); // SELECT COUNT(*)
    xhttp.send();
  }

  function anfang(response) {
    anzahlErg = response;
  }

  function nachher(response) {
    if (anzahlErg != 0 && response != anzahlErg) {
      location.reload();
    }
  }

  window.addEventListener("load", function() {
    ajax(anfang)
  });

  setInterval(function() {
    return ajax(nachher)
  }, 250); //Polling Interval
})();
</code>```

Body:
Just wrap all your code in an Immediate Invoked Function Expression. This is called the "module pattern" and is very common in JS because functions cause their own scope.

Next, this line:

window.onload = ajax(anfang);

Will actually run ajax(anfang) as soon as it is encountered and not wait for the load event. The way it is written, it says: "Run this function right now and whatever function it returns is what should be registered as the function to call when window.load happens." Instead, you need to wrap that in a function that, itself becomes the handler.

Additionally, you should be using .addEventListener() to register event handlers instead of object properties, such as onload or .onreadystatechange.

(function(){
  var anzahlErg = 0; //<--- THIS IS NOW LOCAL TO THE IIFE

  function ajax(f) {
    var xhttp = new XMLHttpRequest();

    xhttp.addEventListener("readystatechange", function() {
      if (this.readyState == 4 && this.status == 200) {
        f(this.responseText);
      }
    });

    xhttp.open("POST", "ajax1.php", true); // SELECT COUNT(*)
    xhttp.send();
  }

  function anfang(response) {
    anzahlErg = response;
  }

  function nachher(response) {
    if (anzahlErg != 0 && response != anzahlErg) {
      location.reload();
    }
  }

  window.addEventListener("load", function() {
    ajax(anfang)
  });

  setInterval(function() {
    return ajax(nachher)
  }, 250); //Polling Interval
})();


问:
Convert Map<String, List<Object>> to ArrayList<DataBaseModel>
I am doing batchLoadItem from DynamoDB it comes back in the form:

```<code>Map<String, List<Object>>
</code>```

To test it is coming back correctly i did an iteration over the returned data like this:

```<code>for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }
</code>```

and it returned this in the log:

```<code>HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]
</code>```

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

答:
NEW ANSWER

As you said you can't use the stream api then try the following:

```<code>ArrayList<DatabaseModel> list = new ArrayList<>();
for(Map.Entry<String, List<Object>> entry : map.entrySet()){
     for(Object o : entry.getValue()){
          list.add((DatabaseModel) o);
     }
}
</code>```

OLD ANSWER

Try it with java8-StreamAPI:

```<code>ArrayList<DatabaseModel> list = map.entrySet().stream()
    .map(Map.Entry::getValue)
    .flatMap(Collection::stream)
    .map(o -> (DatabaseModel) o)
    .collect(Collectors.toCollection(ArrayList::new));
</code>```

Above code-snippet works like the following:

get a Stream (foundation of Java8-Streams) of entries: map.entrySet().stream()

get a new stream consisting of Lists of values .map(Map.Entry::getValue)

get a new stream consisting of values .flatMap(Collection::stream)

cast the values to DatabaseModel .map(o -> (DatabaseModel) o)

Collect all the values into an ArrayList .collect(Collectors.toCollection(ArrayList::new));

Body:
I am doing batchLoadItem from DynamoDB it comes back in the form:

Map<String, List<Object>>

To test it is coming back correctly i did an iteration over the returned data like this:

for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }

and it returned this in the log:

HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

Body:
NEW ANSWER

As you said you can't use the stream api then try the following:

ArrayList<DatabaseModel> list = new ArrayList<>();
for(Map.Entry<String, List<Object>> entry : map.entrySet()){
     for(Object o : entry.getValue()){
          list.add((DatabaseModel) o);
     }
}

OLD ANSWER

Try it with java8-StreamAPI:

ArrayList<DatabaseModel> list = map.entrySet().stream()
    .map(Map.Entry::getValue)
    .flatMap(Collection::stream)
    .map(o -> (DatabaseModel) o)
    .collect(Collectors.toCollection(ArrayList::new));

Above code-snippet works like the following:

get a Stream (foundation of Java8-Streams) of entries: map.entrySet().stream()

get a new stream consisting of Lists of values .map(Map.Entry::getValue)

get a new stream consisting of values .flatMap(Collection::stream)

cast the values to DatabaseModel .map(o -> (DatabaseModel) o)

Collect all the values into an ArrayList .collect(Collectors.toCollection(ArrayList::new));


问:
Display data from mysql row separated with comma as a link to an image
I have a row['cities'] in my table. There are different city's name in that row separated with comma and spaces (London, New York,   Tokyo,    Miami, ...). The goal is to create a link for each city name like img/london.png
I need to get the names from row['cities'], remove comma and whatever space is after comma and before the city's name, and then add img/ before that city's name and add .png after the city's name.

I did the following but because the empty space after comma is not one space for all cities and sometimes is more than one empty space, then the code didn't work for all city's name and it just works for those city's name that has one empty space after comma!

```<code>    $data = array($row['cities']);
    $city = explode(', ', $data[0]);
    $cities = $city[ rand(0, count($city)-1) ];
    $citylink = "img/".$cities.".png";
</code>```

What is the best way to do this and be able to remove all empty space between comma and city's name or perhaps there is a better way to solve this problem?
Thanks,

答:
```<code>$data = array($row['cities']);
$city = explode(', ', $data[0]);
$cities = $city[ rand(0, count($city)-1) ];

$citylink = "img/".trim($cities).".png";
</code>```

Body:
I have a row['cities'] in my table. There are different city's name in that row separated with comma and spaces (London, New York,   Tokyo,    Miami, ...). The goal is to create a link for each city name like img/london.png
I need to get the names from row['cities'], remove comma and whatever space is after comma and before the city's name, and then add img/ before that city's name and add .png after the city's name.

I did the following but because the empty space after comma is not one space for all cities and sometimes is more than one empty space, then the code didn't work for all city's name and it just works for those city's name that has one empty space after comma!

    $data = array($row['cities']);
    $city = explode(', ', $data[0]);
    $cities = $city[ rand(0, count($city)-1) ];
    $citylink = "img/".$cities.".png";

What is the best way to do this and be able to remove all empty space between comma and city's name or perhaps there is a better way to solve this problem?
Thanks,


问:
How to specify $HOME folder in sublime-build file?
I am using a custom build system in Sublime Text 3 for a C++ project. One of the lines looks like

```<code>"-I${HOME}/my_file/include"
</code>```

The problem is that ${HOME} does not expand to the actual /home/user_x, but expands to an empty string ''. I cannot find any way of specifying the HOME folder elegantly, without the need to write the actual path. Is there a way of doing this? I.e., to expand the UNIX $HOME variable to the actual location of the home folder?

答: You can try writing your commands to a shell script and running the script from Sublime. I'm not sure if Sublime supports this feature, but shell script should find and expand $HOME and any other variables.</p>

Body:
I am using a custom build system in Sublime Text 3 for a C++ project. One of the lines looks like

"-I${HOME}/my_file/include"

The problem is that ${HOME} does not expand to the actual /home/user_x, but expands to an empty string ''. I cannot find any way of specifying the HOME folder elegantly, without the need to write the actual path. Is there a way of doing this? I.e., to expand the UNIX $HOME variable to the actual location of the home folder?


问:
Count div from codility. StackOverflowError in program using recursion
I wrote program for one of lessons from Codility. Its called count div.

For example. I give number 6, 11 and 2. There are 3 numbers from 6 to 11 that we can divide by 2, its 6, 8, 10 so method should return 3.

At first I made program with recursion with only ints but I got error so I changed it to BigIntegers, but it doesnt help at all. It's working good for small numbers but with for example input:

A = 0, B = 20000, K = 1 it gives errors:

```<code>Exception in thread "main" java.lang.StackOverflowError
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.BigInteger.remainderKnuth(Unknown Source)
at java.math.BigInteger.remainder(Unknown Source)
at java.math.BigInteger.mod(Unknown Source)
at count_div.Solution.bigIntegerSolution(Solution.java:29)
at count_div.Solution.bigIntegerSolution(Solution.java:35)
</code>```

Here's my code:

```<code>public int solution(int A, int B, int K){

    BigInteger minValue = BigInteger.valueOf(A);
    BigInteger maxValue = BigInteger.valueOf(B);
    BigInteger div = BigInteger.valueOf(K);

    finalCounter = bigIntegerSolution(minValue, maxValue, div).intValue();

    return finalCounter;
}

public BigInteger bigIntegerSolution(BigInteger minValue, BigInteger maxValue, BigInteger div){

    int comparator = minValue.compareTo(maxValue);

    if(comparator <= 0){

        BigInteger modValue = minValue.mod(div);

        if( modValue.compareTo(zero) == 0){
            divCounter = divCounter.add(one);
        }
        minValue = minValue.add(one);
        bigIntegerSolution(minValue, maxValue, div);
    }

    return divCounter;
}
</code>```

Is there anything I can do or my solution idea is just bad for this purpose? I know that they are other solutions but I first came up with this and I would like to know if I can fix it.

答:
Your solution is out of initial requirements

Complexity:

expected worst-case time complexity is O(1);

  expected worst-case space complexity is O(1).

One line solution

```<code>public class CountDiv {
    public int solution(int a, int b, int k) {
        return b / k - a / k + (a % k == 0 ? 1 : 0);
    }
}
</code>```

Test results

Body:
I wrote program for one of lessons from Codility. Its called count div.

For example. I give number 6, 11 and 2. There are 3 numbers from 6 to 11 that we can divide by 2, its 6, 8, 10 so method should return 3.

At first I made program with recursion with only ints but I got error so I changed it to BigIntegers, but it doesnt help at all. It's working good for small numbers but with for example input:

A = 0, B = 20000, K = 1 it gives errors:

Exception in thread "main" java.lang.StackOverflowError
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.BigInteger.remainderKnuth(Unknown Source)
at java.math.BigInteger.remainder(Unknown Source)
at java.math.BigInteger.mod(Unknown Source)
at count_div.Solution.bigIntegerSolution(Solution.java:29)
at count_div.Solution.bigIntegerSolution(Solution.java:35)

Here's my code:

public int solution(int A, int B, int K){

    BigInteger minValue = BigInteger.valueOf(A);
    BigInteger maxValue = BigInteger.valueOf(B);
    BigInteger div = BigInteger.valueOf(K);

    finalCounter = bigIntegerSolution(minValue, maxValue, div).intValue();

    return finalCounter;
}

public BigInteger bigIntegerSolution(BigInteger minValue, BigInteger maxValue, BigInteger div){

    int comparator = minValue.compareTo(maxValue);

    if(comparator <= 0){

        BigInteger modValue = minValue.mod(div);

        if( modValue.compareTo(zero) == 0){
            divCounter = divCounter.add(one);
        }
        minValue = minValue.add(one);
        bigIntegerSolution(minValue, maxValue, div);
    }

    return divCounter;
}

Is there anything I can do or my solution idea is just bad for this purpose? I know that they are other solutions but I first came up with this and I would like to know if I can fix it.

Body:
Your solution is out of initial requirements

Complexity:

expected worst-case time complexity is O(1);

  expected worst-case space complexity is O(1).

One line solution

public class CountDiv {
    public int solution(int a, int b, int k) {
        return b / k - a / k + (a % k == 0 ? 1 : 0);
    }
}

Test results


问:
Mode Calculation Using Teradata
I am trying to calculate a mode by groups within Teradata. Below is what has been recommended:

```<code>select retl_a
from vpp_fpp
group by dpci_lbl_t
qualify rank() over (order by count(*) desc) = 1;
</code>```

But I receive an error saying Selected non-aggregate values must be part of the associated group. Any help is appreciated.

Below is an example:

```<code>data vpp_fpp
dpci_lbl_t retl_a
a 4
a 4
a 3
b 3
b 1
Expected result:
a 4
b 2
</code>```

答:
You just need a partition by.  I think this is the logic you want:

```<code>select dpci_lbl_t, retl_a
from vpp_fpp
group by dpci_lbl_t, retl_a
qualify rank() over (partition by dpci_lbl_t order by count(*) desc) = 1;
</code>```

Title: Mode Calculation Using Teradata

Body:
I am trying to calculate a mode by groups within Teradata. Below is what has been recommended:

select retl_a
from vpp_fpp
group by dpci_lbl_t
qualify rank() over (order by count(*) desc) = 1;

But I receive an error saying Selected non-aggregate values must be part of the associated group. Any help is appreciated.

Below is an example:

data vpp_fpp
dpci_lbl_t retl_a
a 4
a 4
a 3
b 3
b 1
Expected result:
a 4
b 2

Body:
You just need a partition by.  I think this is the logic you want:

select dpci_lbl_t, retl_a
from vpp_fpp
group by dpci_lbl_t, retl_a
qualify rank() over (partition by dpci_lbl_t order by count(*) desc) = 1;


问:
return type is less accessible than method
I am new to c# and here is an excerpt from a personal project i am working on to get some experience.

When calling the getRecipe() function outside this class i am presented with the following error. I want to keep my List private to the CookBook class but still be able to get a reference to one of the Recipes in the List. I do not want to make my List public.

Any advice is greatly appreciated! Thanks

The error

```<code>return type 'cookbook.Recipe is less accessible than method 'cookbook.CookBook.getRecipe(string)'
</code>```

```<code>public class CookBook
{
    private List<Recipe> listOfRecipes = new List<Recipe> {};
    public Recipe getRecipe(string name)
    {
        int i = 0;
        while (listOfRecipes[i].getRecipeName() != name)
        {
            i++;
        }
        return listOfRecipes[i];
    }
}
</code>```

答: Check to make sure the extent if visibility of 'Recipe' class is covers where you want to access it.</p>

Body:
I am new to c# and here is an excerpt from a personal project i am working on to get some experience.

When calling the getRecipe() function outside this class i am presented with the following error. I want to keep my List private to the CookBook class but still be able to get a reference to one of the Recipes in the List. I do not want to make my List public.

Any advice is greatly appreciated! Thanks

The error

return type 'cookbook.Recipe is less accessible than method 'cookbook.CookBook.getRecipe(string)'

public class CookBook
{
    private List<Recipe> listOfRecipes = new List<Recipe> {};
    public Recipe getRecipe(string name)
    {
        int i = 0;
        while (listOfRecipes[i].getRecipeName() != name)
        {
            i++;
        }
        return listOfRecipes[i];
    }
}


问:
Rxjs: How to implement Observable.first()?
I'm learning RxJs and trying to understand how Observable.first() method works under the hood.
Source code is pretty messy.

Is there an easy way to implement this method to understand how it works?

I want to understand exactly how it works inside, but not how it can be implemented.

答:
From the documentation we see

Emits only the first value. Or emits only the first value that passes some test.

So the basic behaiour (emits only the first value) is done by keeping track whether the first value has been emitted or not, with a subscriber-level field.

Then predicate, resultSelector, or defaultValues are just a bit of additions to that basic code (basically a filter, a map or a default).

If you want to take a look on the specific code for this operator, the relevant part is FirstSubscriber._next => FirstSubscriber._emit => FirstSubscriber._emitFinal, where it uses the this._emitted flag to track if it has emitted or not.

Edit: If you wanted to define a custom Rx extension that does what first() does without using other basic operators such as take(1), I would do something like this:

```<code>Observable.prototype.first = function() {
    const source = this;
    return new Observable(observer => {
        let hasSentValue = false;

        return source.subscribe(
            v => {
                if(!hasSentValue) {
                    observer.next(v);
                    observer.complete();
                    hasSentValue = true;
                }
            },
            err => observer.error(err),
            () => {
                if(!hasSentValue) {
                    observer.error("Empty stream");
                }
            });
    });
};
</code>```

Note: not tested

Body:
From the documentation we see

Emits only the first value. Or emits only the first value that passes some test.

So the basic behaiour (emits only the first value) is done by keeping track whether the first value has been emitted or not, with a subscriber-level field.

Then predicate, resultSelector, or defaultValues are just a bit of additions to that basic code (basically a filter, a map or a default).

If you want to take a look on the specific code for this operator, the relevant part is FirstSubscriber._next => FirstSubscriber._emit => FirstSubscriber._emitFinal, where it uses the this._emitted flag to track if it has emitted or not.

Edit: If you wanted to define a custom Rx extension that does what first() does without using other basic operators such as take(1), I would do something like this:

Observable.prototype.first = function() {
    const source = this;
    return new Observable(observer => {
        let hasSentValue = false;

        return source.subscribe(
            v => {
                if(!hasSentValue) {
                    observer.next(v);
                    observer.complete();
                    hasSentValue = true;
                }
            },
            err => observer.error(err),
            () => {
                if(!hasSentValue) {
                    observer.error("Empty stream");
                }
            });
    });
};

Note: not tested


问:
Proper way to display your own push message notification from non-running app in Android Oreo
Now that services are not running in the background, what is the proper way to generate and display your own notification from a push data payload? Is that possible anymore? I want the notification to have a different look and feel depending on the data payload. My GCM version of the app works fine, but my FCM version does not. Any thoughts?</p>

答:
When you send the push data, are you including both a "data" payload and a "notification" payload?

Check the documentation on receiving messages in Android.  If you send your FCM messages with only a "data" payload, then you can implement onMessageReceived() and that code will receive all notifications, both when the app is in the foreground and when it is in the background.

In your onMessageReceived() method, build your own notification in whatever style you want.  You can vary the style depending on the content of the "data" payload.  If you aren't familiar with building your own notifications, here is the documentation.


问:
Asp.net JavaScript OnClick not working
What I'm trying to do is, when I click on the button it should show an alert box.
Here is the code.

```<code>protected void btnAdd_Click(object sender, EventArgs e)
{
    string script = "<script type=\"text/javascript\">alert('abc 1');
    </script>";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
    script);
    Response.Redirect("~/Index.aspx");

}
</code>```

It is working perfectly but when I put this same code in another page it does not work.

what are the things I have to look into? any suggestion please?

答:
Pass the last Parameter either True or False in ClientScript.RegisterScript and better you pass the alert message in this way.

Like This

```<code> protected void btnAdd_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('abc 1');",true);
        Response.Redirect("~/Index.aspx");
    }
</code>```

Title: Asp.net JavaScript OnClick not working

Body:
What I'm trying to do is, when I click on the button it should show an alert box.
Here is the code.

protected void btnAdd_Click(object sender, EventArgs e)
{
    string script = "";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
    script);
    Response.Redirect("~/Index.aspx");

}

It is working perfectly but when I put this same code in another page it does not work.

what are the things I have to look into? any suggestion please?

Body:
Pass the last Parameter either True or False in ClientScript.RegisterScript and better you pass the alert message in this way.

Like This

 protected void btnAdd_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('abc 1');",true);
        Response.Redirect("~/Index.aspx");
    }


问:
Setting Range Results in Application Defined or Object Defined Error, two methods? VBA
When setting a range, and the active worksheet is not = to the reference I get an

Application Defined Object Defined Error

using this method below:

```<code>Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3))
</code>```

But why does it work when I use this method:

```<code>Set Rng = Range(Worksheets("Worksheet2").Cells(2,2),Worksheets("Worksheet2").Cells(2,3))
</code>```

Just trying to understand why exactly the last method works, but the first does not.

答:
Because you cannot have two different references for the worksheet and the cells. So it whould be like</p>

```<code>Set Rng = Worksheets("Worksheet2").Range(Worksheets("Worksheet2").Cells(2, 2), Worksheets("Worksheet2").Cells(2, 3))
</code>```

Body:
When setting a range, and the active worksheet is not = to the reference I get an

Application Defined Object Defined Error

using this method below:

Set Rng = Worksheets("Worksheet2").Range(Cells(2,2),Cells(2,3))

But why does it work when I use this method:

Set Rng = Range(Worksheets("Worksheet2").Cells(2,2),Worksheets("Worksheet2").Cells(2,3))

Just trying to understand why exactly the last method works, but the first does not.

Body:
Because you cannot have two different references for the worksheet and the cells. So it whould be like

Set Rng = Worksheets("Worksheet2").Range(Worksheets("Worksheet2").Cells(2, 2), Worksheets("Worksheet2").Cells(2, 3))


问:
How do I change the element of a list with user input?
I'm trying to change an element of a list by doing this:

```<code>board = []
for i in range(3):
    board.append("-"*3)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)
print "Welcome to tic tac toe. You go first because I say so."
column = int(raw_input("Enter column number: "))
row = int(raw_input("Enter row number: "))

board[row][column] = "O" #THIS ONE
print_board(board)
</code>```

but the error message "TypeError: 'str' object does not support item assignment" shows up. What should I do?

答:
'-' * 3 is a string and you want a list.

So you should replace this :

```<code>board.append("-"*3) # '---'
</code>```

with this :

```<code>board.append(['-']*3) # ['-','-','-']
</code>```

Body:
I'm trying to change an element of a list by doing this:

board = []
for i in range(3):
    board.append("-"*3)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)
print "Welcome to tic tac toe. You go first because I say so."
column = int(raw_input("Enter column number: "))
row = int(raw_input("Enter row number: "))

board[row][column] = "O" #THIS ONE
print_board(board)

but the error message "TypeError: 'str' object does not support item assignment" shows up. What should I do?

Body:
'-' * 3 is a string and you want a list.

So you should replace this :

board.append("-"*3) # '---'

with this :

board.append(['-']*3) # ['-','-','-']


问:
Magento: Product ID by SKU (JavaScript / Client Side)
Is there a way to somehow request the product ID with the SKU as a client without access to the server?

Thanks for any help!

答:
According to your answer i assume you want to scrap magento product id from a 3rd party store.

The most solid way to do this, is to read it from hidden field in addtocart form.


问:
How to structure an array of multiple outputs in one array (Java)
My code basically runs through an array, finds the maximum, and then locates the indices correlated with it. The issue I have is that I would like the indices in one array instead of multiple.

For example (actual output):

```<code>[1] [2] [3] [4]
</code>```

Wanted output: [1,2,3,4]

Here is my code:

```<code> int index;
    int num = myArray[0];
    for (int i = 0; i < myArray.length; i++) {
        if (num < myArray[i]) {
            num = myArray[i];
        }
    }
    for (int j = 0; j < myArray.length; j++) {
        if(num == myArray[j]){
               index = j;
               System.out.println("[" + j + "]");
        }
    }
</code>```

I don't know how to do this without redoing all the code. Thanks.

答:
```<code>int index;
int num = myArray[0];
for (int i = 0; i < myArray.length; i++) {
    if (num < myArray[i]) {
        num = myArray[i];
    }
}
System.out.print("[");
int count = 0;
for (int j = 0; j < myArray.length; j++) {
    if(num == myArray[j]){
           index = j;
           if(count++ > 0)
             System.out.print(",");
           System.out.print(j);
    }
}
System.out.println("]");
</code>```

Body:
My code basically runs through an array, finds the maximum, and then locates the indices correlated with it. The issue I have is that I would like the indices in one array instead of multiple.

For example (actual output):

[1] [2] [3] [4]

Wanted output: [1,2,3,4]

Here is my code:

 int index;
    int num = myArray[0];
    for (int i = 0; i < myArray.length; i++) {
        if (num < myArray[i]) {
            num = myArray[i];
        }
    }
    for (int j = 0; j < myArray.length; j++) {
        if(num == myArray[j]){
               index = j;
               System.out.println("[" + j + "]");
        }
    }

I don't know how to do this without redoing all the code. Thanks.


问:
Window is not defined with Server Side Rendering React and Express
Note that I am using Turbo360, you can find more about here at https://www.turbo360.co/, but I assure you it is exactly like express in how it works, so the error is not coming from here.

I have talked to some people and from what I have gathered this error is coming from my entry point where I call cont initialState = window.INITIAL_STATE;.

This error is triggered when I hit my back-end routes on the server side. However the route itself does succeed on the back-end, and what I mean by that is that if I were to log the data I get a user back success.

However on the front-end I get this instead:

I will try not to clutter this up to much so you will have to have some good knowledge about SSR. The SSR part works just fine until I hit my back-end express routes. So I will keep the code to those unless it is necessary to add it in.

React entry point:

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';

import store from './stores';
import routes from './routes';

const initialState = window.INITIAL_STATE; //WHERE I BELIEVE ERROR IS COMMING FROM

ReactDOM.hydrate(
  <Provider store={store.configure(initialState)}>
    <BrowserRouter>
      <div>{renderRoutes(routes)}</div>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);
</code>```

Server entry point:

```<code>require('babel-core/register')({
  presets: ['env', 'react', 'stage-0', 'stage-1']
});

const pkg_json = require('./package.json');
const vertex = require('vertex360')({ site_id: pkg_json.app });
var renderer = require('./renderer.js');

// initialize app
const app = vertex.app();

// import routes
const index = require('./routes/index');
const api = require('./routes/api');
const users = require('./routes/users');

// set routes
app.use('/api/users', users);

// hopefully will be used on every Route, this should handle SSR RR4
app.use(renderer);

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

Server Side users Route for register:

```<code>router.post('/register', (req, res) => {
  const body = req.body;

  if (body.username.length == 0) {
    res.json({
      confirmation: 'fail',
      message: 'Please enter an username address.'
    });

    return;
  }

  if (body.password.length == 0) {
    res.json({
      confirmation: 'fail',
      message: 'Please enter a password.'
    });

    return;
  }

  turbo
    .createUser(body)
    .then(data => {
      res.json({
        confirmation: 'success',
        user: data
      });
    })
    .catch(err => {
      res.json({
        confirmation: 'fail',
        message: err.message
      });
    });
});
</code>```

Action:

```<code>axios.post('/api/users/register', params)
  .then(response => { console.log(response.data });
  .catch(err => { console.log(err); });
</code>```

答:
Looking at the code the first fix that should be done is

```<code>cont initialState = typeof window !== "undefined" && window && window.INITIAL_STATE;.
</code>```

This should ideally solve the window not defined issues for you.
Since while doing SSR, window object will not exist since that is a browser level object.

Body:
Note that I am using Turbo360, you can find more about here at https://www.turbo360.co/, but I assure you it is exactly like express in how it works, so the error is not coming from here.

I have talked to some people and from what I have gathered this error is coming from my entry point where I call cont initialState = window.INITIAL_STATE;.

This error is triggered when I hit my back-end routes on the server side. However the route itself does succeed on the back-end, and what I mean by that is that if I were to log the data I get a user back success.

However on the front-end I get this instead:

I will try not to clutter this up to much so you will have to have some good knowledge about SSR. The SSR part works just fine until I hit my back-end express routes. So I will keep the code to those unless it is necessary to add it in.

React entry point:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';

import store from './stores';
import routes from './routes';

const initialState = window.INITIAL_STATE; //WHERE I BELIEVE ERROR IS COMMING FROM

ReactDOM.hydrate(
  <Provider store={store.configure(initialState)}>
    <BrowserRouter>

{renderRoutes(routes)}

    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

Server entry point:

require('babel-core/register')({
  presets: ['env', 'react', 'stage-0', 'stage-1']
});

const pkg_json = require('./package.json');
const vertex = require('vertex360')({ site_id: pkg_json.app });
var renderer = require('./renderer.js');

// initialize app
const app = vertex.app();

// import routes
const index = require('./routes/index');
const api = require('./routes/api');
const users = require('./routes/users');

// set routes
app.use('/api/users', users);

// hopefully will be used on every Route, this should handle SSR RR4
app.use(renderer);

module.exports = app;

Server Side users Route for register:

router.post('/register', (req, res) => {
  const body = req.body;

  if (body.username.length == 0) {
    res.json({
      confirmation: 'fail',
      message: 'Please enter an username address.'
    });

    return;
  }

  if (body.password.length == 0) {
    res.json({
      confirmation: 'fail',
      message: 'Please enter a password.'
    });

    return;
  }

  turbo
    .createUser(body)
    .then(data => {
      res.json({
        confirmation: 'success',
        user: data
      });
    })
    .catch(err => {
      res.json({
        confirmation: 'fail',
        message: err.message
      });
    });
});

Action:

axios.post('/api/users/register', params)
  .then(response => { console.log(response.data });
  .catch(err => { console.log(err); });

Body:
Looking at the code the first fix that should be done is

cont initialState = typeof window !== "undefined" && window && window.INITIAL_STATE;.

This should ideally solve the window not defined issues for you.
Since while doing SSR, window object will not exist since that is a browser level object.


问:
Using Assembly.GetEntryAssembly().Location to detect if file exists
I am trying to detect if a given file exists. For example, let's say I'm looking for Joystick.png in this directory: F:\FrontEnd\Themes\Custom\Images\Platform\Controller\Joystick.png

I cannot hard code the directory structure because the application might be installed elsewhere. the directory structure however, doesn't change.

I had been using this

```<code>string path = $"pack://siteoforigin:,,,/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";
</code>```

to send the path to an image on the wpf but I've come to leanr that I cannot pass this same variable into File.Exists. So I had to come up with an alternative.

I've  discovered this:

```<code>string exists = Assembly.GetEntryAssembly().Location;
</code>```

which gets me this result: F:\FrontEnd\FrontEnd.exe

So my question is, how do I modify the var exists so that is matches the structure of var path?

答:
Try this

```<code>  var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

  var pathtoCombine = Path.Combine(path, "themes\\custom\\images\\controls\\pc");

  var image = Path.Combine(pathtoCombine, "image.txt");
  var exists = File.Exists(image);
</code>```

You can change "themes\\custom\\images\\controls\\pc" to $"themes\\custom\\images\\controls\\{platform}\\{imagename}"

This gives the root of your assembly. for example

c:\users\\documents\visual studio 2015\Projects\StringSandbox\StringSandbox\bin\Debug

Body:
I am trying to detect if a given file exists. For example, let's say I'm looking for Joystick.png in this directory: F:\FrontEnd\Themes\Custom\Images\Platform\Controller\Joystick.png

I cannot hard code the directory structure because the application might be installed elsewhere. the directory structure however, doesn't change.

I had been using this

string path = $"pack://siteoforigin:,,,/Themes/Custom/Images/Controls/{game.Platform}/{controller}.png";

to send the path to an image on the wpf but I've come to leanr that I cannot pass this same variable into File.Exists. So I had to come up with an alternative.

I've  discovered this:

string exists = Assembly.GetEntryAssembly().Location;

which gets me this result: F:\FrontEnd\FrontEnd.exe

So my question is, how do I modify the var exists so that is matches the structure of var path?

Body:
Try this

  var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

  var pathtoCombine = Path.Combine(path, "themes\\custom\\images\\controls\\pc");

  var image = Path.Combine(pathtoCombine, "image.txt");
  var exists = File.Exists(image);

You can change "themes\\custom\\images\\controls\\pc" to $"themes\\custom\\images\\controls\\{platform}\\{imagename}"

This gives the root of your assembly. for example

c:\users\\documents\visual studio 2015\Projects\StringSandbox\StringSandbox\bin\Debug


问:
How to order months in Python matplotlib?
I have a table based on month names in SQL. sorted with the monthnumbers int. I want to make a line graph in Python Jupyter Notebook with matplotlib. BUT the line graph is giving me an alphabatical order ( a, b, c etc...)

This is not correct. I need the order in month numbers.

How can i do this?
i have both the monthnumber and the monthname in my select statement:

```<code>cursor = conx.cursor()
cursor.execute(sql)
Revenue = []
Monthnumber = []
Month = []
Maandnummer = []

for row in cursor:
    regio.append(str(row.Mond))
    Revenue.append(int(row.Revenue))
    Month.append(int(row.Month))
    Maandnummer.append(int(row.Monthnumber))

df = pd.read_sql(sql, conx)
Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli', 'augustus','september', 'oktober', 'november', 'december']
mapping = {Maandnummer: i for i, maandnummer in enumerate(Months)}
key = df['maandnummer'].map(mapping)

# Plot de inhoud van het dataframe (tabel als resultaat van query)
plt.figure(figsize=(20,10))
aantal.sort()
plt.plot(key, omzet, 'ro')
plt.ylabel('Omzet')
plt.xlabel('Regio')
plt.show()
</code>```

答:
I got lost between the different lists and columns, where some seem to include the same content. So here is a minimal example.

The idea is indeed to map the month to a number according to its position in the list. This can be done using a dictionary: dict(zip(Months,range(len(Months)))).

One may then apply this map to the dataframe column. In principle that is the approach from the code in the question, but while it is not reproducible, the following would be.

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli',
          'augustus','september', 'oktober', 'november', 'december']

df = pd.DataFrame({"maand" : np.random.choice(Months, size=100),
                   "omzet" : np.random.binomial(100,0.5, size=100)})
mapping = dict(zip(Months,range(len(Months))))
df['maandnummer'] = df['maand'].map(mapping)

plt.figure()

plt.plot(df['maandnummer'], df["omzet"], 'ro')
plt.xticks(range(len(Months)),Months, rotation=45,ha="right")
plt.ylabel('Omzet')
plt.xlabel('Maand')
plt.show()
</code>```

Body:
I have a table based on month names in SQL. sorted with the monthnumbers int. I want to make a line graph in Python Jupyter Notebook with matplotlib. BUT the line graph is giving me an alphabatical order ( a, b, c etc...)

This is not correct. I need the order in month numbers.

How can i do this?
i have both the monthnumber and the monthname in my select statement:

cursor = conx.cursor()
cursor.execute(sql)
Revenue = []
Monthnumber = []
Month = []
Maandnummer = []

for row in cursor:
    regio.append(str(row.Mond))
    Revenue.append(int(row.Revenue))
    Month.append(int(row.Month))
    Maandnummer.append(int(row.Monthnumber))

df = pd.read_sql(sql, conx)
Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli', 'augustus','september', 'oktober', 'november', 'december']
mapping = {Maandnummer: i for i, maandnummer in enumerate(Months)}
key = df['maandnummer'].map(mapping)

# Plot de inhoud van het dataframe (tabel als resultaat van query)
plt.figure(figsize=(20,10))
aantal.sort()
plt.plot(key, omzet, 'ro')
plt.ylabel('Omzet')
plt.xlabel('Regio')
plt.show()

Body:
I got lost between the different lists and columns, where some seem to include the same content. So here is a minimal example.

The idea is indeed to map the month to a number according to its position in the list. This can be done using a dictionary: dict(zip(Months,range(len(Months)))).

One may then apply this map to the dataframe column. In principle that is the approach from the code in the question, but while it is not reproducible, the following would be.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli',
          'augustus','september', 'oktober', 'november', 'december']

df = pd.DataFrame({"maand" : np.random.choice(Months, size=100),
                   "omzet" : np.random.binomial(100,0.5, size=100)})
mapping = dict(zip(Months,range(len(Months))))
df['maandnummer'] = df['maand'].map(mapping)

plt.figure()

plt.plot(df['maandnummer'], df["omzet"], 'ro')
plt.xticks(range(len(Months)),Months, rotation=45,ha="right")
plt.ylabel('Omzet')
plt.xlabel('Maand')
plt.show()


问:
Eclipse doesn't report errors until runtime
I was trying to do some messy tricks to carry in an IMarker a ProblemDescriptor object.

ProblemDescriptor problem = new ProblemDescriptor(... my arguments...);
marker.setAttribute("PROBLEM_DESCRIPTOR", problem);

Later on I wanted to check if the attribute is set, make use of the informations from it.

The error is not reported while developing but at runtime I get the error:

The attribute value type is com.localhost.problems.ProblemDescription and expected is one of java.lang.String, Boolean, Integer

Is it a special case/a bad implementation in that code or I should get used with those kinds of errors reported only at runtime?

答:
Make sure you're calling your method correctly. That error looks like you are passing

com.localhost.problems.ProblemDescription

To a method that is expecting something else.

... leaving out the arguments isn't helping


问:
Send both POST and GET in a form
I need to make a form send both POST and GET requests (due to some bugs in IE and iframes), how can you do so?

The data being sent is nothing mega secure so it doesn't matter if it can be set via GET, just need to make sure it is set both ways.

Thanks for the help!

答:
Make the form do a usual POST and use JavaScript to replicate the values in the query string as well:

HTML:

```<code><form id="myform" method="post" action="..." onsubmit="process()">
  ...
</form>
</code>```

JavaScript:

```<code>function process() {
  var form = document.getElementById('myform');
  var elements = form.elements;
  var values = [];

  for (var i = 0; i < elements.length; i++)
    values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));

  form.action += '?' + values.join('&');
}
</code>```

Title: Send both POST and GET in a form

Body:
Make the form do a usual POST and use JavaScript to replicate the values in the query string as well:

HTML:

<form id="myform" method="post" action="..." onsubmit="process()">
  ...
</form>

JavaScript:

function process() {
  var form = document.getElementById('myform');
  var elements = form.elements;
  var values = [];

  for (var i = 0; i < elements.length; i++)
    values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));

  form.action += '?' + values.join('&');
}


问:
Azure Storage Queue - Trigger on empty
I have a nodejs Azure Function reading for a Storage Queue which is being filled once a day. When all messages have been processed and the results are stored in a table I'd like to call a final function doing some work with the gathered data.

What's the best way to achieve this? Can I get the remaining messages in the queue inside my nodejs bindings? Do I have to peek the queue through the nodejs azure sdk? Can I trigger a different function when the queue runs empty?

答:
This is a classic "join" problem.   There are a few ways to handle this:

Try the new Durable Function preview ( https://azure.github.io/azure-functions-durable-extension/ ). It's exactly for this situation.

At the end of each worker queue message, figure out if it's the "last" one. Ie, if you're writing unique rows to a table, just scan the table and see if it's complete. (this is obviously not feasible if it's a large table).

Maintain a counter. Each queue message decrements the counter. The guy that decrements to 0 is the "last". This can be kind of a pain since there's not a great way to atomically decrement a shared counter. You could either do some etag magic, or degenerate this into case #2 by having each worker write a row to a table.

Title: Azure Storage Queue - Trigger on empty


问:
Using self join/inner join to get the data by adding all the above rows data, in SQL Server
I am working with SQL server, the query details are as below:

Need to get the calculative column whose result will be the addition of all the above rows. And I can't use correlated queries, Lag and Lead as it is not supported.

I tried using self-join/inner join/left outer join, the only problem I am facing is due to group by clause of other columns the result is not coming as expected.

For example, data is like

Expected Output

But the output I am getting due to group by clause applied on Column4.
Output getting is like below

Is there some alternative of GROUP BY clause or other alternatives?

答:
In SQL Server 2012+, you would simply use cumulative sum:</p>

```<code>select d.*, sum(column3) over (order by column2)
from data d;
</code>```

Body:
In SQL Server 2012+, you would simply use cumulative sum:

select d.*, sum(column3) over (order by column2)
from data d;


问:
Sorting an array of dates in bash
I want to sort an array of dates.

Example format: "2017-11-13_07-55-40" or Year-Month-Date_Hour-Minute-Second

```<code>array={"2017-11-13_09-55-42" "2017-11-13_08-30-40" "2017-11-13_07-55-40"}
</code>```

Title: Sorting an array of dates in bash

Body:
I want to sort an array of dates.

Example format: "2017-11-13_07-55-40" or Year-Month-Date_Hour-Minute-Second

array={"2017-11-13_09-55-42" "2017-11-13_08-30-40" "2017-11-13_07-55-40"}

Body:
Since your dates are already in YYYY-MM-DD-HH-MM-SS format, you can use numeric sort:

array=("2017-11-13_09-55-42" "2017-11-13_08-30-40" "2017-11-13_07-55-40")
sort -n < <(printf '%s\n' "${array[@]}")

2017-11-13_07-55-40
2017-11-13_08-30-40
2017-11-13_09-55-42

To store output in another array use:

# populate another array with sorted date values
arr=($(sort -n < <(printf '%s\n' "${array[@]}")))

# examine new array values
declare -p arr
declare -a arr=([0]="2017-11-13_07-55-40" [1]="2017-11-13_08-30-40" [2]="2017-11-13_09-55-42")


问:
Convert Map<String, List<Object>> to ArrayList<DataBaseModel>
I am doing batchLoadItem from DynamoDB it comes back in the form:

```<code>Map<String, List<Object>>
</code>```

To test it is coming back correctly i did an iteration over the returned data like this:

```<code>for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }
</code>```

and it returned this in the log:

```<code>HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]
</code>```

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

答:
One simple way is this

```<code>List<DatabaseModel> value = (List<DatabaseModel>)entry.getValue();
// oops error
</code>```

JIC, why error, Read Wildcards and Subtyping

So we can trick the compiler by upcasting

```<code>List<DatabaseModel> value = (List<DatabaseModel>)((Object)entry.getValue());
</code>```

Body:
I am doing batchLoadItem from DynamoDB it comes back in the form:

Map<String, List<Object>>

To test it is coming back correctly i did an iteration over the returned data like this:

for(Map.Entry<String, List<Object>> entry : individualAlarmsReturnedFromDatabase.entrySet()){
                            List<Object> value = entry.getValue();
                            System.out.println("HASH " + value);
                        }

and it returned this in the log:

HASH [com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@ab28829, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@c36a7ae, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@8f0994f, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@f4188dc, com.amazonaws.models.nosql.IndividualAlarmsDatabaseModel@cc27de5]

This is returning correctly and as you can see the data is in the form of DataBaseModel.

I have tried all the ways I could find on stackoverflow but I don't know how to get it into an ArrayList<DatabaseModel> because it comes back as Map<String, List<Object>>

Thanks

Body:
One simple way is this

List<DatabaseModel> value = (List<DatabaseModel>)entry.getValue();
// oops error

JIC, why error, Read Wildcards and Subtyping

So we can trick the compiler by upcasting

List<DatabaseModel> value = (List<DatabaseModel>)((Object)entry.getValue());


问:
Google Chrome "window.open" workaround?
I have been working on a web app and for part of it I need to open a new window. I have this working on all browsers, my sticking point is with Google Chrome.

Chrome seems to ignore the window features which is causing me issues, the thing I'm struggling with is I need the address bar to be editable within the new window. FF, IE, Safari and Opera do this fine, Chrome does not.

My Code:

```<code>function popitup(url) {
  newwindow=window.open(url, 'name', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=1,resizable=1,width=800,height=600');
  if (window.focus) {
    newwindow.focus()
  }
  return false;
}
</code>```

答:
As far as I can tell, chrome doesn't work properly if you are referencing localhost (say, you're developing a site locally)

This works:

```<code>var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}
</code>```

This does not work

```<code>var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://localhost/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
</code>```

This also does not work, when loaded from http://localhost/webappFolder/Landing.do

```<code>var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}
</code>```

Title: Google Chrome "window.open" workaround?

Body:
I have been working on a web app and for part of it I need to open a new window. I have this working on all browsers, my sticking point is with Google Chrome.

Chrome seems to ignore the window features which is causing me issues, the thing I'm struggling with is I need the address bar to be editable within the new window. FF, IE, Safari and Opera do this fine, Chrome does not.

My Code:

function popitup(url) {
  newwindow=window.open(url, 'name', 'toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=1,resizable=1,width=800,height=600');
  if (window.focus) {
    newwindow.focus()
  }
  return false;
}

Body:
As far as I can tell, chrome doesn't work properly if you are referencing localhost (say, you're developing a site locally)

This works:

var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
}

This does not work

var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("http://localhost/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}

This also does not work, when loaded from http://localhost/webappFolder/Landing.do

var windowObjectReference;
var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

function openRequestedPopup() {
  windowObjectReference = window.open("/webappFolder/MapViewer.do", "CNN_WindowName", strWindowFeatures);
}