问:
Gson ignore json field and deserialize
I'm working with android and gson and i was wondering if i can ignore a field from the webservice.

this its my gson object

```<code>Gson gson = new GsonBuilder().serializeNulls().create();
</code>```

So what i need is to ignore validator field and deserialize to my custom bean in the following code.

Its any way to do that with gson ?

```<code>{ "posts":
  [

        {
       "username": "John",
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
        "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]
        }
      ,

        {
          "username": "Smith",
          "message": "I've been waiting",
          "time": "2010-4-6 10:30:26"
           "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]

       }
]}
</code>```

Thanks in advance

Cheers

答: You can call gson.fromJson(inputString, localObject) and if localObject doesn't declare a validator variable, it will just skip it.

Title: Gson ignore json field and deserialize

Body:
I'm working with android and gson and i was wondering if i can ignore a field from the webservice.

this its my gson object

Gson gson = new GsonBuilder().serializeNulls().create();

So what i need is to ignore validator field and deserialize to my custom bean in the following code.

Its any way to do that with gson ?

{ "posts":
  [

        {
       "username": "John",
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
        "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]
        }
      ,

        {
          "username": "Smith",
          "message": "I've been waiting",
          "time": "2010-4-6 10:30:26"
           "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]

       }
]}

Thanks in advance

Cheers


来源: stackexchange

问:
How send data from a component to a Module?
I have a component where I have flagPerfil variable, I need to send this variable to my module.

my service

```<code>export class ListUserService {
    public flagPerfil = boolean;
    changeFlagPerfil() {
        console.log('EEE' + this.flagPerfil);
        this.flagPerfil ? this.flagPerfil = false : this.flagPerfil = true;
    }
</code>```

component class:

```<code>@Component({
    selector: 'app-list-user',
    templateUrl: './list-user.component.html',
    styleUrls: ['./list-user.component.scss'],
    providers: [ListUserService]
})
export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }
</code>```

This is the view list-user.component.html

```<code><span *ngIf="!flagPerfil">
  <input type="button" id="usuarios" name="more" (click)="changeFlagPerfil()"
    value="Amigos">
</span>
</code>```

I have a module, I want to inject the service in the module, because
I need the FlagProfile variable

```<code>  @NgModule({
    imports: [
        IonicModule,
        CommonModule,
        FormsModule,
        RouterModule.forChild([{path: '', component: Tab1Page}])
    ],
    declarations: [Tab1Page, ListUserComponent, FriendsComponent]
})
export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        this.flagPerfil = listUserService.flagPerfil;
        console.log('FLAG', listUserService.flagPerfil);
    }
}
</code>```

How do I use an event Emit?

I need the module to automatically hear the changes of that variable

答:
You can pass the type to the Subject as shown in this tutorial for Subject, e.g. = new Subject<boolean>();

A similar question was asked here

Update: I fixed the formatting, which was preventing <boolean> from being displayed

ContentLicense: CC BY-SA 4.0

Body:
I have a component where I have flagPerfil variable, I need to send this variable to my module.

my service

export class ListUserService {
    public flagPerfil = boolean;
    changeFlagPerfil() {
        console.log('EEE' + this.flagPerfil);
        this.flagPerfil ? this.flagPerfil = false : this.flagPerfil = true;
    }

component class:

@Component({
    selector: 'app-list-user',
    templateUrl: './list-user.component.html',
    styleUrls: ['./list-user.component.scss'],
    providers: [ListUserService]
})
export class ListUserComponent implements OnInit {
    private flagPerfil = false;

    getFlag() {
        return this.flagPerfil;
    }

This is the view list-user.component.html

  <input type="button" id="usuarios" name="more" (click)="changeFlagPerfil()"
    value="Amigos">

I have a module, I want to inject the service in the module, because
I need the FlagProfile variable

  @NgModule({
    imports: [
        IonicModule,
        CommonModule,
        FormsModule,
        RouterModule.forChild([{path: '', component: Tab1Page}])
    ],
    declarations: [Tab1Page, ListUserComponent, FriendsComponent]
})
export class Tab1PageModule {
    public flagPerfil: boolean;

    constructor(private listUserService: ListUserService) {
        this.flagPerfil = listUserService.flagPerfil;
        console.log('FLAG', listUserService.flagPerfil);
    }
}

How do I use an event Emit?

I need the module to automatically hear the changes of that variable


问:
Create Zip File Fedora 17
Hi  I work with fedora 17 and I want to create zip file

There are four files in my directory /tmp/manager/

```<code>sos.prj
sos.shp
sos.shx
sbb.shh
</code>```

I want to  create zip file from    sos.prj,sos.shp,sos.shx files

I want to use grep. In other words, I want to create zip file from grep's result

Can anybody help me?

答: Perhaps the OP was thinking of using grep to find all the sos.* files but as @Impossibear says it's easier to just use a wildcard. If you want to focus on sos files, you could use zip myArchive sos.*

ContentLicense: CC BY-SA 3.0

Title: Create Zip File Fedora 17

Body:
Hi  I work with fedora 17 and I want to create zip file

There are four files in my directory /tmp/manager/

sos.prj
sos.shp
sos.shx
sbb.shh

I want to  create zip file from    sos.prj,sos.shp,sos.shx files

I want to use grep. In other words, I want to create zip file from grep's result

Can anybody help me?


问:
Is there a way to both destructure a function parameter, and keep a named reference to the parameter?
In react stateless functional components we'll commonly write something like this:

```<code>export function MyCompoment({
    title,
    foo,
    bar
}) {
    return <div> title: {title}, ...</div>
}
</code>```

Where we're immediately destructuring the props object into its variables.

Now I'm using a Material-UI makeStyles hook, and I'm also using TypeScript, and the way I'm currently using it looks like this.

```<code>const useStyles = makeStyles((theme : Theme ) =>({
     root: ({foo} : MyComponentProps) => ({
         content: foo
     })
});

interface MyComponentProps  {
    title: string;
    foo: string;
    bar: string;
}
export function MyCompoment({
    title,
    foo,
    bar
} : MyComponentProps) {
    const classes = useStyles({
        title,
        foo,
        bar
    });
    return <div> title: {title}, ...</div>
}
</code>```

And you can see the problem - I have to repeat the props variable names to pass into the classes.

The best way I can think to avoid this, is write it this way:

```<code>export function MyCompoment(props: MyComponentProps) {
    const {
       title,
       foo,
       bar
    }  = props;
    const classes = useStyles(props);
    return <div> title: {title}, ...</div>
}
</code>```

But that's a little messier than I was wanting.

I was wondering if it's possible to do something like:

```<code>export function MyCompoment({
       title,
       foo,
       bar
    }  = props : MyComponentProps) {

    const classes = useStyles(props);
    return <div> title: {title}, ...</div>
}
</code>```

Pretty picky I know, just wondering.

答:
Is there a way to both destructure a function parameter, and keep a named reference to the parameter?

No. You will need to do it two step as you have where you take the props as a single argument and then destructure them later.

Body:
In react stateless functional components we'll commonly write something like this:

export function MyCompoment({
    title,
    foo,
    bar
}) {
    return
 title: {title}, ...

}

Where we're immediately destructuring the props object into its variables.

Now I'm using a Material-UI makeStyles hook, and I'm also using TypeScript, and the way I'm currently using it looks like this.

const useStyles = makeStyles((theme : Theme ) =>({
     root: ({foo} : MyComponentProps) => ({
         content: foo
     })
});

interface MyComponentProps  {
    title: string;
    foo: string;
    bar: string;
}
export function MyCompoment({
    title,
    foo,
    bar
} : MyComponentProps) {
    const classes = useStyles({
        title,
        foo,
        bar
    });
    return
 title: {title}, ...

}

And you can see the problem - I have to repeat the props variable names to pass into the classes.

The best way I can think to avoid this, is write it this way:

export function MyCompoment(props: MyComponentProps) {
    const {
       title,
       foo,
       bar
    }  = props;
    const classes = useStyles(props);
    return
 title: {title}, ...

}

But that's a little messier than I was wanting.

I was wondering if it's possible to do something like:

export function MyCompoment({
       title,
       foo,
       bar
    }  = props : MyComponentProps) {

    const classes = useStyles(props);
    return
 title: {title}, ...

}

Pretty picky I know, just wondering.


问:
Logstash: Nothing displayed on console (Mac)
I am trying to set up a very simple logstash config

```<code>input {
  file {

    path => "/path/to/my/log/file"
    start_position => "beginning"
    ignore_older => 0
  }
}
filter {
}
output {
  stdout {
    codec => rubydebug
  }
}
</code>```

and here is how i start logstash

[logstash-7.1.1]$ bin/logstash -r -f log.conf

but here is all i see on the console

```<code>Sending Logstash logs to path/to/logstash-7.1.1/logs which is now configured via log4j2.properties
[2019-05-28T13:22:57,294][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2019-05-28T13:22:57,313][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.1.1"}
[2019-05-28T13:23:02,904][INFO ][logstash.javapipeline    ] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>8, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50, "pipeline.max_inflight"=>1000, :thread=>"#<Thread:0x7ad3cf30 run>"}
[2019-05-28T13:23:03,254][INFO ][logstash.inputs.file     ] No sincedb_path set, generating one based on the "path" setting {:sincedb_path=>"path/to/logstash-7.1.1/data/plugins/inputs/file/.sincedb_8164b23a475b43f1b0c9aba125f7f5cf", :path=>["/path/to/my/log/file"]}
[2019-05-28T13:23:03,284][INFO ][logstash.javapipeline    ] Pipeline started {"pipeline.id"=>"main"}
[2019-05-28T13:23:03,355][INFO ][filewatch.observingtail  ] START, creating Discoverer, Watch with file and sincedb collections
[2019-05-28T13:23:03,360][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
[2019-05-28T13:23:03,703][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
</code>```

i can see that

```<code>No sincedb_path set, generating one based on the "path" setting {:sincedb_path=>"path/to/logstash-7.1.1/data/plugins/inputs/file/.sincedb_8164b23a475b43f1b0c9aba125f7f5cf", :path=>["/path/to/my/log/file"]}
</code>```

so the path seems correct. Also, my log file is not empty.

What am i doing wrong? Why cant I see the content of my log file on the console?

答:
```<code>input {
  file {
    path => "/salaries.csv"
    start_position => "beginning"
    type => "data"
  }
}

filter {
  csv{
    separator => ","
  }
}

output {
  stdout {
    codec => rubydebug
  }
}
</code>```

This link may helpful to you

Body:
I am trying to set up a very simple logstash config

input {
  file {

    path => "/path/to/my/log/file"
    start_position => "beginning"
    ignore_older => 0
  }
}
filter {
}
output {
  stdout {
    codec => rubydebug
  }
}

and here is how i start logstash

[logstash-7.1.1]$ bin/logstash -r -f log.conf

but here is all i see on the console

Sending Logstash logs to path/to/logstash-7.1.1/logs which is now configured via log4j2.properties
[2019-05-28T13:22:57,294][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2019-05-28T13:22:57,313][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.1.1"}
[2019-05-28T13:23:02,904][INFO ][logstash.javapipeline    ] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>8, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50, "pipeline.max_inflight"=>1000, :thread=>"#<Thread:0x7ad3cf30 run>"}
[2019-05-28T13:23:03,254][INFO ][logstash.inputs.file     ] No sincedb_path set, generating one based on the "path" setting {:sincedb_path=>"path/to/logstash-7.1.1/data/plugins/inputs/file/.sincedb_8164b23a475b43f1b0c9aba125f7f5cf", :path=>["/path/to/my/log/file"]}
[2019-05-28T13:23:03,284][INFO ][logstash.javapipeline    ] Pipeline started {"pipeline.id"=>"main"}
[2019-05-28T13:23:03,355][INFO ][filewatch.observingtail  ] START, creating Discoverer, Watch with file and sincedb collections
[2019-05-28T13:23:03,360][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
[2019-05-28T13:23:03,703][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}

i can see that

No sincedb_path set, generating one based on the "path" setting {:sincedb_path=>"path/to/logstash-7.1.1/data/plugins/inputs/file/.sincedb_8164b23a475b43f1b0c9aba125f7f5cf", :path=>["/path/to/my/log/file"]}

so the path seems correct. Also, my log file is not empty.

What am i doing wrong? Why cant I see the content of my log file on the console?

Body:
input {
  file {
    path => "/salaries.csv"
    start_position => "beginning"
    type => "data"
  }
}

filter {
  csv{
    separator => ","
  }
}

output {
  stdout {
    codec => rubydebug
  }
}

This link may helpful to you


问:
IE Handling in Excel macros
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

```<code>Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub
</code>```

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">
```

答:
I think you need to search through all the elements returned by Document.All().  Try looping through the collection that is returned.  This is much easier if the control had an id, but you will have to check each element having a title = "Search for a template".  Once you have found the item you can set the text.

I suggest debugging so you can see what .All returns and then you can work from there.

Title: IE Handling in Excel macros

Body:
I am new to Excel macros and I am trying to auto-fill the text box and select the option from Dropdown and click on Submit.

Using macros I have navigated to a page and from the page, I need to enter the text in the text box, and based on the Suggestion, I need to select the option.

Once the option is selected I need to click on continue using macros.

Here is the current code (I tried with the commented line but it's not working).

Sub Create_Change()
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object
    Dim HWNDSrc As Long
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    URL = "URL to Navigate"
    IE.Navigate URL
    Application.StatusBar = URL & " is loading. Please wait..."
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
    Application.StatusBar = URL & " Loaded"
    ' IE.Document.All("Search for a template").Value = "text to search"
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing
End Sub

HTML CODE:

<input title="Search for a template"
       class="change-template__search-input ng-pristine ng-untouched ng-valid"
       role="combobox"
       aria-expanded="false"
       aria-owns="typeahead-258-8737"
       aria-autocomplete="list"
       type="text"
       placeholder="Search for a template"
       ng-enter="getRecommendedTemplates(template.search)"
       ng-model="template.search"
       typeahead="template as template for template in getTemplateList($viewValue)"
       typeahead-focus-first="false"
       typeahead-on-select="getRecommendedTemplates($item)"
       typeahead-min-length="3">


问:
How to re-submit HTML form
EDIT: I made a dumb mistake. I was using some legacy code where start was greyed out after it was clicked. It's all fixed now. Lesson learned: parse through your code line by line if your file is small enough.

I have a form in html that calls a function titled callStopwatch() in javascript. Upon submitting the form for the first time, the function executes just fine. However, clicking the submit button another time doesn't do anything. Refreshing the page solves the problem, but I would like to be able to click on submit and return callStopwatch() multiple times without having to refresh. What am I doing wrong?

HTML:

```<code><form id="options" action="" onsubmit="return callStopwatch()" method="post">

<fieldset>

<label> foo:

<input type="text" class="textForm" name="foo" size="2" /> foo1

</label>

<input type="submit" id="submit" class="button" alt="start" value="Start" />

<input type="reset" id="clear" class="button" alt="clear" value="Clear" />

<input type="button" id="reset" class="button" alt="reset" value="Reset" />

</fieldset>

</form>

</code>```

JS:

```<code>var isRunning = false; // flag purposes

function callStopwatch() {
    var timer = document.getElementById('timer');
    var toggleBtn = document.getElementById('submit');
    var resetBtn = document.getElementById('reset');
    var clearBtn = document.getElementById('clear');

    watch = new Stopwatch(timer);
    watch.start();
    isRunning = true;

    resetBtn.addEventListener('click', function() {
        watch.stop();
        watch.reset();
        document.getElementById("submit").disabled = false;
    });

    clearBtn.addEventListener('click', function() {
        watch.stop();
        watch.reset();
        document.getElementById("submit").disabled = false;
    });
}

navigator.mediaDevices.getUserMedia({ audio: true})
---more code here---
    .then(function(stream) {
            if(arbitrary_condition = true){
                watch.stop();
                isRunning = false;
            }
})
</code>```

I know the above is a lot of code. I don't know where to look for the problem. The form should run my stopwatch again when I click submit, although it does not. Clicking reset then start behaves just fine, but I want to be able to click start without resetting.

Edit: I tried adding another eventlistener for the start button but it didn't work as expected. Maybe I did it wrong though.

答:
I don't know if this is your problem, but this:

```<code>if(arbitrary_condition = true)
</code>```

is almost certainly not what you want to be doing (= for assignment, == or === for comparison)

Title: How to re-submit HTML form

Body:
EDIT: I made a dumb mistake. I was using some legacy code where start was greyed out after it was clicked. It's all fixed now. Lesson learned: parse through your code line by line if your file is small enough.

I have a form in html that calls a function titled callStopwatch() in javascript. Upon submitting the form for the first time, the function executes just fine. However, clicking the submit button another time doesn't do anything. Refreshing the page solves the problem, but I would like to be able to click on submit and return callStopwatch() multiple times without having to refresh. What am I doing wrong?

HTML:

<form id="options" action="" onsubmit="return callStopwatch()" method="post">

<fieldset>

 foo:

<input type="text" class="textForm" name="foo" size="2" /> foo1

<input type="submit" id="submit" class="button" alt="start" value="Start" />

<input type="reset" id="clear" class="button" alt="clear" value="Clear" />

<input type="button" id="reset" class="button" alt="reset" value="Reset" />

</fieldset>

</form>

JS:

var isRunning = false; // flag purposes

function callStopwatch() {
    var timer = document.getElementById('timer');
    var toggleBtn = document.getElementById('submit');
    var resetBtn = document.getElementById('reset');
    var clearBtn = document.getElementById('clear');

    watch = new Stopwatch(timer);
    watch.start();
    isRunning = true;

    resetBtn.addEventListener('click', function() {
        watch.stop();
        watch.reset();
        document.getElementById("submit").disabled = false;
    });

    clearBtn.addEventListener('click', function() {
        watch.stop();
        watch.reset();
        document.getElementById("submit").disabled = false;
    });
}

navigator.mediaDevices.getUserMedia({ audio: true})
---more code here---
    .then(function(stream) {
            if(arbitrary_condition = true){
                watch.stop();
                isRunning = false;
            }
})

I know the above is a lot of code. I don't know where to look for the problem. The form should run my stopwatch again when I click submit, although it does not. Clicking reset then start behaves just fine, but I want to be able to click start without resetting.

Edit: I tried adding another eventlistener for the start button but it didn't work as expected. Maybe I did it wrong though.

Body:
I don't know if this is your problem, but this:

if(arbitrary_condition = true)

is almost certainly not what you want to be doing (= for assignment, == or === for comparison)


问:
How to use a nested query to update a value in another table?
I have a table (TablevVariables) which stores the last file updated date, the latest log date imported, etc, which is basically storing the values so that that the duplicate data import won't happen if the tool run multiple times a day.

So each day, the logs will be appended to a log archive table which will be used later for other historical data analysis. Then update the TableVariables.Keyvalue=<latest date of the log file>.

Update Template:

```<code>UPDATE my_table SET my_column='new value' WHERE something='some value';
</code>```

My Update Query:

```<code>UPDATE TablevVariables SET [TablevVariables].KeyValue =
    (SELECT Max([xxxx_Archived_Log].[年月日]) FROM xxxx_Archived_Log)
WHERE [TablevVariables].KeyName="xxxx_Archived_Log";
</code>```

When I try to execute this query, access throws the error that "Operation must use an updatable query".

答:
While waiting for guidance, I used a work around for this issue. Assigned the value to a variable and then passed it in a normal query.</p>

```<code>txtSQLcmd = "SELECT Max([年月日]) FROM xxxx_Archived_Log;"
dtDateValue = DateValue(FetchAValueFromTable(txtSQLcmd))
txtSQLcmd = "UPDATE TablevVariables SET [TablevVariables].KeyValue = #" & dtDateValue & "# WHERE [TablevVariables].KeyName='xxxx_Archived_Log';"
ExecuteSQLcmd (txtSQLcmd)

Function FetchAValueFromTable(ByVal strSQL As String) As String
Dim cnn1 As ADODB.Connection
Set cnn1 = CurrentProject.Connection
Dim myRecordSet As New ADODB.Recordset
myRecordSet.ActiveConnection = cnn1
myRecordSet.CursorType = adOpenDynamic
myRecordSet.LockType = adLockOptimistic
myRecordSet.Open strSQL
FetchAValueFromTable = myRecordSet.Fields(0).Value
myRecordSet.Close
Set myRecordSet = Nothing
Set cnn1 = Nothing
End Function

Function ExecuteSQLcmd(ByVal strSQL As String)
   DoCmd.RunSQL strSQL
End Function
</code>```

Body:
I have a table (TablevVariables) which stores the last file updated date, the latest log date imported, etc, which is basically storing the values so that that the duplicate data import won't happen if the tool run multiple times a day.

So each day, the logs will be appended to a log archive table which will be used later for other historical data analysis. Then update the TableVariables.Keyvalue=<latest date of the log file>.

Update Template:

UPDATE my_table SET my_column='new value' WHERE something='some value';

My Update Query:

UPDATE TablevVariables SET [TablevVariables].KeyValue =
    (SELECT Max([xxxx_Archived_Log].[年月日]) FROM xxxx_Archived_Log)
WHERE [TablevVariables].KeyName="xxxx_Archived_Log";

When I try to execute this query, access throws the error that "Operation must use an updatable query".

Body:
While waiting for guidance, I used a work around for this issue. Assigned the value to a variable and then passed it in a normal query.

txtSQLcmd = "SELECT Max([年月日]) FROM xxxx_Archived_Log;"
dtDateValue = DateValue(FetchAValueFromTable(txtSQLcmd))
txtSQLcmd = "UPDATE TablevVariables SET [TablevVariables].KeyValue = #" & dtDateValue & "# WHERE [TablevVariables].KeyName='xxxx_Archived_Log';"
ExecuteSQLcmd (txtSQLcmd)

Function FetchAValueFromTable(ByVal strSQL As String) As String
Dim cnn1 As ADODB.Connection
Set cnn1 = CurrentProject.Connection
Dim myRecordSet As New ADODB.Recordset
myRecordSet.ActiveConnection = cnn1
myRecordSet.CursorType = adOpenDynamic
myRecordSet.LockType = adLockOptimistic
myRecordSet.Open strSQL
FetchAValueFromTable = myRecordSet.Fields(0).Value
myRecordSet.Close
Set myRecordSet = Nothing
Set cnn1 = Nothing
End Function

Function ExecuteSQLcmd(ByVal strSQL As String)
   DoCmd.RunSQL strSQL
End Function


问:
Saving large Pandas df of text data to disk crashes Colab due to using up all RAM. Is there a workaround?
I have a very large Pandas dataframe that I would like to save to disk to use later. The dataframe only contains string data.

However, no matter what format I use, the saving process crashes my Google Colab enviroment due to using up all available RAM, except CSV, which doesn't complete even after 5 hours.

but that also crashes the enviroment.

Is there a workaround to saving a large text pandas dataframe to disk?

I have tried to_json, to_feather, to_parquet, to_pickle, and they all crash the enviroment.

I also tried to_sql by using

```<code>from sqlalchemy import create_engine
engine = sqlalchemy.create_engine("sqlite:///database.db")
df.to_sql("table", engine)
</code>```

I would like to save my dataframe to disk within a reasonable time without crashing the enviroment.

答:
Instead of using Pandas method "to_csv()", use Dask Dataframe to write the csv file; it will be quicker than pandas method.
Dask write function will break your file into mulitple chuncks and store it.
Code:

```<code>#Reading file
import dask.dataframe as dd

df = dd.from_pandas(pd.DataFrame(load_boston().data),npartitions=10)

def operation(df):
   df['new'] = df[0]
   return df[['new']]

#Writing the file
df.pipe(operation).to_csv('boston*.csv')
</code>```

NOTE: Install Dask package before use:

Using Conda:

```<code>conda install -c conda-forge dask
</code>```

Using pip:

```<code>pip install "dask[complete]"    # Install everything
</code>```

References:

[1] https://docs.dask.org/en/latest/install.html

[2] https://gist.github.com/hussainsultan/f7c2fb9f11008123bda405c5b024a79f

Body:
I have a very large Pandas dataframe that I would like to save to disk to use later. The dataframe only contains string data.

However, no matter what format I use, the saving process crashes my Google Colab enviroment due to using up all available RAM, except CSV, which doesn't complete even after 5 hours.

but that also crashes the enviroment.

Is there a workaround to saving a large text pandas dataframe to disk?

I have tried to_json, to_feather, to_parquet, to_pickle, and they all crash the enviroment.

I also tried to_sql by using

from sqlalchemy import create_engine
engine = sqlalchemy.create_engine("sqlite:///database.db")
df.to_sql("table", engine)

I would like to save my dataframe to disk within a reasonable time without crashing the enviroment.

Body:
Instead of using Pandas method "to_csv()", use Dask Dataframe to write the csv file; it will be quicker than pandas method.
Dask write function will break your file into mulitple chuncks and store it.
Code:

#Reading file
import dask.dataframe as dd

df = dd.from_pandas(pd.DataFrame(load_boston().data),npartitions=10)

def operation(df):
   df['new'] = df[0]
   return df[['new']]

#Writing the file
df.pipe(operation).to_csv('boston*.csv')

NOTE: Install Dask package before use:

Using Conda:

conda install -c conda-forge dask

Using pip:

pip install "dask[complete]"    # Install everything

References:

[1] https://docs.dask.org/en/latest/install.html

[2] https://gist.github.com/hussainsultan/f7c2fb9f11008123bda405c5b024a79f


问:
Formatting csv file with python
I have a csv file with the following structure:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"
</code>```

I need him to stay like this:

```<code>"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"
</code>```

I received this .csv file from someone else, so I do not know how the conversion was done. I am trying unsuccessfully with the code below:

```<code>input_fd = open("/home/gustavo/Downloads/Redes/Despesas/csvfile.csv", 'r')
output_fd = open('dados_2018_1.csv', 'w')
for line in input_fd.readlines():
    line.replace("\"","")
    output_fd.write(line)
    input_fd.close()
output_fd.close()
</code>```

Is it possible to make this change or will I have to do the conversion from an xml file to a csv, and make this change during the conversion?

答:
A couple things.  First, you do NOT have a csv file because in a csv file, the delimiter is a comma by definition.  I'm assuming you want the values in your data file to (1) remain separated by semicolons [why not fix it and make it commas?] and (2) you want each value to be in quotation marks.

If so, I think this will work:

```<code># data reader

in_file = 'data.txt'
out_file = 'fixed.txt'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
        # split by semicolon
        data = line.strip().split(';')
        # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            output.write(''.join(['"', item, '"',';']))
        # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()
</code>```

If your target user is python, you should consider replacing the semicolons with commas (correct csv format) and forgoing the quotes.  Everything python reads from csv is taken in as string anyhow.

Title: Formatting csv file with python

Body:
I have a csv file with the following structure:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE;1;1;2015;PP"

I need him to stay like this:

"txNomeParlamentar";"ideCadastro";"nuCarteiraParlamentar";"nuLegislatura";"sgUF"
"AVANTE";"1";"1";"2015";"PP"

I received this .csv file from someone else, so I do not know how the conversion was done. I am trying unsuccessfully with the code below:

input_fd = open("/home/gustavo/Downloads/Redes/Despesas/csvfile.csv", 'r')
output_fd = open('dados_2018_1.csv', 'w')
for line in input_fd.readlines():
    line.replace("\"","")
    output_fd.write(line)
    input_fd.close()
output_fd.close()

Is it possible to make this change or will I have to do the conversion from an xml file to a csv, and make this change during the conversion?

Body:
A couple things.  First, you do NOT have a csv file because in a csv file, the delimiter is a comma by definition.  I'm assuming you want the values in your data file to (1) remain separated by semicolons [why not fix it and make it commas?] and (2) you want each value to be in quotation marks.

If so, I think this will work:

# data reader

in_file = 'data.txt'
out_file = 'fixed.txt'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
        # split by semicolon
        data = line.strip().split(';')
        # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            output.write(''.join(['"', item, '"',';']))
        # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()

If your target user is python, you should consider replacing the semicolons with commas (correct csv format) and forgoing the quotes.  Everything python reads from csv is taken in as string anyhow.


问:
(Android) Draw image outside the view class (canvas access?)
I'd like to make a Library containing an override class of View(eg: MyView extends View)
and want to make a method "Draw(String FileName)".

So what I ultimately want to do is to simply import this library and call this "Draw(String FileName)" method to draw an image from other activities.

I've tried by myself, but I encountered some problem with accessing main Canvas which onDraw() method actually has.

It would be easy if I just draw every image in onDraw() method function,
but I have no idea how to put things from outside the class.

any idea for this structure?

答:
OK, I solved my problem but I'm not sure this is the best way.

I made an interface call back function inside the class which inherits View,
and I could access the Draw() method by using that call back.

ContentLicense: CC BY-SA 2.5


问:
How to target multiple remote nodes in WQL?
I'm creating a service in C# that polls remote hosts in an Active Directory domain on a regular interval with WMI. I've been using the System.Management.ManagementObjectSearcher but so far I've only gotten it to work with the local host.

Example:

private List<Disk> GetDisks()
{
    var disks = new List<Disk>();

    var searcher = new ManagementObjectSearcher("select deviceid, volumename, description, filesystem, freespace, size from win32_logicaldisk");
    foreach (var obj in searcher.Get())
    {
        var id = obj.Properties["deviceid"].Value.ToString();
        var name = obj.Properties["volumename"].Value.ToString();
        var description = obj.Properties["description"].Value.ToString();
        var fileSystem = obj.Properties["filesystem"].Value.ToString();
        var freeSpace = Convert.ToUInt64(obj.Properties["freespace"].Value);
        var totalSpace = Convert.ToUInt64(obj.Properties["size"].Value);

        var disk = new Disk(id, name, description, fileSystem, freeSpace, totalSpace);

        disks.Add(disk);
    }

    return disks;
}
```

<p>However, I have a list of machine hostnames that I need to poll. This can easily be done with WMIC like so:</p>

```wmic /node:"hostname1","hostname2","hostname3" logicaldisk get deviceid, volumename, description, filesystem, freespace, size /format:list
```

but I cannot figure out how to do it in C#.

Any help greatly appreciated.

答:
You can use ORMi to create multiple WMI connections and get the info you need.

You could do something like this:

```<code>//Supposing you got the info on a list of computers

List<Computer> computers = new List<Computers>();

foreach(Computer c in computers)
{
    WMIHelper helper = new WMIHelper("root\\CimV2", c.WorkstationName);

    var info = helper.Query("select deviceid, volumename, description, filesystem, freespace, size from win32_logicaldisk").ToList();
}
</code>```

Refer to the documentation for more specific data.

Body:
I'm creating a service in C# that polls remote hosts in an Active Directory domain on a regular interval with WMI. I've been using the System.Management.ManagementObjectSearcher but so far I've only gotten it to work with the local host.

Example:

private List<Disk> GetDisks()
{
    var disks = new List<Disk>();

    var searcher = new ManagementObjectSearcher("select deviceid, volumename, description, filesystem, freespace, size from win32_logicaldisk");
    foreach (var obj in searcher.Get())
    {
        var id = obj.Properties["deviceid"].Value.ToString();
        var name = obj.Properties["volumename"].Value.ToString();
        var description = obj.Properties["description"].Value.ToString();
        var fileSystem = obj.Properties["filesystem"].Value.ToString();
        var freeSpace = Convert.ToUInt64(obj.Properties["freespace"].Value);
        var totalSpace = Convert.ToUInt64(obj.Properties["size"].Value);

        var disk = new Disk(id, name, description, fileSystem, freeSpace, totalSpace);

        disks.Add(disk);
    }

    return disks;
}

However, I have a list of machine hostnames that I need to poll. This can easily be done with WMIC like so:

wmic /node:"hostname1","hostname2","hostname3" logicaldisk get deviceid, volumename, description, filesystem, freespace, size /format:list

but I cannot figure out how to do it in C#.

Any help greatly appreciated.

Body:
You can use ORMi to create multiple WMI connections and get the info you need.

You could do something like this:

//Supposing you got the info on a list of computers

List<Computer> computers = new List<Computers>();

foreach(Computer c in computers)
{
    WMIHelper helper = new WMIHelper("root\\CimV2", c.WorkstationName);

    var info = helper.Query("select deviceid, volumename, description, filesystem, freespace, size from win32_logicaldisk").ToList();
}

Refer to the documentation for more specific data.


问:
How can show alert message in node.js
what should i do ?? I work on node.js . I can not use alert("sometext");

```<code>MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({Email:  req.body.email} , function(err, result) {
  if (result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      window.alert("sometext");
    });
    db.close();
  });
});
</code>```

output = ReferenceError: window is not defined

答:
NodeJS runs on the console of the given operating system, that said, window.alert is actually a browser API command, you cannot use it, as alternatives, you can:

Use console.log that will output information on the STDOUT(Aka the standard output, aka will just print on the console).

Use console.error, that will do exactly the same as above, but will pipe the content to STDERR, that can be usefull for logging or process output identification purposes.

Wrap your Node application on a container like Electron, that, to be honest, is overkill.

And finally, calling the native dialog API from your OS:

To call a native dialog, you need acess to the OS native libraries, you can do that using the Node FFI module that allows you to bind those libraries.
Or, for the sake of simplicity, just use one of existing implementations of that function, like: node-native-dialog, mitsobox or dialog.

Disclaimer: I did not develop or can attest the quality of those
  modules, use at your own risk, if native dialogs are really required
  to your development, implement your own binding of the OS libraries.

Title: How can show alert message in node.js

Body:
what should i do ?? I work on node.js . I can not use alert("sometext");

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({Email:  req.body.email} , function(err, result) {
  if (result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      window.alert("sometext");
    });
    db.close();
  });
});

output = ReferenceError: window is not defined


问:
Connect MongoDB to NodeJS on GAE
I'm running a NodeJS app on GAE and I want to connect to a mongodb cluster on Atlas.

I have white-listed my IP on atlas and established a connection. All work fine on my local machine.

When deployed my app on GAE it could not connect to Atlas since the IP is not white-listed. When I white-listed all IPs on Atlas I could make a connection and everything worked fine as on my local machine

I cannot assign a static-IP to a standard GAE app, therefore I must allow access from anywhere to my cluster on Atlas, which is probably a bad idea.

What would be best solution to work with mongoDB from a GAE standard app?
Any configuration I can make to Atlas? maybe switching to mLab? or any other ideas?

答: App Engine applications do not have fixed IP addresses. I'm not very familiar with MongoDB Atlas, but it does look like it offers an option to run on GCP and if that runs on a Compute Engine instance what you might be able to do is use the VPC Connector to enable access between your app and your MongoDB setup.</p>

Title: Connect MongoDB to NodeJS on GAE


问:
Xcode 8 A valid provisioning profile for this executable was not found
I know there are other questions asked like this here but I've followed all their solutions yet still end up with this error message.

I have a valid Apple Developer account with program active.

I have tried using managed and unmanaged provisioning with new/fresh bundle ID's (which get recreated provisioning profiles).

I have tried this: A valid provisioning profile for this executable was not found for debug mode

I have tried this: XCode :7 App installation failed :A valid provisioning profile for this executable was not found

I have deleted any old versions of the app from my phone.

I have confirmed my device ID on the developer portal is the same as in Xcode (was also useful for manual provisioning profile management to confirm)

I even tried another developer ID I have out of sheer desperation and yet the same error appears.

I even get this error when building for release scheme with my valid distribution certificate.

I've spent a ton of time trying to figure this out now I'm hoping someone else has felt my pain and actually solved this.

UPDATE: Adding screenshots for usefulness

UPDATE 2: I gave up trying to solve this problem, I created a new project and copied source files into the new project and I now have it working. Clearly something in the project configuration/settings files got corrupted somehow in the previous project which no obvious fix available. Will leave this question open, perhaps someone has a solution eventually. I have my old 'non-working' project so will continue to try those just for curiousities sake.

Before this error message, Build Succeeded is shown.

答:
I had edited my app scheme Build Configuration from Debug to Release, and unchecked the Debug Executable.

I am not sure why, but if it makes a difference my signing details for Debug and Release were different. So after I reset those back to Debug and checked back the Debug Executable box, and all was fine again.

Edit: found out it was because I was trying to run release mode on my phone via App Store provisioning profile and App Store profile doesn't allow this. I switched to Ad Hoc and there is no more issues.


问:
Products values not sending to addProduct page using php ajax
I am creating simple ecmommerce webisite while I am going to add products to card I couldn’t send the values through ajex.i have tried to send  'frmProduct' values to 'addproduct.php' page.  While I checking using echo echo $product_name = $_POST['des']; ,echo   $price = $_POST['price'];
    echo  $qty= $_POST['qty'];  only 'qty'   Value  sent successfully other fields are not sent to
 'addproduct.php' page

```<code> $.ajax({
            type: 'GET',
            url: 'all_product.php' ,
            dataType: 'JSON',
            success: function (data) {
                for (var i = 0; i < data.length; i++)
                {
                    var price = data[i].price;
                        var image = data[i].image;
                        var description = data[i].description;

    $("#Products").append("<form class='form-horizontal' id='frmProduct'>" +

           "<div class='col-md-4'> " +
                                  "<div class='panel panel-info' id='Products'>" +
                                  "<div class='card-body'>" +
                                  "<div class='panel-heading' id='des' "  +  "<h4> "  +  description + "</h4> " +
                                   "<p class='panel-body' id='price'>"+  "<h3> "  +  price + "</h3> "  +
                                    "<p class='panel-body'> " +
                                    "<img class='card-img-top' style='width:150px' height='150px' id='theImg' src='images/"  + image  + "' /> </p>" +
                                      "<input type='text' name='qty' id='qty'>" +
                                      "</br></br>" +
                                    " <Button type='button' class='btn btn-primary' onclick='addProduct()' >View More</a> " +

            "</div> " +
            "</div>" +
            "</div>" +
            " </div>" +
            "</form>");

        }
    },
</code>```

$.ajax({

```<code>type : 'POST',
data : $("#'frmProduct'").serialize(),
url : 'addproduct.php',
dataType : 'JSON',
success : function(data){
</code>```

}

addproduct.php page

```<code><?php
include("db.php");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo   $product_name = $_POST['des'];
    echo   $price = $_POST['price'];
    echo  $qty= $_POST['qty'];
    $stmt = $conn->prepare("insert into cart (productname,price,qty)values(?,?,?)");
    $stmt-> bind_param("sss",$productname,$price,$qty);
    if($stmt->execute())
    {
        echo 1;
    }
    else
    {
        echo 0;
    }
    $stmt->close();
}
?>
</code>```

答:
Your form is not passing anything else other than qty. Elements like
,
 and so on are not passed when the form is submitted.
If you need to pass these values without showing them to the user in an actual input field, use <input type="hidden" name="des" value="123">, for example.

Body:
I am creating simple ecmommerce webisite while I am going to add products to card I couldn’t send the values through ajex.i have tried to send  'frmProduct' values to 'addproduct.php' page.  While I checking using echo echo $product_name = $_POST['des']; ,echo   $price = $_POST['price'];
    echo  $qty= $_POST['qty'];  only 'qty'   Value  sent successfully other fields are not sent to
 'addproduct.php' page

 $.ajax({
            type: 'GET',
            url: 'all_product.php' ,
            dataType: 'JSON',
            success: function (data) {
                for (var i = 0; i < data.length; i++)
                {
                    var price = data[i].price;
                        var image = data[i].image;
                        var description = data[i].description;

    $("#Products").append("<form class='form-horizontal' id='frmProduct'>" +

           "
 " +
                                  "
" +
                                  "
" +
                                  "<div class='panel-heading' id='des' "  +  "
 "  +  description + "
 " +
                                   "
"+  "
 "  +  price + "
 "  +
                                    "
 " +
                                    "
" +
                                      "<input type='text' name='qty' id='qty'>" +
                                      "

" +
                                    " <Button type='button' class='btn btn-primary' onclick='addProduct()' >View More " +

            "
 " +
            "
" +
            "
" +
            "
" +
            "</form>");

        }
    },

$.ajax({

type : 'POST',
data : $("#'frmProduct'").serialize(),
url : 'addproduct.php',
dataType : 'JSON',
success : function(data){

}

addproduct.php page

<?php
include("db.php");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo   $product_name = $_POST['des'];
    echo   $price = $_POST['price'];
    echo  $qty= $_POST['qty'];
    $stmt = $conn->prepare("insert into cart (productname,price,qty)values(?,?,?)");
    $stmt-> bind_param("sss",$productname,$price,$qty);
    if($stmt->execute())
    {
        echo 1;
    }
    else
    {
        echo 0;
    }
    $stmt->close();
}
?>

Body:
Your form is not passing anything else other than qty. Elements like <div>, <p> and so on are not passed when the form is submitted.
If you need to pass these values without showing them to the user in an actual input field, use <input type="hidden" name="des" value="123">, for example.


问:
Split a text with regex in Java
I need to get a text splitted with regex in  Java (each substring will be less than or close to 10 characters (including space and special) and no word would be splitted). For example, "James has gone out for a meal." would be "James has", "gone out", "for a meal", ".".
Thanks in advance.</p>

答:
This expression might be a little complicated, maybe we could start with:

```<code>.{1,10}[^\s](?=\s|$)
</code>```

DEMO

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = ".{1,10}[^\\s](?=\\s|$)";
final String string = "James has gone out for a meal.";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

Title: Split a text with regex in Java

Body:
This expression might be a little complicated, maybe we could start with:

.{1,10}[^\s](?=\s|$)

DEMO

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = ".{1,10}[^\\s](?=\\s|$)";
final String string = "James has gone out for a meal.";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx Circuit

jex.im visualizes regular expressions:


答:
You could use the csv module to do it if you massage the input data a little first.

```<code>import csv

#input_csv = '/home/gustavo/Downloads/Redes/Despesas/csvfile.csv'
input_csv = 'gustavo_input.csv'
output_csv = 'dados_2018_1.csv'

with open(input_csv, 'r', newline='') as input_fd, \
     open(output_csv, 'w', newline='') as output_fd:

    reader = csv.DictReader(input_fd, delimiter=';')
    writer = csv.DictWriter(output_fd, delimiter=';',
                            fieldnames=reader.fieldnames,
                            quoting=csv.QUOTE_ALL)

    first_field = reader.fieldnames[0]
    for row in reader:
        fields = row[first_field].split(';')
        newrow = dict(zip(reader.fieldnames, fields))
        writer.writerow(newrow)

print('done')
</code>```

Title: Formatting csv file with python

Body:
You could use the csv module to do it if you massage the input data a little first.

import csv

#input_csv = '/home/gustavo/Downloads/Redes/Despesas/csvfile.csv'
input_csv = 'gustavo_input.csv'
output_csv = 'dados_2018_1.csv'

with open(input_csv, 'r', newline='') as input_fd, \
     open(output_csv, 'w', newline='') as output_fd:

    reader = csv.DictReader(input_fd, delimiter=';')
    writer = csv.DictWriter(output_fd, delimiter=';',
                            fieldnames=reader.fieldnames,
                            quoting=csv.QUOTE_ALL)

    first_field = reader.fieldnames[0]
    for row in reader:
        fields = row[first_field].split(';')
        newrow = dict(zip(reader.fieldnames, fields))
        writer.writerow(newrow)

print('done')


问:
RedirectToAction not calling action
Why is it that the Index action is not calling Foo on the RedirectToAction? I put a breakpoint and it doesn't seem to be hitting this action. It should be noted that my modelstate is valid so that is not the issue.</p>

```<code>    [HttpPost]
    public ActionResult Index(Home model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        TempData["model"] = model;
        return RedirectToAction("Foo");
    }

    public ActionResult Foo()
    {
        Home model = (Home)TempData["model"];
        return View();
    }
</code>```

答:
if you are using the Same controller Alternatively if you don't want a redirect
Just return view. because I checked your code in my Demo Application and try to reproduce your issue. but Your code working fine

```<code>[HttpPost]
    public ActionResult Index(Home model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        TempData["model"] = model;
        return View("Foo");
    }
</code>```

If it is not working then you may check your routes and make sure there are no special Routes define that could make things break.
 Or inside your Global.asax add this method and debug .

```<code>protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
}
</code>```

Title: RedirectToAction not calling action

Body:
Why is it that the Index action is not calling Foo on the RedirectToAction? I put a breakpoint and it doesn't seem to be hitting this action. It should be noted that my modelstate is valid so that is not the issue.

    [HttpPost]
    public ActionResult Index(Home model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        TempData["model"] = model;
        return RedirectToAction("Foo");
    }

    public ActionResult Foo()
    {
        Home model = (Home)TempData["model"];
        return View();
    }

Body:
if you are using the Same controller Alternatively if you don't want a redirect
Just return view. because I checked your code in my Demo Application and try to reproduce your issue. but Your code working fine

[HttpPost]
    public ActionResult Index(Home model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        TempData["model"] = model;
        return View("Foo");
    }

If it is not working then you may check your routes and make sure there are no special Routes define that could make things break.
 Or inside your Global.asax add this method and debug .

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
}


问:
PermGen Out of Memory reasons
I constantly detect OOM in PermGen for my environment:

java 6

jboss-4.2.3

Not a big web-application

I know about String.intern() problem - but I don't have enough valuable usage of it.
Increasing of MaxPermGen size didn't take a force (from 128 Mb to 256 Mb).

What other reasons could invoke OOM for PermGen?
What scenario of investigation is the best in such situation (strategy, tools and etc.)?

Thanks for any help

答:
See this note

Put JDBC driver in common/lib (as tomcat documentation says) and not in WEB-INF/lib

Don't put commons-logging into WEB-INF/lib since tomcat already bootstraps it

new class objects get placed into the PermGen and thus occupy an ever increasing amount of space. Regardless of how large you make the PermGen space, it will inevitably top out after enough deployments. What you need to do is take measures to flush the PermGen so that you can stabilize its size. There are two JVM flags which handle this cleaning:

```<code>-XX:+CMSPermGenSweepingEnabled
</code>```

This setting includes the PermGen in a garbage collection run. By default, the PermGen space is never included in garbage collection (and thus grows without bounds).

```<code>-XX:+CMSClassUnloadingEnabled
</code>```

This setting tells the PermGen garbage collection sweep to take action on class objects. By default, class objects get an exemption, even when the PermGen space is being visited during a garabage collection.

Title: PermGen Out of Memory reasons

Body:
See this note

Put JDBC driver in common/lib (as tomcat documentation says) and not in WEB-INF/lib

Don't put commons-logging into WEB-INF/lib since tomcat already bootstraps it

new class objects get placed into the PermGen and thus occupy an ever increasing amount of space. Regardless of how large you make the PermGen space, it will inevitably top out after enough deployments. What you need to do is take measures to flush the PermGen so that you can stabilize its size. There are two JVM flags which handle this cleaning:

-XX:+CMSPermGenSweepingEnabled

This setting includes the PermGen in a garbage collection run. By default, the PermGen space is never included in garbage collection (and thus grows without bounds).

-XX:+CMSClassUnloadingEnabled

This setting tells the PermGen garbage collection sweep to take action on class objects. By default, class objects get an exemption, even when the PermGen space is being visited during a garabage collection.


问:
Is it advisable to add to the global window object?
So I'm working a React/Typescript project, where I need to store a value for the number of rows that needs to be accessible globally.

Is it a good idea to define it on the window object?

```<code>window.MySpace = {};
MySpace.rowCount = 10;
</code>```

Are there any issues that could arise as the project grows? Or is there a more elegant way of handling this through Typescript?

Thanks!

edit:

Declare it as a module in a module.ts file

```<code>export module Global {
    export const rowCount = 10;
}
</code>```

Then import it to whichever file requires the value of rowCount.

答:
where I need to store a value for the number of rows that needs to be accessible globally

If you have to have to globally then ofcourse you would put it on window. The biggest concern would be naming MySpace conflict.

Rethink

However you probably don't need it globally, and really you should use a module.

Body:
So I'm working a React/Typescript project, where I need to store a value for the number of rows that needs to be accessible globally.

Is it a good idea to define it on the window object?

window.MySpace = {};
MySpace.rowCount = 10;

Are there any issues that could arise as the project grows? Or is there a more elegant way of handling this through Typescript?

Thanks!

edit:

Declare it as a module in a module.ts file

export module Global {
    export const rowCount = 10;
}

Then import it to whichever file requires the value of rowCount.


问:
Plotting data dynamically in the Matlab figure
Just to explain what I am facing, I have the following code.

```<code>ind=(1:10);
A=[sin(ind);cos(ind);tan(ind);sec(ind)]';
plot(ind,A(:,1),ind,A(:,2),ind,A(:,3),ind,A(:,4));
</code>```

the result looks like this:

Now, in my real program, the matrix A gets updated every few seconds with new rows. And I want to update the graph dynamically as soon as I get a new row. After some googling I realized that I have to use drawnow, but not sure how.

I have the following code as of now.

```<code>B=A(1,:);
h = plot(B,'YDataSource','B');
for k = 1:size(A,1)
   B=A(1:k,:);
   refreshdata(h,'caller')
   drawnow
   pause(.25)
end
</code>```

But I get the following error on this:

Error using refreshdata (line 70) Could not refresh YData from 'B'.

Error in test (line 9)    refreshdata(h,'caller')

Please help.

答:
I solved it after some more googling. The following code does, what I wanted:

```<code>ind=(1:10);
A=[sin(ind);cos(ind);tan(ind);sec(ind)]';
plots=plot(ind(1,1),A(1,1),ind(1,1),A(1,2),ind(1,1),A(1,3),ind(1,1),A(1,4));
for k = 1:size(plots,1)
   set(plots, {'XData'}, {ind(1,1:k);ind(1,1:k);ind(1,1:k);ind(1,1:k)})
   set(plots, {'YData'}, {A(1:k,1);A(1:k,2);A(1:k,3);A(1:k,4)})
   drawnow
   pause(.5)
end
</code>```

This answer helped me to find the solution : https://stackoverflow.com/a/36155528/919177

Body:
Just to explain what I am facing, I have the following code.

ind=(1:10);
A=[sin(ind);cos(ind);tan(ind);sec(ind)]';
plot(ind,A(:,1),ind,A(:,2),ind,A(:,3),ind,A(:,4));

the result looks like this:

Now, in my real program, the matrix A gets updated every few seconds with new rows. And I want to update the graph dynamically as soon as I get a new row. After some googling I realized that I have to use drawnow, but not sure how.

I have the following code as of now.

B=A(1,:);
h = plot(B,'YDataSource','B');
for k = 1:size(A,1)
   B=A(1:k,:);
   refreshdata(h,'caller')
   drawnow
   pause(.25)
end

But I get the following error on this:

Error using refreshdata (line 70) Could not refresh YData from 'B'.

Error in test (line 9)    refreshdata(h,'caller')

Please help.

Body:
I solved it after some more googling. The following code does, what I wanted:

ind=(1:10);
A=[sin(ind);cos(ind);tan(ind);sec(ind)]';
plots=plot(ind(1,1),A(1,1),ind(1,1),A(1,2),ind(1,1),A(1,3),ind(1,1),A(1,4));
for k = 1:size(plots,1)
   set(plots, {'XData'}, {ind(1,1:k);ind(1,1:k);ind(1,1:k);ind(1,1:k)})
   set(plots, {'YData'}, {A(1:k,1);A(1:k,2);A(1:k,3);A(1:k,4)})
   drawnow
   pause(.5)
end

This answer helped me to find the solution : https://stackoverflow.com/a/36155528/919177


问:
How do we do classes in Julia?
I have a problem with writing classes in Julia. I have looked at the documentation and I haven't seen any docs on classes.

In Python, classes are, for example,

class Dog:
   # ----blah blah---

```

How is this possible in Julia?

答:
Julia does not have classes. Instead we define new types and then define methods on those types. Methods are not "owned" by the types they operate on. Instead, a method can be said to belong to a generic function of the same name as the method. For instance, there are many versions ("methods") of the length function; together they form the generic function length.

Here's an extended example of the Julian approach to programming with types and methods. New types are declared using the struct keyword:

```<code>struct Person
    name::String
    age::Int64
end
</code>```

Now we can define methods on the Person type:

```<code>name(p::Person) = p.name
age(p::Person) = p.age

bio(p::Person) = println("My name is ", name(p)," and I am ", age(p), " years old.")
</code>```

Methods can be defined for different combinations of argument types. To illustrate this, let's first define some new types:

```<code>abstract type Pet end

struct Cat <: Pet
    name::String
    color::String
end

name(c::Cat) = c.name
color(c::Cat) = c.color
species(::Cat) = "cat"

struct Dog <: Pet
    name::String
    color::String
end

name(d::Dog) = d.name
color(d::Dog) = d.color
species(::Dog) = "dog"

bio(p::Pet) = println("I have a ", color(p), " ", species(p), " named ", name(p), ".")

struct Plant
    type::String
end

type(p::Plant) = p.type
bio(p::Plant) = println("I have a ", type(p), " house plant.")
</code>```

At this point we can see that we've defined three different one-argument methods for bio:

```<code>julia> methods(bio)
  3 methods for generic function "bio":
[1] bio(p::Plant) in Main at REPL[17]:1
[2] bio(p::Person) in Main at REPL[4]:1
[3] bio(p::Pet) in Main at REPL[14]:1
</code>```

Note the comment in the output of methods(bio): "3 methods for generic function 'bio'". We see that bio is a generic function that currently has 3 methods defined for different function signatures. Now let's add a two-argument method for bio:

```<code>function bio(person::Person, possession)
    bio(person)
    bio(possession)
end
</code>```

Notice that this function is generic in the possession argument, since the internal call to bio(possession) will work whether the possession is a plant, cat, or dog! So we now have four total methods for bio:

```<code>julia> methods(bio)
  4 methods for generic function "bio":
[1] bio(p::Plant) in Main at REPL[17]:1
[2] bio(p::Person) in Main at REPL[4]:1
[3] bio(p::Pet) in Main at REPL[14]:1
[4] bio(person::Person, possession) in Main at REPL[18]:1
</code>```

Now let's create a few instances of our types:

```<code>alice = Person("Alice", 37)
cat = Cat("Socks", "black")
dog = Dog("Roger", "brown")
plant = Plant("Boston Fern")
</code>```

So finally we can test our bio methods:

```<code>julia> bio(alice, cat)
My name is Alice and I am 37 years old.
I have a black cat named Socks.

julia> bio(alice, dog)
My name is Alice and I am 37 years old.
I have a brown dog named Roger.

julia> bio(alice, plant)
My name is Alice and I am 37 years old.
I have a Boston Fern house plant.
</code>```

Side note: Modules are used primarily for namespace management. A single module can contain the definitions for multiple types and multiple methods.

Title: How do we do classes in Julia?

Body:
I have a problem with writing classes in Julia. I have looked at the documentation and I haven't seen any docs on classes.

In Python, classes are, for example,

class Dog:
   # ----blah blah---

How is this possible in Julia?

Body:
Julia does not have classes. Instead we define new types and then define methods on those types. Methods are not "owned" by the types they operate on. Instead, a method can be said to belong to a generic function of the same name as the method. For instance, there are many versions ("methods") of the length function; together they form the generic function length.

Here's an extended example of the Julian approach to programming with types and methods. New types are declared using the struct keyword:

struct Person
    name::String
    age::Int64
end

Now we can define methods on the Person type:

name(p::Person) = p.name
age(p::Person) = p.age

bio(p::Person) = println("My name is ", name(p)," and I am ", age(p), " years old.")

Methods can be defined for different combinations of argument types. To illustrate this, let's first define some new types:

abstract type Pet end

struct Cat <: Pet
    name::String
    color::String
end

name(c::Cat) = c.name
color(c::Cat) = c.color
species(::Cat) = "cat"

struct Dog <: Pet
    name::String
    color::String
end

name(d::Dog) = d.name
color(d::Dog) = d.color
species(::Dog) = "dog"

bio(p::Pet) = println("I have a ", color(p), " ", species(p), " named ", name(p), ".")

struct Plant
    type::String
end

type(p::Plant) = p.type
bio(p::Plant) = println("I have a ", type(p), " house plant.")

At this point we can see that we've defined three different one-argument methods for bio:

julia> methods(bio)
  3 methods for generic function "bio":
[1] bio(p::Plant) in Main at REPL[17]:1
[2] bio(p::Person) in Main at REPL[4]:1
[3] bio(p::Pet) in Main at REPL[14]:1

Note the comment in the output of methods(bio): "3 methods for generic function 'bio'". We see that bio is a generic function that currently has 3 methods defined for different function signatures. Now let's add a two-argument method for bio:

function bio(person::Person, possession)
    bio(person)
    bio(possession)
end

Notice that this function is generic in the possession argument, since the internal call to bio(possession) will work whether the possession is a plant, cat, or dog! So we now have four total methods for bio:

julia> methods(bio)
  4 methods for generic function "bio":
[1] bio(p::Plant) in Main at REPL[17]:1
[2] bio(p::Person) in Main at REPL[4]:1
[3] bio(p::Pet) in Main at REPL[14]:1
[4] bio(person::Person, possession) in Main at REPL[18]:1

Now let's create a few instances of our types:

alice = Person("Alice", 37)
cat = Cat("Socks", "black")
dog = Dog("Roger", "brown")
plant = Plant("Boston Fern")

So finally we can test our bio methods:

julia> bio(alice, cat)
My name is Alice and I am 37 years old.
I have a black cat named Socks.

julia> bio(alice, dog)
My name is Alice and I am 37 years old.
I have a brown dog named Roger.

julia> bio(alice, plant)
My name is Alice and I am 37 years old.
I have a Boston Fern house plant.

Side note: Modules are used primarily for namespace management. A single module can contain the definitions for multiple types and multiple methods.


问:
Retaining Fragments when the Activity killed in background
In my application, I have an Activity. That Activity has 5 fragments. Each Fragment occupies the whole window and at anytime only one of them will be shown.

From the fifth fragment I'm opening the camera to take a picture. Since I'm opening camera, in some phones the Activity got killed and recreated.

After capturing photo, the result is given to the newly created Activity. But since this is a newly created one, this one shows the First fragment instead of Fifth.

How can I show the fifth Fragment with maintaining its state? setRetainInstance is useful only if the Activity got recreated on configuration changes.

The main problem is, at that time Activity recreation, those fragments' default constructor gets called and resulting in duplicate instance of all fragments.

答:
```<code>How can I show the fifth Fragment with maintaining its state? setRetainInstance is useful only if the Activity got recreated on configuration changes.
</code>```

As one of the answers mentioned, you can just use an index and save it in onSaveInstanceState and then use that later.

```<code>The main problem is, at that time Activity recreation, those fragments' default constructor gets called and resulting in duplicate instance of all fragments.
</code>```

Its the default behaviour. System destroyed your fragments, system will create them again using a default constructor. Duplicate will occur if you also create new fragment. To avoid that, simply check if a fragment is already existing in fragment manager.

e.g

```<code>if(getSupportFragmentManager().findFragmentByTag(tag5th) == null)
    create your fragment and add in fragment transaction
else
    use this fragment from fragment manager
</code>```

Body:
How can I show the fifth Fragment with maintaining its state? setRetainInstance is useful only if the Activity got recreated on configuration changes.

As one of the answers mentioned, you can just use an index and save it in onSaveInstanceState and then use that later.

The main problem is, at that time Activity recreation, those fragments' default constructor gets called and resulting in duplicate instance of all fragments.

Its the default behaviour. System destroyed your fragments, system will create them again using a default constructor. Duplicate will occur if you also create new fragment. To avoid that, simply check if a fragment is already existing in fragment manager.

e.g

if(getSupportFragmentManager().findFragmentByTag(tag5th) == null)
    create your fragment and add in fragment transaction
else
    use this fragment from fragment manager


问:
Display user's GitHub repositories in React App
I am still fairly new to React and I built a GitHub search app where you type in a user's name in a searchbox, it shows their avatar, bio, username etc, but no idea how to fetch their repositories of their GitHub and display them.

I do a fetch request in one of my stateless functional components where it gets the repo data, I can even do a console.log and that will display the data, but actually mapping it and rendering it does not seem to work.

Here is the code I have been trying in what I call my RepoList component that gets the data:

```<code>import React, { Component } from 'react';
import RepoListItem from './RepoListItem';

const RepoList = (props) => {
    const repoUserName = props.username;
    const repoURL = props.reposURL;

fetch(`https://api.github.com/users/${repoUserName}/repos`)
    .then(response => response.json())
    .then(data =>  {

        //const id = dateData.photos.map(roverdata => roverdata.id);

        console.log("getting mappedrepo array IDs", data.map((mappedData) => mappedData.id ));

        const mappedIDs = data.map((mappedData) => mappedData.id );
        const mappedRepoNames = data.map((mappedData) => mappedData.full_name );

        console.log("getting mappedrepo array names", mappedRepoNames);

        const arrayItems = data.map((arraySingleItem) => {
            return (
                <RepoListItem
                    arrayID={arraySingleItem.id}
                    key={arraySingleItem.id}
                    fullName={arraySingleItem.full_name}
                 />
                );
        });

        console.log("repo data map function", repoData);

    });

return (
        <ul>
            <h4>Repos</h4>
            <a href={repoURL} className="embed-responsive-item">{repoURL}</a>
            <br />
            <br />
            <h3>List of repositories</h3>
            {arrayItems}

        </ul>
   );
};

export default RepoList;
</code>```

I have a slightly different working version of the app deployed to Heroku at: https://githubsearchv1.herokuapp.com/ and the actual code is at https://github.com/aalfr494/githubsearchv1

Any idea what to try? Doing {arrayItems} in the return function seems to give an error saying it is not defined...is this because I did all this within the fetch block? Any ideas would help a ton.

答:
you can use react-hooks

you can use useEffect() for api calling like this,

```<code>import React, { useState, useEffect } from 'react';
const RepoList = () => {
  const [arrayItems, setArrayItems] = useState([]);

  useEffect( async()=>{
    await fetch(`https://api.github.com/users/${repoUserName}/repos`)
    .then(response => response.json())
    .then(data => {
      const items= data.map((arraySingleItem) => {
        return (
            <RepoListItem
                arrayID={arraySingleItem.id}
                key={arraySingleItem.id}
                fullName={arraySingleItem.full_name}
             />
            );
      });
      setArrayItems(items);
    })

  }
}

return (
        <ul>
            <h4>Repos</h4>
            <a href={repoURL} className="embed-responsive-item">{repoURL}</a>
            <br />
            <br />
            <h3>List of repositories</h3>
            {arrayItems}

        </ul>
   );
};
</code>```

Body:
I am still fairly new to React and I built a GitHub search app where you type in a user's name in a searchbox, it shows their avatar, bio, username etc, but no idea how to fetch their repositories of their GitHub and display them.

I do a fetch request in one of my stateless functional components where it gets the repo data, I can even do a console.log and that will display the data, but actually mapping it and rendering it does not seem to work.

Here is the code I have been trying in what I call my RepoList component that gets the data:

import React, { Component } from 'react';
import RepoListItem from './RepoListItem';

const RepoList = (props) => {
    const repoUserName = props.username;
    const repoURL = props.reposURL;

fetch(`https://api.github.com/users/${repoUserName}/repos`)
    .then(response => response.json())
    .then(data =>  {

        //const id = dateData.photos.map(roverdata => roverdata.id);

        console.log("getting mappedrepo array IDs", data.map((mappedData) => mappedData.id ));

        const mappedIDs = data.map((mappedData) => mappedData.id );
        const mappedRepoNames = data.map((mappedData) => mappedData.full_name );

        console.log("getting mappedrepo array names", mappedRepoNames);

        const arrayItems = data.map((arraySingleItem) => {
            return (
                <RepoListItem
                    arrayID={arraySingleItem.id}
                    key={arraySingleItem.id}
                    fullName={arraySingleItem.full_name}
                 />
                );
        });

        console.log("repo data map function", repoData);

    });

return (

Repos

            {repoURL}

List of repositories

            {arrayItems}

   );
};

export default RepoList;

I have a slightly different working version of the app deployed to Heroku at: https://githubsearchv1.herokuapp.com/ and the actual code is at https://github.com/aalfr494/githubsearchv1

Any idea what to try? Doing {arrayItems} in the return function seems to give an error saying it is not defined...is this because I did all this within the fetch block? Any ideas would help a ton.

Body:
you can use react-hooks

you can use useEffect() for api calling like this,

import React, { useState, useEffect } from 'react';
const RepoList = () => {
  const [arrayItems, setArrayItems] = useState([]);

  useEffect( async()=>{
    await fetch(`https://api.github.com/users/${repoUserName}/repos`)
    .then(response => response.json())
    .then(data => {
      const items= data.map((arraySingleItem) => {
        return (
            <RepoListItem
                arrayID={arraySingleItem.id}
                key={arraySingleItem.id}
                fullName={arraySingleItem.full_name}
             />
            );
      });
      setArrayItems(items);
    })

  }
}

return (
        <ul>
            <h4>Repos</h4>
            <a href={repoURL} className="embed-responsive-item">{repoURL}</a>
            <br />
            <br />
            <h3>List of repositories</h3>
            {arrayItems}

        </ul>
   );
};


答:
First, remove all double spaces if exists and apply this regex.

```<code>.{1,11}(?:\s|$)|.{1,11}(?:[^\s]|$)
</code>```

But I would use the split function and then 'for clause' calculating lengths.

Title: Split a text with regex in Java

Body:
I need to get a text splitted with regex in  Java (each substring will be less than or close to 10 characters (including space and special) and no word would be splitted). For example, "James has gone out for a meal." would be "James has", "gone out", "for a meal", ".".
Thanks in advance.

Body:
First, remove all double spaces if exists and apply this regex.

.{1,11}(?:\s|$)|.{1,11}(?:[^\s]|$)

But I would use the split function and then 'for clause' calculating lengths.


问:
How to convert "float value 1232.0" to time format "12:32" (HH:MM) in panda/python?
I have a time column which has datatype as float and values as follows:

12:15 is written as 1215.0.

I am looking to fix this issue and set accurate datatype for this column alongwith correct representation of the time in HH:MM format

I am working in jupyter notebook (panda/python)

答:
Do perform necessary checks to see whether the time is valid or not.</p>

```<code>f = 1215.0
x = int (f) //1215

hr = x / 100 //12
min = x % 100 //15

time = "{}:{}".format(hr, min) // 12:15
</code>```

Body:
Do perform necessary checks to see whether the time is valid or not.

f = 1215.0
x = int (f) //1215

hr = x / 100 //12
min = x % 100 //15

time = "{}:{}".format(hr, min) // 12:15


问:
Looping through an array based on the first index
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

```<code> a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]
</code>```

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

```<code>  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]
</code>```

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

```<code> for i in a:
      if i in b:
          print (b)
</code>```

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

```<code> Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85
</code>```

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

```<code>for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above
</code>```

答:
Use list comprehension:

```<code>c = [l for l in b if l[0] in a]
</code>```

Output:

```<code>[[10, 8, 52, 30, 15], [11, 81, 152, 54, 112], [13, 82, 84, 63, 24]]
</code>```

If your list or arrays are considerably large, using numpy.isin can be significantly faster:

```<code>b[np.isin(b[:, 0], a), :]
</code>```

Benchmark:

```<code>a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56], [10, 8, 52, 30, 15], [11, 81, 152, 54, 112],
 [13, 82, 84, 63, 24], [18, 182, 25, 63, 96]]

list_comp, np_isin = [], []
for i in range(1,100):
    a_test = a * i
    b_test = b * i
    list_comp.append(timeit.timeit('[l for l in b_test if l[0] in a_test]', number=10, globals=globals()))
    a_arr = np.array(a_test)
    b_arr = np.array(b_test)
    np_isin.append(timeit.timeit('b_arr[np.isin(b_arr[:, 0], a_arr), :]', number=10, globals=globals()))
</code>```

While it is not clear and concise, I would recommend using list comprehension if the b is shorter than 100. Otherwise, numpy is your way to go.

Body:
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

 a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

 for i in a:
      if i in b:
          print (b)

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

 Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above

Body:
Use list comprehension:

c = [l for l in b if l[0] in a]

Output:

[[10, 8, 52, 30, 15], [11, 81, 152, 54, 112], [13, 82, 84, 63, 24]]

If your list or arrays are considerably large, using numpy.isin can be significantly faster:

b[np.isin(b[:, 0], a), :]

Benchmark:

a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56], [10, 8, 52, 30, 15], [11, 81, 152, 54, 112],
 [13, 82, 84, 63, 24], [18, 182, 25, 63, 96]]

list_comp, np_isin = [], []
for i in range(1,100):
    a_test = a * i
    b_test = b * i
    list_comp.append(timeit.timeit('[l for l in b_test if l[0] in a_test]', number=10, globals=globals()))
    a_arr = np.array(a_test)
    b_arr = np.array(b_test)
    np_isin.append(timeit.timeit('b_arr[np.isin(b_arr[:, 0], a_arr), :]', number=10, globals=globals()))

While it is not clear and concise, I would recommend using list comprehension if the b is shorter than 100. Otherwise, numpy is your way to go.


问:
elasticsearch aggregate on list of objects with condition
Say we have following documents in elasticsearch:

```<code>[{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 210
    },
    {
      code:3,
      value: 330
    },
    {
      code:8,
      value: 220
    },
  ]
},
{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 340
    },
    {
      code:4,
      value: 340
    },
    {
      code:1,
      value: 200
    },
  ]
},
{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 810
    },
    {
      code:4,
      value: 630
    },
    {
      code:8,
      value: 220
    },
  ]
}]
</code>```

I want to apply aggregate function on specific object in the bill array iwth some condition, for example I want calculate avg of value which its code is 2.

答:
You need to first make sure that the bill field is of nested type. Then you can use nested aggregation to deal with nested documents. You can use terms aggregation on bill.code and a child avg aggregation on field bill.value to this terms aggregation. This will give you average value for each code. Now since you want only aggregation against the code 2, you can make use of bucket selector aggregation to filter and get only bucket with code 2.

So the final aggregation query will look as below:

```<code>{
  "aggs": {
    "VALUE_NESTED": {
      "nested": {
        "path": "bill"
      },
      "aggs": {
        "VALUE_TERM": {
          "terms": {
            "field": "bill.code"
          },
          "aggs": {
            "VALUE_AVG": {
              "avg": {
                "field": "bill.value"
              }
            },
            "CODE": {
              "max": {
                "field": "bill.code"
              }
            },
            "CODE_FILTER": {
              "bucket_selector": {
                "buckets_path": {
                  "code": "CODE"
                },
                "script": "params.code == 2"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Sample o/p for above:

```<code>"aggregations": {
  "VALUE_NESTED": {
    "doc_count": 9,
    "VALUE_TERM": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 2,
          "doc_count": 3,
          "CODE": {
            "value": 2
          },
          "VALUE_AVG": {
            "value": 453.3333333333333
          }
        }
      ]
    }
  }
}
</code>```

Body:
Say we have following documents in elasticsearch:

[{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 210
    },
    {
      code:3,
      value: 330
    },
    {
      code:8,
      value: 220
    },
  ]
},
{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 340
    },
    {
      code:4,
      value: 340
    },
    {
      code:1,
      value: 200
    },
  ]
},
{
  "person": {
    'name': 'asqar'
  },
  "bill": [
    {
      code:2,
      value: 810
    },
    {
      code:4,
      value: 630
    },
    {
      code:8,
      value: 220
    },
  ]
}]

I want to apply aggregate function on specific object in the bill array iwth some condition, for example I want calculate avg of value which its code is 2.

Body:
You need to first make sure that the bill field is of nested type. Then you can use nested aggregation to deal with nested documents. You can use terms aggregation on bill.code and a child avg aggregation on field bill.value to this terms aggregation. This will give you average value for each code. Now since you want only aggregation against the code 2, you can make use of bucket selector aggregation to filter and get only bucket with code 2.

So the final aggregation query will look as below:

{
  "aggs": {
    "VALUE_NESTED": {
      "nested": {
        "path": "bill"
      },
      "aggs": {
        "VALUE_TERM": {
          "terms": {
            "field": "bill.code"
          },
          "aggs": {
            "VALUE_AVG": {
              "avg": {
                "field": "bill.value"
              }
            },
            "CODE": {
              "max": {
                "field": "bill.code"
              }
            },
            "CODE_FILTER": {
              "bucket_selector": {
                "buckets_path": {
                  "code": "CODE"
                },
                "script": "params.code == 2"
              }
            }
          }
        }
      }
    }
  }
}

Sample o/p for above:

"aggregations": {
  "VALUE_NESTED": {
    "doc_count": 9,
    "VALUE_TERM": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 2,
          "doc_count": 3,
          "CODE": {
            "value": 2
          },
          "VALUE_AVG": {
            "value": 453.3333333333333
          }
        }
      ]
    }
  }
}


问:
Is there a way to both destructure a function parameter, and keep a named reference to the parameter?
In react stateless functional components we'll commonly write something like this:

```<code>export function MyCompoment({
    title,
    foo,
    bar
}) {
    return <div> title: {title}, ...</div>
}
</code>```

Where we're immediately destructuring the props object into its variables.

Now I'm using a Material-UI makeStyles hook, and I'm also using TypeScript, and the way I'm currently using it looks like this.

```<code>const useStyles = makeStyles((theme : Theme ) =>({
     root: ({foo} : MyComponentProps) => ({
         content: foo
     })
});

interface MyComponentProps  {
    title: string;
    foo: string;
    bar: string;
}
export function MyCompoment({
    title,
    foo,
    bar
} : MyComponentProps) {
    const classes = useStyles({
        title,
        foo,
        bar
    });
    return <div> title: {title}, ...</div>
}
</code>```

And you can see the problem - I have to repeat the props variable names to pass into the classes.

The best way I can think to avoid this, is write it this way:

```<code>export function MyCompoment(props: MyComponentProps) {
    const {
       title,
       foo,
       bar
    }  = props;
    const classes = useStyles(props);
    return <div> title: {title}, ...</div>
}
</code>```

But that's a little messier than I was wanting.

I was wondering if it's possible to do something like:

```<code>export function MyCompoment({
       title,
       foo,
       bar
    }  = props : MyComponentProps) {

    const classes = useStyles(props);
    return <div> title: {title}, ...</div>
}
</code>```

Pretty picky I know, just wondering.

答:
No (mostly)

From the grammar:

It's hard to prove a negative, so I had to go to the grammar.

Typescript, as far as I'm aware, does not provide any extra destructuring power that javascript does not, so I'll just answer this for javascript.

In the ES6 grammar, there's no way for a single function parameter to be both destructed and given a name in the parameter list, in one parameter.

If you look at the ES6 grammar for FormalParameter, which is one of the things in an argument list, you'll find it can only be a BindingElement, which is either a SingleNameBinding or a BindingPattern — not both. Binding patterns can only do destructuring and single name bindings can only assign to one value, so there's no way to do both.

(Note the grammar I linked is just a gist someone put on github. I don't think someone would post a misleading ES6 grammar on github, but if you're skeptical you can always check the less convenient official grammar.)

It's possible there's some other wild way to do this that I missed, but I've never seen it before and would be very surprised.

If you really want to...

You're "best way you can think of" is the best way I can think of too. You should do that.

I don't like answering "no", though, so if you really want to get it all in the parameter list, you can do something unpleasant instead. If you do:

function assignAndDestructure(props, { foo, bar } = props) {
    // props, foo, and bar will all be assigned
}
```

which kind of fits your criteria. However, it creates an optional second parameter the caller can abuse to mess up your destructuring. You can hide it by assigning it to a type that doesn't have that parameter in Typescript, but it's still risky.

In summary, there's no good way to do it, but there is a bad way. Go with your mentioned "best you can think of."

Body:
In react stateless functional components we'll commonly write something like this:

export function MyCompoment({
    title,
    foo,
    bar
}) {
    return
 title: {title}, ...

}

Where we're immediately destructuring the props object into its variables.

Now I'm using a Material-UI makeStyles hook, and I'm also using TypeScript, and the way I'm currently using it looks like this.

const useStyles = makeStyles((theme : Theme ) =>({
     root: ({foo} : MyComponentProps) => ({
         content: foo
     })
});

interface MyComponentProps  {
    title: string;
    foo: string;
    bar: string;
}
export function MyCompoment({
    title,
    foo,
    bar
} : MyComponentProps) {
    const classes = useStyles({
        title,
        foo,
        bar
    });
    return
 title: {title}, ...

}

And you can see the problem - I have to repeat the props variable names to pass into the classes.

The best way I can think to avoid this, is write it this way:

export function MyCompoment(props: MyComponentProps) {
    const {
       title,
       foo,
       bar
    }  = props;
    const classes = useStyles(props);
    return
 title: {title}, ...

}

But that's a little messier than I was wanting.

I was wondering if it's possible to do something like:

export function MyCompoment({
       title,
       foo,
       bar
    }  = props : MyComponentProps) {

    const classes = useStyles(props);
    return
 title: {title}, ...

}

Pretty picky I know, just wondering.

Body:
No (mostly)

From the grammar:

It's hard to prove a negative, so I had to go to the grammar.

Typescript, as far as I'm aware, does not provide any extra destructuring power that javascript does not, so I'll just answer this for javascript.

In the ES6 grammar, there's no way for a single function parameter to be both destructed and given a name in the parameter list, in one parameter.

If you look at the ES6 grammar for FormalParameter, which is one of the things in an argument list, you'll find it can only be a BindingElement, which is either a SingleNameBinding or a BindingPattern — not both. Binding patterns can only do destructuring and single name bindings can only assign to one value, so there's no way to do both.

(Note the grammar I linked is just a gist someone put on github. I don't think someone would post a misleading ES6 grammar on github, but if you're skeptical you can always check the less convenient official grammar.)

It's possible there's some other wild way to do this that I missed, but I've never seen it before and would be very surprised.

If you really want to...

You're "best way you can think of" is the best way I can think of too. You should do that.

I don't like answering "no", though, so if you really want to get it all in the parameter list, you can do something unpleasant instead. If you do:

function assignAndDestructure(props, { foo, bar } = props) {
    // props, foo, and bar will all be assigned
}

which kind of fits your criteria. However, it creates an optional second parameter the caller can abuse to mess up your destructuring. You can hide it by assigning it to a type that doesn't have that parameter in Typescript, but it's still risky.

In summary, there's no good way to do it, but there is a bad way. Go with your mentioned "best you can think of."