问:
spss search for value in dataset
I'd like to find any cases of a value (e.g., 0) in any cell in an SPSS database. What syntax would accomplish this? </p>

<p>(I came across a python script but don't have that option.)</p>

答:
It is still not very clear how you want to select those cases. But the below syntax will list in the output any cases which have ate least one "0" in any of the variables var1,var2 or var3. I am assuming CaseID is the case identifier variable.

```<code>TEMPORARY.
SELECT IF ANY(0,var1,var2,var3).
LIST CaseID var1 var2 var3.
</code>```

You can use as many variables as you want in the ANY function, and also on the LIST command.

Title: spss search for value in dataset

Body:
I'd like to find any cases of a value (e.g., 0) in any cell in an SPSS database. What syntax would accomplish this?

(I came across a python script but don't have that option.)

Body:
It is still not very clear how you want to select those cases. But the below syntax will list in the output any cases which have ate least one "0" in any of the variables var1,var2 or var3. I am assuming CaseID is the case identifier variable.

TEMPORARY.
SELECT IF ANY(0,var1,var2,var3).
LIST CaseID var1 var2 var3.

You can use as many variables as you want in the ANY function, and also on the LIST command.


来源: stackexchange

问:
Fetch API: how can I access the payload of a chunked response?
I'm making a simple GET request using the Fetch API and the response has:

Transfer-Encoding: chunked

The network inspector in the Firefox dev tools shows me a chunk (a partial JSON response) in the payload, but I can't figure out how to access it in JavaScript.

Interestingly, even though the response status is 200, response.ok is false.

So how can I access the payload?

答:
You might be able to use the fetch response's body field, which is a stream like object with support for streaming reads. As long as you're reading data you've received, you should be OK to process it in a streaming manner.

Here is an example of using the Reader associated with the body stream to read chunks.

ContentLicense: CC BY-SA 3.0


问:
Stuck coding post() for myform(forms.Form) in app engine, embedded django
I've come a ways, but have trouble pulling data from my form.  Below is my form and its post() method.  validation is working ok, but how to get 'cleaned' data in app engine's version of django?

```<code>def get_type():
    return [(str(type.key()), type.name) for type in GreType.all()]

class LatField(forms.Field):
    def clean(self,value):
        x = None
        try:
            x = float(value)
            if x > 90.0 or x < -90.0:
                x = None
        except:
            x = None
        if x is None:
            raise forms.ValidationError("Latitude should be a number between 90.00 and -90.00")

class LonField(forms.Field):
    def clean(self,value):
        x = None
        try:
            x = float(value)
            if x > 180.0 or x < -180.0:
                x = None
        except:
            x = None
        if x is None:
            raise forms.ValidationError("Longitude should be a number between 180.00 and -180.00")

class LocationForm(forms.Form):
    type = forms.ChoiceField(choices=get_type())
    name = forms.CharField(max_length=100)
    desc = forms.CharField(widget=forms.Textarea(), required=False)
    lat = LatField()
    lon = LonField()

class LocationHandler(webapp.RequestHandler):
  def get(self):
    template_data = { 'form' : LocationForm() }
    template_path = os.path.join(os.path.dirname(__file__), '../template/location.html')
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write(template.render(template_path, template_data))

  def post(self):
    data = LocationForm(data=self.request.POST)
    if data.is_valid():
        # what to do here?
        self.redirect('/locations')
</code>```

my validation routines probably have some redundancy, but i'm not clear about python scope

I passed on a model based form (earlier question) to get separate lat and lon fields.)

答:
Cleaned data available in self.cleaned_data. This example worked correctly:

```<code>class BlogCreateForm(forms.ModelForm):
    class Meta:
        model   = Blog
        exclude = ('author',)

    def clean_slug(self):
        '''Prevent duplicate blogs with equal key names'''
        # blog with given url address already exists
        if self.Meta.model.get_by_key_name(self.cleaned_data['slug']):
            raise forms.ValidationError("Blog with url '%s' already exists" %
                                         self.cleaned_data['slug'])
        return self.cleaned_data['slug']
</code>```

Replace return self.cleaned_data['slug'] to return self.clean_data['slug'] if you have used builtin version of Django.

Try to use http://gaeframework.com - Python web framework designed for Google App Engine

ContentLicense: CC BY-SA 2.5

Body:
I've come a ways, but have trouble pulling data from my form.  Below is my form and its post() method.  validation is working ok, but how to get 'cleaned' data in app engine's version of django?

def get_type():
    return [(str(type.key()), type.name) for type in GreType.all()]

class LatField(forms.Field):
    def clean(self,value):
        x = None
        try:
            x = float(value)
            if x > 90.0 or x < -90.0:
                x = None
        except:
            x = None
        if x is None:
            raise forms.ValidationError("Latitude should be a number between 90.00 and -90.00")

class LonField(forms.Field):
    def clean(self,value):
        x = None
        try:
            x = float(value)
            if x > 180.0 or x < -180.0:
                x = None
        except:
            x = None
        if x is None:
            raise forms.ValidationError("Longitude should be a number between 180.00 and -180.00")

class LocationForm(forms.Form):
    type = forms.ChoiceField(choices=get_type())
    name = forms.CharField(max_length=100)
    desc = forms.CharField(widget=forms.Textarea(), required=False)
    lat = LatField()
    lon = LonField()

class LocationHandler(webapp.RequestHandler):
  def get(self):
    template_data = { 'form' : LocationForm() }
    template_path = os.path.join(os.path.dirname(__file__), '../template/location.html')
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write(template.render(template_path, template_data))

  def post(self):
    data = LocationForm(data=self.request.POST)
    if data.is_valid():
        # what to do here?
        self.redirect('/locations')

my validation routines probably have some redundancy, but i'm not clear about python scope

I passed on a model based form (earlier question) to get separate lat and lon fields.)

Body:
Cleaned data available in self.cleaned_data. This example worked correctly:

class BlogCreateForm(forms.ModelForm):
    class Meta:
        model   = Blog
        exclude = ('author',)

    def clean_slug(self):
        '''Prevent duplicate blogs with equal key names'''
        # blog with given url address already exists
        if self.Meta.model.get_by_key_name(self.cleaned_data['slug']):
            raise forms.ValidationError("Blog with url '%s' already exists" %
                                         self.cleaned_data['slug'])
        return self.cleaned_data['slug']

Replace return self.cleaned_data['slug'] to return self.clean_data['slug'] if you have used builtin version of Django.

Try to use http://gaeframework.com - Python web framework designed for Google App Engine

OwnerDisplayName: Anton Danilchenko

LastEditorDisplayName: Anton Danilchenko


问:
Detect Page Close Event
What is the best way for page closed event detection ?

I have a page and I want to check if the page get's closed.
I have to do something if the user closes the page.

I tried this way and it didn't work.

I will rollback progress if user leave.

答:
Write the code in project.

C#:

using System.Web.Services;

[WebMethod]
public static void AbandonSession()
{
  HttpContext.Current.Session.Abandon();
}
```

<p>VB.NET:</p>

<pre class="lang-vb prettyprint-override"><code>Imports System.Web.Services

<WebMethod> _
Public Shared Sub AbandonSession()
  HttpContext.Current.Session.Abandon()
End Sub
</code>```

Add a script tag in between head tag of Default.aspx page and write following code:

```

Edit the function to serve your purpose and you should be fine.

Title: Detect Page Close Event

Body:
Write the code in project.

C#:

using System.Web.Services;

[WebMethod]
public static void AbandonSession()
{
  HttpContext.Current.Session.Abandon();
}

VB.NET:

Imports System.Web.Services

<WebMethod> _
Public Shared Sub AbandonSession()
  HttpContext.Current.Session.Abandon()
End Sub

Add a script tag in between head tag of Default.aspx page and write following code:

<script type="text/javascript">
  function HandleOnclose() {
    alert("Close Session");
    PageMethods.AbandonSession();
  }
  window.onbeforeunload = HandleOnclose;
</script>

Edit the function to serve your purpose and you should be fine.


问:
Event handler affects in garbage collection in CLR
I'm completely confused about how event handler can affect in garbage collection operation.

For example, why object a1 not collected by garbage collection ( the destructor of a1 is not calling):

Even after unsubscribing timeChange eventHandler the destructor isn't called by garbage collector.

Best regards.

```<code>public class B
{
    private void button1_Click(object sender, EventArgs e)
    {
        A a1 = new A();
        a1.timeChange += A1_timeChange;

        a1.Start();

        a1 = null;

        GC.Collect();
    }

    private void A1_timeChange(object sender, EventArgs e)
    {
        MessageBox.Show(((DateTime)sender).ToString() );
    }
}

public class A
{
    ~A()
    {
        MessageBox.Show("A Collected");
    }

    public void Start()
    {
        if (timeChange != null)
        {
            Task.Factory.StartNew(() => {
                while (true)
                {
                    timeChange(DateTime.Now, null);
                    System.Threading.Thread.Sleep(3000);
                }
            });
        }
    }
    public event EventHandler timeChange;
}
</code>```

答:
In summary

It is not the event itself that is causing this, but rather referencing an instance member of class A from a long running thread using a closure.

The event itself is not the issue, or is it?

This code a1.timeChange += A1_timeChange; causes a delegate inside class A that implements the event public event EventHandler timeChange to reference A1_timeChange inside class B.

So, the reference is the other way around

In your scenario, if you got rid of all references to class B, but did not unsubscribe from the event, then the event handler in A that points to a handler method in B could keep class B reachable, and therefore not GC'ed

What is really happening

Your class A is accessible from one of the GC roots (specifically, actively running threads), it's still reachable and therefore, not collected - read more

You have spawned an eternally running task (well it will stop when the app closes / foreground thread terminates) with this code

```<code>Task.Factory.StartNew(() => {
                while (true)
                {
                    timeChange(DateTime.Now, null);
                    System.Threading.Thread.Sleep(3000);
                }
</code>```

The thing is, that you're using a lambda that closes over the timeChange event, and that makes a compiler to generate a class that simply references class A

One more thing, just by having a descructor (which is compiled to a finalizer) you prolong the lifetime of your object by one GC collection - on the first GC, your object will be marked as unreachable, and will be put onto finalization queue. And on the next GC, the finalizer will actually run - read more

Body:
I'm completely confused about how event handler can affect in garbage collection operation.

For example, why object a1 not collected by garbage collection ( the destructor of a1 is not calling):

Even after unsubscribing timeChange eventHandler the destructor isn't called by garbage collector.

Best regards.

public class B
{
    private void button1_Click(object sender, EventArgs e)
    {
        A a1 = new A();
        a1.timeChange += A1_timeChange;

        a1.Start();

        a1 = null;

        GC.Collect();
    }

    private void A1_timeChange(object sender, EventArgs e)
    {
        MessageBox.Show(((DateTime)sender).ToString() );
    }
}

public class A
{
    ~A()
    {
        MessageBox.Show("A Collected");
    }

    public void Start()
    {
        if (timeChange != null)
        {
            Task.Factory.StartNew(() => {
                while (true)
                {
                    timeChange(DateTime.Now, null);
                    System.Threading.Thread.Sleep(3000);
                }
            });
        }
    }
    public event EventHandler timeChange;
}

Body:
In summary

It is not the event itself that is causing this, but rather referencing an instance member of class A from a long running thread using a closure.

The event itself is not the issue, or is it?

This code a1.timeChange += A1_timeChange; causes a delegate inside class A that implements the event public event EventHandler timeChange to reference A1_timeChange inside class B.

So, the reference is the other way around

In your scenario, if you got rid of all references to class B, but did not unsubscribe from the event, then the event handler in A that points to a handler method in B could keep class B reachable, and therefore not GC'ed

What is really happening

Your class A is accessible from one of the GC roots (specifically, actively running threads), it's still reachable and therefore, not collected - read more

You have spawned an eternally running task (well it will stop when the app closes / foreground thread terminates) with this code

Task.Factory.StartNew(() => {
                while (true)
                {
                    timeChange(DateTime.Now, null);
                    System.Threading.Thread.Sleep(3000);
                }

The thing is, that you're using a lambda that closes over the timeChange event, and that makes a compiler to generate a class that simply references class A

One more thing, just by having a descructor (which is compiled to a finalizer) you prolong the lifetime of your object by one GC collection - on the first GC, your object will be marked as unreachable, and will be put onto finalization queue. And on the next GC, the finalizer will actually run - read more


问:
Exporting list to .csv [Scala]
I am new to Scala and programming in general.
How would I go to write a list into a .csv file using Scala?

So I have a list of objects...

```<code>List[test] = List(test(Group1,lol,1,2,3),test(Group2,lel,4,5,6)....)
</code>```

how would I export it to a .csv with 4 columns, and each line having the attributes of an object?

Any help is appreciated.

答:
I recommend using an existing library: https://github.com/melrief/PureCSV

Use SBT for resolving the dependency: http://www.scala-sbt.org/

Files:

* ./build.sbt

* ./OutputCsv.scala

build.sbt

```<code>name := "parse-csv"
version := "1.0.0"
libraryDependencies ++= Seq("com.github.melrief" %% "purecsv" % "0.1.1")
</code>```

OutputCsv.scala

```<code>import purecsv.safe._

object OutputCsv extends App {
    case class Test(group: String, message: String, age: Int)
    val tests = List(Test("Group1", "lol", 1), Test("Group2", "lel", 4))

    println(tests.toCSV()) // just for debug purposes
    tests.writeCSVToFileName("/tmp/example.csv", header=Some(Seq("group", "message", "age")))
}
</code>```

sbt run will execute the file

Title: Exporting list to .csv [Scala]

Body:
I am new to Scala and programming in general.
How would I go to write a list into a .csv file using Scala?

So I have a list of objects...

List[test] = List(test(Group1,lol,1,2,3),test(Group2,lel,4,5,6)....)

how would I export it to a .csv with 4 columns, and each line having the attributes of an object?

Any help is appreciated.

Body:
I recommend using an existing library: https://github.com/melrief/PureCSV

Use SBT for resolving the dependency: http://www.scala-sbt.org/

Files:

* ./build.sbt

* ./OutputCsv.scala

build.sbt

name := "parse-csv"
version := "1.0.0"
libraryDependencies ++= Seq("com.github.melrief" %% "purecsv" % "0.1.1")

OutputCsv.scala

import purecsv.safe._

object OutputCsv extends App {
    case class Test(group: String, message: String, age: Int)
    val tests = List(Test("Group1", "lol", 1), Test("Group2", "lel", 4))

    println(tests.toCSV()) // just for debug purposes
    tests.writeCSVToFileName("/tmp/example.csv", header=Some(Seq("group", "message", "age")))
}

sbt run will execute the file


答:
You can easily use split to convert each line into a list

```<code>with open("fileToRead.txt", "r") as fi, open("fileToWrite.txt", "w") as fo:
    for line in fi:
        x = line.strip().split()
        fo.write("{}{}\t{}\n".format(x[1], x[0], x[2]))
</code>```

Title: how to merge two columns into one (using Python)?

Body:
I need to merge two columns (first and second) into one column, using Python.
Here is my file:

   0 C   -0.053959    0.000000
   1 C   -0.053862    0.000000
   2 C   -0.059245    0.000000
   3 C   -0.058925    0.000000
   4 S    0.050616    0.000000
   5 H    0.040353    0.000000
   6 H    0.040480    0.000000
   7 H    0.045907    0.000000
   8 H    0.045941    0.000000

I already managed to reach my goal with Bash:

awk '{print $2 "" $1 "\ t" $3}' <MYfile.txt >> OUTPUT.txt

The result is :

C0      -0.053959
C1      -0.053862
C2      -0.059245
C3      -0.058925
S4      0.050616
H5      0.040353
H6      0.040480
H7      0.045907
H8      0.045941

Is it possible with Python ???

Body:
You can easily use split to convert each line into a list

with open("fileToRead.txt", "r") as fi, open("fileToWrite.txt", "w") as fo:
    for line in fi:
        x = line.strip().split()
        fo.write("{}{}\t{}\n".format(x[1], x[0], x[2]))


问:
Use async pipe in ngFor on Observable of Observables (Angular)
I have variable defined like this: myVar: Observable<Observable<MyObject>[]>.

I am using Angular4 feature to enumerate with async pipe

```<code>*ngFor="let obsMyObject of (myVar | async)"
</code>```

now I have Observable of MyObject, but I need just MyObject. I could write something like that:

```<code><div *ngFor="let obsMyObject of (myVar | async)">
    <div *ngIf="let obsMyObject | async; let MyObject"></div>
</div>
</code>```

but I can not do this in inner div, because I am setting flex order (which doesn't have any effect on inner div) property so I need something like this:

```<code><div *ngFor="let obsMyObject of (myVar | async); let MyObject = (obsMyObject | async)"
    [style.order]="MyObject.order">
</div>
</code>```

I just had one idea how to do this, and I tried this:

```<code><div *ngFor="let obsMyObject of (myVar | async); let MyObject = obsMyObject)">
    {{MyObject}}
</div>
</code>```

but MyObject is undefined, so there is no way let MyObject = (obsMyObject | async) would work.

答:
I think you want to use an ng-container and an ngIf to subscribe and create reference to the observable. Then from within the ng-container you can reference this new variable as if it was a plain object.

```<code><ng-container *ngIf="myVar$| async as myVar">
   <div *ngFor="let obsMyObject of myVar">
    {{obsMyObject }}
   </div>
</ng-container>
</code>```

The use of myVar and object is really confusing.  Here's a better example:

Property in component declared as:

```<code>users$: Observable<User[]>
</code>```

And the template:

```<code><ng-container *ngIf="users$ | async as users">
   <div *ngFor="let user of users">
     {{ user.name }}
   </div>
</ng-container>
</code>```

Body:
I have variable defined like this: myVar: Observable<Observable<MyObject>[]>.

I am using Angular4 feature to enumerate with async pipe

*ngFor="let obsMyObject of (myVar | async)"

now I have Observable of MyObject, but I need just MyObject. I could write something like that:

but I can not do this in inner div, because I am setting flex order (which doesn't have any effect on inner div) property so I need something like this:

I just had one idea how to do this, and I tried this:

    {{MyObject}}

but MyObject is undefined, so there is no way let MyObject = (obsMyObject | async) would work.

Body:
I think you want to use an ng-container and an ngIf to subscribe and create reference to the observable. Then from within the ng-container you can reference this new variable as if it was a plain object.

<ng-container *ngIf="myVar$| async as myVar">
   <div *ngFor="let obsMyObject of myVar">
    {{obsMyObject }}
   </div>
</ng-container>

The use of myVar and object is really confusing.  Here's a better example:

Property in component declared as:

users$: Observable<User[]>

And the template:

<ng-container *ngIf="users$ | async as users">
   <div *ngFor="let user of users">
     {{ user.name }}
   </div>
</ng-container>


问:
Arrays in C are used through pointers?
In a question I posted here: C++ - class issue

One of the replies, which was from @SanSS mentioned the following part of the reply:

Arrays in C are used through pointers...

How is this done? And, can you clarify this by an example if possible?

Thanks.

答:
What is meant by that could be a couple of things:

1) the subscript operator is defined in terms of pointer arithmetic. C99 6.5.2.1/2 "Array subscripting" says:

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).

As an example, assume you have an array declated like so: char s[] = "012345";

All of the following evaluate to '4':

s[4]

*(s + 4)

4[s] - this
unusual construct might surprise you,
but because of the way that
subscripting is defined by the
standard, this is equivalent to *(4 +
s), which is the same as *(s + 4)
and the same as s[4].

2) (closely related to the above) array names evaluate to pointers to the first element of the array in most expressions (being the operand to the sizeof operation being the main exception).

Title: Arrays in C are used through pointers?


问:
Checking if folder exists in directory
I want to know if the folder foo exists in my current directory, so I wrote a function to do so:

```<code>use std::env;
use std::fs;
use std::io;

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|ref x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}
</code>```

However, the compiler says that I cannot move out of borrowed content here: let x = x.unwrap();.

Why is this moving out of borrowed content since I ref x?

答:
There's no reason to iterate over all the entries in a directory to check if a single item exists. Just check for the specific item:</p>

```<code>use std::{env, fs, io};

fn does_folder_foo_exist_in_current_directory() -> io::Result<bool> {
    let mut path = env::current_dir()?;
    path.push("foo");
    let metadata = fs::metadata(path)?;
    Ok(metadata.is_dir())
}
</code>```

Title: Checking if folder exists in directory

Body:
I want to know if the folder foo exists in my current directory, so I wrote a function to do so:

use std::env;
use std::fs;
use std::io;

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|ref x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}

However, the compiler says that I cannot move out of borrowed content here: let x = x.unwrap();.

Why is this moving out of borrowed content since I ref x?

Body:
There's no reason to iterate over all the entries in a directory to check if a single item exists. Just check for the specific item:

use std::{env, fs, io};

fn does_folder_foo_exist_in_current_directory() -> io::Result<bool> {
    let mut path = env::current_dir()?;
    path.push("foo");
    let metadata = fs::metadata(path)?;
    Ok(metadata.is_dir())
}


问:
iPhone App With SQLITE FTS3 Xcode Release Build Not Working
My iPhone application uses SQLITE's FTS3 functions (specifically MATCH and OFFSET). These are essential to my optimized searching algorithm. I implemented FTS3 by including three SQLITE source files, namely sqlite3.c, sqlite3.h and sqlite3ext.h in my project, under a group named SQLite. I removed from the Frameworks group my previous reference to the libsqlite3.dylib library. I set the "Other C Flags" and "Other C++ Flags" project settings to -DSQLITE_ENABLE_FTS3=1. (I also tried simply setting those flags to -DSQLITE_ENABLE_FTS3.)

The application performs perfectly in the Simulator for both debug and release builds. The application also performs perfectly on the iPhone, BUT only for the debug build!

The release build does not return result rows for any SQL calls using the MATCH and OFFSET keywords. My specific question is, "When I build the release version with my iPhone connected, is my FTS3 enabled version of SQLITE not being installing along with my app?" I see the sqlite.o object file in the appropriate Release-iphoneos subfolder on my Mac. It is a bit smaller than the one in the Debug-iphoneos subfolder, but I concluded this is due to a lack of debug symbols.

I am desperate for a solution, so any ideas at all will be greatly appreciated.

答:
This answer is different from others in the following ways:

Highlights the useful code supplied by @Robert Hawkey

Shows full code and output for Xcode 9/Swift 4.0.3

Notes that one can identify useful features of SQLite in iOS (eg. JSON SQL Functions)

tldr;

PRAGMA compile_options; (more on pragma)

Swift 4.0.3

```<code>func testSQLiteOptions(){
    var db: OpaquePointer? = nil
    var statement: OpaquePointer? = nil
    sqlite3_open(self.dbPath, &db)
    guard db != nil else {return}
    NSLog("Compile options specified when Apple built the library:");
    if (sqlite3_prepare_v2(db, "PRAGMA compile_options", -1, &statement, nil) == SQLITE_OK)
    {
      while (sqlite3_step(statement) == SQLITE_ROW)
      {
        NSLog("%s", sqlite3_column_text(statement, 0));
      }
    }
  }
</code>```

Output

```<code>2017-12-09 06:34:04.233638-0800 jlmj[5997:2882220] Compile options specified when Apple built the library:
2017-12-09 06:34:04.236378-0800 jlmj[5997:2882220] BUG_COMPATIBLE_20160819
2017-12-09 06:34:04.236490-0800 jlmj[5997:2882220] COMPILER=clang-9.0.0
2017-12-09 06:34:04.236574-0800 jlmj[5997:2882220] DEFAULT_CACHE_SIZE=128
2017-12-09 06:34:04.236651-0800 jlmj[5997:2882220] DEFAULT_CKPTFULLFSYNC
2017-12-09 06:34:04.236727-0800 jlmj[5997:2882220] DEFAULT_JOURNAL_SIZE_LIMIT=32768
2017-12-09 06:34:04.236803-0800 jlmj[5997:2882220] DEFAULT_PAGE_SIZE=4096
2017-12-09 06:34:04.236968-0800 jlmj[5997:2882220] DEFAULT_SYNCHRONOUS=2
2017-12-09 06:34:04.237046-0800 jlmj[5997:2882220] DEFAULT_WAL_SYNCHRONOUS=1
2017-12-09 06:34:04.237121-0800 jlmj[5997:2882220] ENABLE_API_ARMOR
2017-12-09 06:34:04.237195-0800 jlmj[5997:2882220] ENABLE_COLUMN_METADATA
2017-12-09 06:34:04.237270-0800 jlmj[5997:2882220] ENABLE_DBSTAT_VTAB
2017-12-09 06:34:04.237345-0800 jlmj[5997:2882220] ENABLE_FTS3
2017-12-09 06:34:04.237421-0800 jlmj[5997:2882220] ENABLE_FTS3_PARENTHESIS
2017-12-09 06:34:04.237497-0800 jlmj[5997:2882220] ENABLE_FTS3_TOKENIZER
2017-12-09 06:34:04.237648-0800 jlmj[5997:2882220] ENABLE_FTS4
2017-12-09 06:34:04.237726-0800 jlmj[5997:2882220] ENABLE_FTS5
2017-12-09 06:34:04.237802-0800 jlmj[5997:2882220] ENABLE_JSON1
2017-12-09 06:34:04.237876-0800 jlmj[5997:2882220] ENABLE_LOCKING_STYLE=1
2017-12-09 06:34:04.237950-0800 jlmj[5997:2882220] ENABLE_PREUPDATE_HOOK
2017-12-09 06:34:04.238023-0800 jlmj[5997:2882220] ENABLE_RTREE
2017-12-09 06:34:04.238097-0800 jlmj[5997:2882220] ENABLE_SESSION
2017-12-09 06:34:04.238172-0800 jlmj[5997:2882220] ENABLE_SNAPSHOT
2017-12-09 06:34:04.238248-0800 jlmj[5997:2882220] ENABLE_SQLLOG
2017-12-09 06:34:04.238323-0800 jlmj[5997:2882220] ENABLE_UNKNOWN_SQL_FUNCTION
2017-12-09 06:34:04.238398-0800 jlmj[5997:2882220] ENABLE_UPDATE_DELETE_LIMIT
2017-12-09 06:34:04.238473-0800 jlmj[5997:2882220] HAS_CODEC_RESTRICTED
2017-12-09 06:34:04.238548-0800 jlmj[5997:2882220] HAVE_ISNAN
2017-12-09 06:34:04.238622-0800 jlmj[5997:2882220] MAX_LENGTH=2147483645
2017-12-09 06:34:04.238695-0800 jlmj[5997:2882220] MAX_MMAP_SIZE=20971520
2017-12-09 06:34:04.242805-0800 jlmj[5997:2882220] MAX_VARIABLE_NUMBER=500000
2017-12-09 06:34:04.242891-0800 jlmj[5997:2882220] OMIT_AUTORESET
2017-12-09 06:34:04.242967-0800 jlmj[5997:2882220] OMIT_LOAD_EXTENSION
2017-12-09 06:34:04.243045-0800 jlmj[5997:2882220] STMTJRNL_SPILL=131072
2017-12-09 06:34:04.243120-0800 jlmj[5997:2882220] SUBSTR_COMPATIBILITY
2017-12-09 06:34:04.243196-0800 jlmj[5997:2882220] THREADSAFE=2
2017-12-09 06:34:04.243509-0800 jlmj[5997:2882220] USE_URI
</code>```

Reference

SQLite Compile-Time Options

JSON SQLite Functions

Pragma Compile Options

Body:
This answer is different from others in the following ways:

Highlights the useful code supplied by @Robert Hawkey

Shows full code and output for Xcode 9/Swift 4.0.3

Notes that one can identify useful features of SQLite in iOS (eg. JSON SQL Functions)

tldr;

PRAGMA compile_options; (more on pragma)

Swift 4.0.3

func testSQLiteOptions(){
    var db: OpaquePointer? = nil
    var statement: OpaquePointer? = nil
    sqlite3_open(self.dbPath, &db)
    guard db != nil else {return}
    NSLog("Compile options specified when Apple built the library:");
    if (sqlite3_prepare_v2(db, "PRAGMA compile_options", -1, &statement, nil) == SQLITE_OK)
    {
      while (sqlite3_step(statement) == SQLITE_ROW)
      {
        NSLog("%s", sqlite3_column_text(statement, 0));
      }
    }
  }

Output

2017-12-09 06:34:04.233638-0800 jlmj[5997:2882220] Compile options specified when Apple built the library:
2017-12-09 06:34:04.236378-0800 jlmj[5997:2882220] BUG_COMPATIBLE_20160819
2017-12-09 06:34:04.236490-0800 jlmj[5997:2882220] COMPILER=clang-9.0.0
2017-12-09 06:34:04.236574-0800 jlmj[5997:2882220] DEFAULT_CACHE_SIZE=128
2017-12-09 06:34:04.236651-0800 jlmj[5997:2882220] DEFAULT_CKPTFULLFSYNC
2017-12-09 06:34:04.236727-0800 jlmj[5997:2882220] DEFAULT_JOURNAL_SIZE_LIMIT=32768
2017-12-09 06:34:04.236803-0800 jlmj[5997:2882220] DEFAULT_PAGE_SIZE=4096
2017-12-09 06:34:04.236968-0800 jlmj[5997:2882220] DEFAULT_SYNCHRONOUS=2
2017-12-09 06:34:04.237046-0800 jlmj[5997:2882220] DEFAULT_WAL_SYNCHRONOUS=1
2017-12-09 06:34:04.237121-0800 jlmj[5997:2882220] ENABLE_API_ARMOR
2017-12-09 06:34:04.237195-0800 jlmj[5997:2882220] ENABLE_COLUMN_METADATA
2017-12-09 06:34:04.237270-0800 jlmj[5997:2882220] ENABLE_DBSTAT_VTAB
2017-12-09 06:34:04.237345-0800 jlmj[5997:2882220] ENABLE_FTS3
2017-12-09 06:34:04.237421-0800 jlmj[5997:2882220] ENABLE_FTS3_PARENTHESIS
2017-12-09 06:34:04.237497-0800 jlmj[5997:2882220] ENABLE_FTS3_TOKENIZER
2017-12-09 06:34:04.237648-0800 jlmj[5997:2882220] ENABLE_FTS4
2017-12-09 06:34:04.237726-0800 jlmj[5997:2882220] ENABLE_FTS5
2017-12-09 06:34:04.237802-0800 jlmj[5997:2882220] ENABLE_JSON1
2017-12-09 06:34:04.237876-0800 jlmj[5997:2882220] ENABLE_LOCKING_STYLE=1
2017-12-09 06:34:04.237950-0800 jlmj[5997:2882220] ENABLE_PREUPDATE_HOOK
2017-12-09 06:34:04.238023-0800 jlmj[5997:2882220] ENABLE_RTREE
2017-12-09 06:34:04.238097-0800 jlmj[5997:2882220] ENABLE_SESSION
2017-12-09 06:34:04.238172-0800 jlmj[5997:2882220] ENABLE_SNAPSHOT
2017-12-09 06:34:04.238248-0800 jlmj[5997:2882220] ENABLE_SQLLOG
2017-12-09 06:34:04.238323-0800 jlmj[5997:2882220] ENABLE_UNKNOWN_SQL_FUNCTION
2017-12-09 06:34:04.238398-0800 jlmj[5997:2882220] ENABLE_UPDATE_DELETE_LIMIT
2017-12-09 06:34:04.238473-0800 jlmj[5997:2882220] HAS_CODEC_RESTRICTED
2017-12-09 06:34:04.238548-0800 jlmj[5997:2882220] HAVE_ISNAN
2017-12-09 06:34:04.238622-0800 jlmj[5997:2882220] MAX_LENGTH=2147483645
2017-12-09 06:34:04.238695-0800 jlmj[5997:2882220] MAX_MMAP_SIZE=20971520
2017-12-09 06:34:04.242805-0800 jlmj[5997:2882220] MAX_VARIABLE_NUMBER=500000
2017-12-09 06:34:04.242891-0800 jlmj[5997:2882220] OMIT_AUTORESET
2017-12-09 06:34:04.242967-0800 jlmj[5997:2882220] OMIT_LOAD_EXTENSION
2017-12-09 06:34:04.243045-0800 jlmj[5997:2882220] STMTJRNL_SPILL=131072
2017-12-09 06:34:04.243120-0800 jlmj[5997:2882220] SUBSTR_COMPATIBILITY
2017-12-09 06:34:04.243196-0800 jlmj[5997:2882220] THREADSAFE=2
2017-12-09 06:34:04.243509-0800 jlmj[5997:2882220] USE_URI

Reference

SQLite Compile-Time Options

JSON SQLite Functions

Pragma Compile Options


问:
User Authentication for aws using Python
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user.

My scenario is:
I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API.

How can I do that in python?
I'm new to aws.So, please don't mind my question.

Update:

Here's what i have tried:
From views.py:

```<code>def boto3_with_role(role_arn, session_prefix, external_id, **kwargs):
"""
Create a partially applied session to assume a role with an external id.
A unique session_name will be generated by {session_prefix}_{time}
`session` can be passed, otherwise the default sesion will be used
see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
"""
sts = boto3.client('sts')
res = sts.assume_role(
    RoleArn=role_arn,
    RoleSessionName='{}_{}'.format(session_prefix, int(time.time())),
    ExternalId=external_id,
)
creds = res['Credentials']
return partial(boto3.session.Session,
               aws_access_key_id=creds['AccessKeyId'],
               aws_secret_access_key=creds['SecretAccessKey'],
               aws_session_token=creds['SessionToken']
               )

class AwsAuthentication(LoginRequiredMixin, CreateView):
def post(self, request, *args, **kwargs):
    AwsSession = boto3_with_role('ARN_LINK_FROM_CUSTOMER', 'MyPrefix',
                                 'EXTERNAL_ID_FROM_CUSTOMER')
    my_session = AwsSession()
    client = my_session.resource('s3')
    for bucket in client.buckets.all():
        print(bucket.name)
        return HttpResponse('Your Bucket is: {}'.format(bucket.name))
</code>```

Now, it returns: botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.

Help me, please!

Thanks in advance!

答:
I'm not sure why some others are suggesting that you cannot do this. This is completely normal and well-supported - many AWS account users allow third-parties to operate in the user's AWS account on behalf of the user. Any third-party monitoring service or cost analysis service, for example.

[Bad way] The first way is to simply ask the user for IAM credentials (an access key and a secret key). Your app can use those to access the user's AWS account. This is simple, but don't do it.

[Good way] A better way to do this is via cross-account access. You have an AWS account, and your user has an AWS account. You instruct the user to create an IAM role in his account with an appropriate IAM policy (the minimum set of permissions that your app needs) and you instruct the user how to allow your account to assume this role in the user's account - to do this you advertize the IAM policy needed and your AWS account number. The user can then create an IAM policy, create a role with that policy, then establish a trust relationship between your accounts so that you can assume that IAM role and operate in his account. For more, see here and here.

Body:
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user.

My scenario is:
I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API.

How can I do that in python?
I'm new to aws.So, please don't mind my question.

Update:

Here's what i have tried:
From views.py:

def boto3_with_role(role_arn, session_prefix, external_id, **kwargs):
"""
Create a partially applied session to assume a role with an external id.
A unique session_name will be generated by {session_prefix}_{time}
`session` can be passed, otherwise the default sesion will be used
see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
"""
sts = boto3.client('sts')
res = sts.assume_role(
    RoleArn=role_arn,
    RoleSessionName='{}_{}'.format(session_prefix, int(time.time())),
    ExternalId=external_id,
)
creds = res['Credentials']
return partial(boto3.session.Session,
               aws_access_key_id=creds['AccessKeyId'],
               aws_secret_access_key=creds['SecretAccessKey'],
               aws_session_token=creds['SessionToken']
               )

class AwsAuthentication(LoginRequiredMixin, CreateView):
def post(self, request, *args, **kwargs):
    AwsSession = boto3_with_role('ARN_LINK_FROM_CUSTOMER', 'MyPrefix',
                                 'EXTERNAL_ID_FROM_CUSTOMER')
    my_session = AwsSession()
    client = my_session.resource('s3')
    for bucket in client.buckets.all():
        print(bucket.name)
        return HttpResponse('Your Bucket is: {}'.format(bucket.name))

Now, it returns: botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.

Help me, please!

Thanks in advance!


问:
Using the reserved word "class" as field name in Django and Django REST Framework

Description of the problem

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species.
More information on Taxonomy and Taxonomic ranks in Wikipedia.

Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this:

```<code>{
    "species": "vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "<b>class</b>": "Mammalia",
    "phylum": "Chordata",
    "kingdom": "Animalia",
    "domain": "Eukarya"
}
</code>```

Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name.

What I have tried

A model class created in Django would look like this:

```<code>class Species(models.Model):
    species = models.CharField()
    genus = models.CharField()
    family = models.CharField()
    # class = models.CharField() - class is reserved word in Python
    # class_ = models.CharField() - Django doesn't allow field names
    # ending with underscore. That wouldn't be either a satisfying solution.
    # further fields
</code>```

Question

Is there any possible way to solve this problem and generate the desired output?
If not, what is the best practice to work around this problem?

答:
You can do it like below

```<code>class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Species
        fields = (
            'url', 'id', 'canonical_name', 'slug',  'species', 'genus',
            'subfamily', 'family', 'order','class', 'phylum',
            'ncbi_id', 'ncbi_taxonomy',
        )
        read_only_fields = ('slug',)
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name")
</code>```

As explained in below answer

https://stackoverflow.com/a/47717441/2830850

Body:
Description of the problem

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species.
More information on Taxonomy and Taxonomic ranks in Wikipedia.

Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this:

{
    "species": "vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "class": "Mammalia",
    "phylum": "Chordata",
    "kingdom": "Animalia",
    "domain": "Eukarya"
}

Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name.

What I have tried

A model class created in Django would look like this:

class Species(models.Model):
    species = models.CharField()
    genus = models.CharField()
    family = models.CharField()
    # class = models.CharField() - class is reserved word in Python
    # class_ = models.CharField() - Django doesn't allow field names
    # ending with underscore. That wouldn't be either a satisfying solution.
    # further fields

Question

Is there any possible way to solve this problem and generate the desired output?
If not, what is the best practice to work around this problem?

Body:
You can do it like below

class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Species
        fields = (
            'url', 'id', 'canonical_name', 'slug',  'species', 'genus',
            'subfamily', 'family', 'order','class', 'phylum',
            'ncbi_id', 'ncbi_taxonomy',
        )
        read_only_fields = ('slug',)
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name")

As explained in below answer

https://stackoverflow.com/a/47717441/2830850


答:
You can do something like this:
I suppose that your input file is called test_file.txt and your output file is called new_file.txt:

```<code>def read_file(name):
    data = None
    with open(name, 'r') as f:
        data = f.readlines()
    return (k.split() for k in data) if data else data

def merge_columns(name, new_file):
    data = read_file(name)
    if not data:
        raise Exception('Cant operate with a None data')
    with open(new_file, 'a+') as f:
        for k in data:
            first, second, third, *_ = k
            f.write('{0}{1} {2}\n'.format(second, first, third))

merge_columns('test_file.txt', 'new_file.txt')
</code>```

In terminal:

```<code>>>> python3 test.py
>>> cat new_file.txt
C0 -0.053959
C1 -0.053862
C2 -0.059245
C3 -0.058925
S4 0.050616
H5 0.040353
H6 0.040480
H7 0.045907
H8 0.045941
</code>```

Body:
You can do something like this:
I suppose that your input file is called test_file.txt and your output file is called new_file.txt:

def read_file(name):
    data = None
    with open(name, 'r') as f:
        data = f.readlines()
    return (k.split() for k in data) if data else data

def merge_columns(name, new_file):
    data = read_file(name)
    if not data:
        raise Exception('Cant operate with a None data')
    with open(new_file, 'a+') as f:
        for k in data:
            first, second, third, *_ = k
            f.write('{0}{1} {2}\n'.format(second, first, third))

merge_columns('test_file.txt', 'new_file.txt')

In terminal:

>>> python3 test.py
>>> cat new_file.txt
C0 -0.053959
C1 -0.053862
C2 -0.059245
C3 -0.058925
S4 0.050616
H5 0.040353
H6 0.040480
H7 0.045907
H8 0.045941


问:
How to use specific custom objectMapper/JsonSerializer for specific requestMapping
I know thar Jackson allow us to use custom serializer for specific domain/entity/modle, like this:

```<code>@JsonSerialize(using = CustomSerializer.class)
public class SimpleDomain {

}
</code>```

And, is there any idea to specify custom serializer for some requestMapping,
(only for the specific requestMapping(that method), not to set global objectMapper.) like this:

```<code>@RequestMapping(method = RequestMethod.GET, value = "hello")
@JsonSerialize(nullsUsing = NullToEmptyStrSerializer.class)
public @ResponseBody
Object get() {
    return new HashMap<String, Object>() {{
        put("aa", null);
        put("bb", "");
    }};
}
</code>```

I execute the code above, it returns:

```<code>{
    "aa": null,
    "bb": ""
}
</code>```

instead of:

```<code>{
    "aa": "",
    "bb": ""
}
</code>```

which exactly i wanted.

NullToEmptyStrSerializer :

```<code>public class NullToEmptyStrSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString("");
    }
}
</code>```

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.

答:
Finally, I found it out by myself.
I realized this point:

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.

My purpose :

Custom convert null to "" for specific Url(RequestMapping)

My solution :

Define a bean to keep ApplicationContext storing in a static field, also, a static getter:

```<code>@Component
public class ContextHolder {
    private static ApplicationContext applicationContext;

    @Resource
    public void setApplicationContext(ApplicationContext applicationContext) {
        ContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext get(){
        return applicationContext;
    }
}
</code>```

Define a bean below, this bean will create for every request, thus, i store ServletRequest in this bean.

```<code>@Component("servletRequestHolder")
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ServletRequestHolder {

    @Resource
    private HttpServletRequest request;

    public HttpServletRequest getRequest(){
       return request;
    }
}
</code>```

Then, a serializer is needed.

```<code>public class NullToEmptyStringSerializer extends JsonSerializer.None {

    public static List<String> convertUrls = new ArrayList<String>(){{
        add("/hello");
    }};

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        HttpServletRequest request = ContextHolder.get().getBean(ServletRequestHolder.class).getRequest();
        if (request != null) {
            String currentUrl = request.getRequestURI();
            boolean match = convertUrls.contains(currentUrl);
            if (match) {
                gen.writeString("");
            } else {
                gen.writeObject(null);
            }
        } else {
            gen.writeObject(null);
        }
    }
}
</code>```

Add the Serializer to objectMapper:

```<code>DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullToEmptyStringSerializer());
objectMapper.setSerializerProvider(sp);
</code>```

Finally, test it :

```<code>@GetMapping({"hello", "hello1"})
public Object get() {
    return new HashMap<String, Object>() {{
        put("a", null);
        put("b", "");
    }};
}
</code>```

In case of requesting localhost:20000/hello, the client receive:

```<code>{
  "aa": "",
  "bb": ""
}
</code>```

And for requesting localhost:20000/hello1, the client receive:

```<code>{
  "aa": null,
  "bb": ""
}
</code>```

Body:
I know thar Jackson allow us to use custom serializer for specific domain/entity/modle, like this:

@JsonSerialize(using = CustomSerializer.class)
public class SimpleDomain {

}

And, is there any idea to specify custom serializer for some requestMapping,
(only for the specific requestMapping(that method), not to set global objectMapper.) like this:

@RequestMapping(method = RequestMethod.GET, value = "hello")
@JsonSerialize(nullsUsing = NullToEmptyStrSerializer.class)
public @ResponseBody
Object get() {
    return new HashMap<String, Object>() {{
        put("aa", null);
        put("bb", "");
    }};
}

I execute the code above, it returns:

{
    "aa": null,
    "bb": ""
}

instead of:

{
    "aa": "",
    "bb": ""
}

which exactly i wanted.

NullToEmptyStrSerializer :

public class NullToEmptyStrSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString("");
    }
}

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.

Body:
Finally, I found it out by myself.
I realized this point:

Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.

My purpose :

Custom convert null to "" for specific Url(RequestMapping)

My solution :

Define a bean to keep ApplicationContext storing in a static field, also, a static getter:

@Component
public class ContextHolder {
    private static ApplicationContext applicationContext;

    @Resource
    public void setApplicationContext(ApplicationContext applicationContext) {
        ContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext get(){
        return applicationContext;
    }
}

Define a bean below, this bean will create for every request, thus, i store ServletRequest in this bean.

@Component("servletRequestHolder")
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ServletRequestHolder {

    @Resource
    private HttpServletRequest request;

    public HttpServletRequest getRequest(){
       return request;
    }
}

Then, a serializer is needed.

public class NullToEmptyStringSerializer extends JsonSerializer.None {

    public static List<String> convertUrls = new ArrayList<String>(){{
        add("/hello");
    }};

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        HttpServletRequest request = ContextHolder.get().getBean(ServletRequestHolder.class).getRequest();
        if (request != null) {
            String currentUrl = request.getRequestURI();
            boolean match = convertUrls.contains(currentUrl);
            if (match) {
                gen.writeString("");
            } else {
                gen.writeObject(null);
            }
        } else {
            gen.writeObject(null);
        }
    }
}

Add the Serializer to objectMapper:

DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullToEmptyStringSerializer());
objectMapper.setSerializerProvider(sp);

Finally, test it :

@GetMapping({"hello", "hello1"})
public Object get() {
    return new HashMap<String, Object>() {{
        put("a", null);
        put("b", "");
    }};
}

In case of requesting localhost:20000/hello, the client receive:

{
  "aa": "",
  "bb": ""
}

And for requesting localhost:20000/hello1, the client receive:

{
  "aa": null,
  "bb": ""
}


问:
Async Controllers in ASP.NET MVC
I have a "blog" website developed using ASP.NET MVC 1. Recent version of MVC includes AsyncController feature. This actually requires some additional task in development. But how can I reuse my existing code without modifying my business layer.

Some part of the code looks like:

```<code>BlogPost post = new BlogPost();
post.GetPost(58345);

BlogComment comments = new BlogComment();
comments.GetComments(58345);
</code>```

As per the current environment, I need to wait till the request completes two operations. Using AsyncController, I can do two operations simultaneously. But the classes BlogPost and BlogComment requires to be changed to support for asynchronous operations like adding EventHandlers to know whether the operation is completed and etc.

How can I do asynchronous operation without modifying existing business layer.

答:
You could do this:

```<code>public class BlogController : AsyncController
{
    private readonly IBlogRepository _repository;
    public BlogController(IBlogRepository repository)
    {
        _repository = repository;
    }

    public void ShowAsync(int id)
    {
        AsyncManager.OutstandingOperations.Increment(2);
        new Thread(() =>
        {
            AsyncManager.Parameters["post"] = _repository.GetPost(id);
            AsyncManager.OutstandingOperations.Decrement();
        }).Start();
        new Thread(() =>
        {
            AsyncManager.Parameters["comments"] = _repository.GetComments(id);
            AsyncManager.OutstandingOperations.Decrement();
        }).Start();
    }

    public ActionResult ShowCompleted(Post post, IEnumerable<Comment> comments)
    {
        return View(new BlogViewModel
        {
            Post = post,
            Comments = comments,
        });
    }
}
</code>```

You should measure the performance of your application and decide whether introducing an async controller brings any value to the performance.

Title: Async Controllers in ASP.NET MVC

Body:
I have a "blog" website developed using ASP.NET MVC 1. Recent version of MVC includes AsyncController feature. This actually requires some additional task in development. But how can I reuse my existing code without modifying my business layer.

Some part of the code looks like:

BlogPost post = new BlogPost();
post.GetPost(58345);

BlogComment comments = new BlogComment();
comments.GetComments(58345);

As per the current environment, I need to wait till the request completes two operations. Using AsyncController, I can do two operations simultaneously. But the classes BlogPost and BlogComment requires to be changed to support for asynchronous operations like adding EventHandlers to know whether the operation is completed and etc.

How can I do asynchronous operation without modifying existing business layer.

Body:
You could do this:

public class BlogController : AsyncController
{
    private readonly IBlogRepository _repository;
    public BlogController(IBlogRepository repository)
    {
        _repository = repository;
    }

    public void ShowAsync(int id)
    {
        AsyncManager.OutstandingOperations.Increment(2);
        new Thread(() =>
        {
            AsyncManager.Parameters["post"] = _repository.GetPost(id);
            AsyncManager.OutstandingOperations.Decrement();
        }).Start();
        new Thread(() =>
        {
            AsyncManager.Parameters["comments"] = _repository.GetComments(id);
            AsyncManager.OutstandingOperations.Decrement();
        }).Start();
    }

    public ActionResult ShowCompleted(Post post, IEnumerable<Comment> comments)
    {
        return View(new BlogViewModel
        {
            Post = post,
            Comments = comments,
        });
    }
}

You should measure the performance of your application and decide whether introducing an async controller brings any value to the performance.


答:
Create just 1 event that runs daily and closes the matches expiring that day.

```<code>CREATE EVENT test_event
ON SCHEDULE AT 1 every day
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY)
DO
   UPDATE tblMatch SET status = 0 WHERE end_date = CURRENT_DATE;
</code>```

UPDATE

If you want to time your events at a minute level, then either change the frequency of your event to minute level and use minute level when determining if a match needs closing, or completely drop the status field and just use the end_date field's value compared to now() to determine if the event is closed. The latter is a better way.

Title: mysql - Is it a good practice to have a lot of events?

Body:
I have a table tblMatch :

+---------+---------------------+------------------+-----------+
|  ID     |      start_date     |     end_date     |  status   |
+---------+---------------------+------------------+-----------+
|  1      |   2017-12-09 03:23  | 2017-12-10 03:23 |      1    |
+---------+---------------------+------------------+-----------+
| ...     |         ...         |       ...        |      1    |
+---------+---------------------+------------------+-----------+
| 1000000 |   2017-12-22 15:12  | 2017-12-30 15:12 |      1    |
+---------+---------------------+------------------+-----------+

When I insert a row, I create one event too.
Event will change status to 0 if the match is ended.

CREATE EVENT test_event_increment_number
ON SCHEDULE AT end_date
ON COMPLETION NOT PRESERVE
DO
   UPDATE tblMatch SET status = 0 WHERE ID = increment_number;

If tblMatch has 100 million matches :
Does it effect server performance?
Is it bad or good idea to create a lot of events?

Body:
Create just 1 event that runs daily and closes the matches expiring that day.

CREATE EVENT test_event
ON SCHEDULE AT 1 every day
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY)
DO
   UPDATE tblMatch SET status = 0 WHERE end_date = CURRENT_DATE;

UPDATE

If you want to time your events at a minute level, then either change the frequency of your event to minute level and use minute level when determining if a match needs closing, or completely drop the status field and just use the end_date field's value compared to now() to determine if the event is closed. The latter is a better way.


问:
Import C++ function returning pointer of structs into VB.NET
I have created a simple DLL in C++, for the sole purpose of isolating the issue and testing on a small scale the importing of a function that returns a list of structs with members of different types.

dll_header.h

```<code>#ifdef MY_DLL_EXPORTS
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif

enum color_type
{
    RGB = 1,
    MONO = 2
};

struct my_struct
{
    unsigned char *name;
    char *value;
    color_type type;
    my_struct* next;
};

extern "C" struct my_struct MY_DLL_API * get_list(void);
</code>```

dll_header.cpp

```<code>#include "dll_header.h"

MY_DLL_API my_struct * get_list(void)
{
    my_struct my_list[2];

    unsigned char name1[] = "name1";
    unsigned char name2[] = "name2";

    char val1[] = "val1";
    char val2[] = "val2";

    my_list[0].name = name1;
    my_list[0].value = val1;
    my_list[0].type = RGB;
    my_list[0].next = &my_list[1];

    my_list[0].name = name2;
    my_list[0].value  = val2;
    my_list[0].type = MONO;
    my_list[0].next = NULL;

    return my_list;
}
</code>```

Like I said, I have to use these data types (cannot change them to strings or anything else because I am testing something and I need them like this)

Now, in my VB.NET application I import and try to retrieve the list like this from the DLL

Form1.vb

```<code>Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1
    Public Enum color_type
        RGB = 1
        COLOR = 2
    End Enum

    Private Structure my_struct
        Public name As Byte()
        Public value As Char()
        Public type As color_type
        Public next As IntPtr
    End Structure

    Private Declare Function get_list Lib "my_lib.dll" () As IntPtr

    Private my_list As List(Of my_struct)

    Private Sub get_list()
        Dim my_list_pointer As IntPtr = get_list()

        my_list = New List(Of my_struct)

        Dim my_item As my_struct

        While my_list_pointer <> IntPtr.Zero
            my_item = CType(Marshal.PtrToStructure(my_list_pointer, GetType(my_struct)), my_struct)

            my_list.Add(my_item)

            my_list_pointer = my_item.next
        End While
    End Sub
</code>```

I have tried many other methods, specially changing data types but so far here I am, stuck with this exception when trying to run the code:

System.AccessViolationException: 'Attempted to read or write protected
  memory. This is often an indication that other memory is corrupt.'

Trying to find a way to make these two understand each other

答:
Either use mixed mode C++ to do the translation between native and managed types or use types that are compatible with P/Invoke.

Looking how Win32 define structure (and function that use those) is a good start to help you understand how to define compatible structures as one of the main intent of P/Invoke is to be able to use Win32 API from managed code.

If you go for mixed mode, then you can do whatever required translation between both world as you can mix native C++ and C++/CLI in the same assembly. So essentially, you would write code that convert the native structure into a managed one and then VB.NET will be able to use that managed code (assuming that you use types available in VB.NET for example).

Well, if you go for the mixed mode route, you generally ends up with 3 DLLs/Assemblies/Executable as you would have the original C++ DLL (native code), the VB.NET code (managed) and the mixed mode C++ assembly in between.

Update

While it could be relatively easy to provide code if the list is read only, if this is not the case, it could be much harder depending how the code is expected to be used and what are the availaible function in the existing DLL.

The starting point would be to create a ref class in C++/CLI.

Some similar questions

https://bytes.com/topic/c-sharp/answers/674468-passing-linked-list-c-dll-c-pinvoke

Return list of points (x,y,z) from C to C# using PInvoke

PInvoke of self referential struct from C++

Problem with your code

Your exported function retuns a pointer to a local variable which is undefined behavior.

Additional observation

If your original list is an array, the why making it a list also? An array would be easier to marshal and use. And probably perform better too.

When defining you structure, you have be explicit on how strings are marshalled and the alignment that should be used. You shoull validate that everything is as expected.

Body:
I have created a simple DLL in C++, for the sole purpose of isolating the issue and testing on a small scale the importing of a function that returns a list of structs with members of different types.

dll_header.h

#ifdef MY_DLL_EXPORTS
#define MY_DLL_API __declspec(dllexport)
#else
#define MY_DLL_API __declspec(dllimport)
#endif

enum color_type
{
    RGB = 1,
    MONO = 2
};

struct my_struct
{
    unsigned char *name;
    char *value;
    color_type type;
    my_struct* next;
};

extern "C" struct my_struct MY_DLL_API * get_list(void);

dll_header.cpp

#include "dll_header.h"

MY_DLL_API my_struct * get_list(void)
{
    my_struct my_list[2];

    unsigned char name1[] = "name1";
    unsigned char name2[] = "name2";

    char val1[] = "val1";
    char val2[] = "val2";

    my_list[0].name = name1;
    my_list[0].value = val1;
    my_list[0].type = RGB;
    my_list[0].next = &my_list[1];

    my_list[0].name = name2;
    my_list[0].value  = val2;
    my_list[0].type = MONO;
    my_list[0].next = NULL;

    return my_list;
}

Like I said, I have to use these data types (cannot change them to strings or anything else because I am testing something and I need them like this)

Now, in my VB.NET application I import and try to retrieve the list like this from the DLL

Form1.vb

Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1
    Public Enum color_type
        RGB = 1
        COLOR = 2
    End Enum

    Private Structure my_struct
        Public name As Byte()
        Public value As Char()
        Public type As color_type
        Public next As IntPtr
    End Structure

    Private Declare Function get_list Lib "my_lib.dll" () As IntPtr

    Private my_list As List(Of my_struct)

    Private Sub get_list()
        Dim my_list_pointer As IntPtr = get_list()

        my_list = New List(Of my_struct)

        Dim my_item As my_struct

        While my_list_pointer <> IntPtr.Zero
            my_item = CType(Marshal.PtrToStructure(my_list_pointer, GetType(my_struct)), my_struct)

            my_list.Add(my_item)

            my_list_pointer = my_item.next
        End While
    End Sub

I have tried many other methods, specially changing data types but so far here I am, stuck with this exception when trying to run the code:

System.AccessViolationException: 'Attempted to read or write protected
  memory. This is often an indication that other memory is corrupt.'

Trying to find a way to make these two understand each other


问:
How to unit test a service call in xUnit and nSubstitute
I been trying to figure out how i can unit test service and so far have got nowhere.

I am using xUnit and NSubstitute (as advised by friends), below is the simple test that i want to run (which fails currently).

```<code>public class UnitTest1
{
    private readonly RallyService _rallyService;

    public UnitTest1(RallyService rallyService)
    {
        _rallyService= rallyService;
    }

    [Fact]
    public void Test1()
    {
        var result = _rallyService.GetAllRallies();

        Assert.Equal(2, result.Count());
    }
}
</code>```

My rally service class makes a simple call to the db to get all Rally entites and returns those:

```<code>public class RallyService : IRallyService
{
    private readonly RallyDbContext _context;

    public RallyService(RallyDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Rally> GetAllRallies()
    {
        return _context.Rallies;
    }
}
</code>```

Any guidance would be appreciated.

答:
Since you use .NET Core, I assume you also use Entity Framework Core. While it was possible to mock most of the operations in the previous EF version, however the EF Core suggests to use in-memory database for unit testing. I.e. you don't need to mock RallyDbContext, hence NSubstitute is not needed for this particular test. You would need NSubstitute to mock the service when testing a controller or application using the service.

Below is your Test1 written using in-memory database.

```<code>public class UnitTest1
{
    private readonly DbContextOptions<RallyDbContext> _options;

    public UnitTest1()
    {
        // Use GUID for in-memory DB names to prevent any possible name conflicts
        _options = new DbContextOptionsBuilder<RallyDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
    }

    [Fact]
    public async Task Test1()
    {
        using (var context = new RallyDbContext(_options))
        {
            //Given 2 records in database
            await context.AddRangeAsync(new Rally { Name = "rally1" }, new Rally { Name = "rally2" });
            await context.SaveChangesAsync();
        }

        using (var context = new RallyDbContext(_options))
        {
            //When retrieve all rally records from the database
            var service = new RallyService(context);
            var rallies = service.GetAllRallies();

            //Then records count should be 2
            Assert.Equal(2, rallies.Count());
        }
    }
}
</code>```

A working test application with this unit test is in my GitHub for your reference. I used SQL Express in the actual app.

Body:
I been trying to figure out how i can unit test service and so far have got nowhere.

I am using xUnit and NSubstitute (as advised by friends), below is the simple test that i want to run (which fails currently).

public class UnitTest1
{
    private readonly RallyService _rallyService;

    public UnitTest1(RallyService rallyService)
    {
        _rallyService= rallyService;
    }

    [Fact]
    public void Test1()
    {
        var result = _rallyService.GetAllRallies();

        Assert.Equal(2, result.Count());
    }
}

My rally service class makes a simple call to the db to get all Rally entites and returns those:

public class RallyService : IRallyService
{
    private readonly RallyDbContext _context;

    public RallyService(RallyDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Rally> GetAllRallies()
    {
        return _context.Rallies;
    }
}

Any guidance would be appreciated.

Body:
Since you use .NET Core, I assume you also use Entity Framework Core. While it was possible to mock most of the operations in the previous EF version, however the EF Core suggests to use in-memory database for unit testing. I.e. you don't need to mock RallyDbContext, hence NSubstitute is not needed for this particular test. You would need NSubstitute to mock the service when testing a controller or application using the service.

Below is your Test1 written using in-memory database.

public class UnitTest1
{
    private readonly DbContextOptions<RallyDbContext> _options;

    public UnitTest1()
    {
        // Use GUID for in-memory DB names to prevent any possible name conflicts
        _options = new DbContextOptionsBuilder<RallyDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
    }

    [Fact]
    public async Task Test1()
    {
        using (var context = new RallyDbContext(_options))
        {
            //Given 2 records in database
            await context.AddRangeAsync(new Rally { Name = "rally1" }, new Rally { Name = "rally2" });
            await context.SaveChangesAsync();
        }

        using (var context = new RallyDbContext(_options))
        {
            //When retrieve all rally records from the database
            var service = new RallyService(context);
            var rallies = service.GetAllRallies();

            //Then records count should be 2
            Assert.Equal(2, rallies.Count());
        }
    }
}

A working test application with this unit test is in my GitHub for your reference. I used SQL Express in the actual app.


问:
Pass local variable of a function back to it's parameter
I'm wanting to pass a local variable within a function, back through it's pointer parameter (not returned).

My assignment uses a stack data structure, and one criteria that must be used is the Pop() function must have a pointer parameter that is used to return the top-most item on the stack. I have used this before. My program became more complex with a data struct, I started getting either segmentation faults, or the data not being saved after the function's frame popped.

```<code>// Definitions
typedef char * string;
typedef enum { SUCCESS, FAIL } result;
typedef enum { INTEGER, DOUBLE, STRING } item_tag;

// Result Check
static result RESULT;

// Item_Tag
typedef struct {
    item_tag tag;
    union {
        int i;
        double d;
        string s;
    } value;
} item;

// Declarations
int STACK_SIZE = 0;
const int MAX_STACK_SIZE = 1024;       // Maximum stack size
item stack[1024];

// Pop
result Pop(item *ip){
    item poppedItem;
    item * pointerReturn = malloc(sizeof(item));

    // Check stack size is not 0
    if(STACK_SIZE == 0){
        return FAIL;
    }
        // If stack size is only 1, creates a blank stack
    else if(STACK_SIZE == 1){
        item emptyItem;
        // Initialize
        emptyItem.tag = INTEGER;
        emptyItem.value.i = 0;

        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;
        // Store empty stack to top of stack
        stack[0] = emptyItem;

        // Decrease stack size
        STACK_SIZE--;

    }
        // Grab top Item from stack
    else{
        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;

        // Reshuffle Items in Stack
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}
</code>```

My knowledge with pointers is alright, and memory location/management. But I can't claim to be an expert by any means. I don't exactly know what happens in the background when you're using the function's own pointer parameter as a means of passing data back.

What is the correct syntax to solve this problem?

How can a parameter pass something back?

Thanks in advance!

EDIT*
Since many people are confused. I'll post some snippets. This is an assignment, so I cannot simply post all of it online as that'd be inappropriate. But I think it's okay to post the function itself and have people analyze it. I'm aware it's a bit messy atm since I've edited it several dozen times to try and figure out the solution. Sorry for the confusion. Keep in mind that not all the code is there. just the function in question, and some of the structure.

答:
Response to the originally posted code:

```<code>typedef struct{
    variables
}item;

void myFunc(item *itemPointer){
    item newItem;
    newItem.variable = stuff;
}

int main(){
    item * catcher;
    myFunc(catcher);
    printf("%s\n", catcher.variable);
}
</code>```

A few issues.

Your program will not compile. variable has to have a type.

```<code>void myFunc(item *itemPointer){
    item newItem;
    newItem.variable = stuff;
}
</code>```

stuff is not defined; item *itemPointer is not used.

item * catcher pointer has to point to allocated memory. It is not initialized.

Pass arguments via pointers and modify member of the structure like this:

```<code>void myFunc(item *itemPointer, const char *string){

    itemPointer->variable = string ;
}
</code>```

Solution like:

```<code>void myFunc(item *itemPointer)
{
    itemPointer->variable = stuff;
    // or
    *itemPointer = someItem;
}
</code>```

is possible, but it assumes that stuff or someItem is a global variable which is not the best programming practice IMO.

Retrieve value from pointer via -> not . operator.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char * variable;
}item;

void myFunc(item *itemPointer, const char *string){

itemPointer->variable = string ;
}

int main(){
    item * catcher;
    char *new_string = "new string";

    catcher = malloc(sizeof(item));

    myFunc(catcher, new_string);
    printf("%s\n", catcher->variable);
    free(catcher);
    return 0;
}
</code>```

OUTPUT:

```<code>new string
</code>```

Body:
I'm wanting to pass a local variable within a function, back through it's pointer parameter (not returned).

My assignment uses a stack data structure, and one criteria that must be used is the Pop() function must have a pointer parameter that is used to return the top-most item on the stack. I have used this before. My program became more complex with a data struct, I started getting either segmentation faults, or the data not being saved after the function's frame popped.

// Definitions
typedef char * string;
typedef enum { SUCCESS, FAIL } result;
typedef enum { INTEGER, DOUBLE, STRING } item_tag;

// Result Check
static result RESULT;

// Item_Tag
typedef struct {
    item_tag tag;
    union {
        int i;
        double d;
        string s;
    } value;
} item;

// Declarations
int STACK_SIZE = 0;
const int MAX_STACK_SIZE = 1024;       // Maximum stack size
item stack[1024];

// Pop
result Pop(item *ip){
    item poppedItem;
    item * pointerReturn = malloc(sizeof(item));

    // Check stack size is not 0
    if(STACK_SIZE == 0){
        return FAIL;
    }
        // If stack size is only 1, creates a blank stack
    else if(STACK_SIZE == 1){
        item emptyItem;
        // Initialize
        emptyItem.tag = INTEGER;
        emptyItem.value.i = 0;

        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;
        // Store empty stack to top of stack
        stack[0] = emptyItem;

        // Decrease stack size
        STACK_SIZE--;

    }
        // Grab top Item from stack
    else{
        // Check top item's tag
        poppedItem = stack[0];
        // Store top item data based on tag
        switch(stack[0].tag){
            case STRING:
                poppedItem.value.s = stack[0].value.s;
            case DOUBLE:
                poppedItem.value.d = stack[0].value.d;
            default:
                poppedItem.value.i = stack[0].value.i;
        }
        poppedItem.tag = stack[0].tag;
        // Allocate memory for parameter, and have it point to poppedItem
        ip = malloc(sizeof(poppedItem));
        *ip = poppedItem;

        // Reshuffle Items in Stack
        for(int idx = 0; idx < STACK_SIZE; idx++){
            stack[idx] = stack[idx + 1];
        }
        STACK_SIZE--;
    }
    return SUCCESS;
}

My knowledge with pointers is alright, and memory location/management. But I can't claim to be an expert by any means. I don't exactly know what happens in the background when you're using the function's own pointer parameter as a means of passing data back.

What is the correct syntax to solve this problem?

How can a parameter pass something back?

Thanks in advance!

EDIT*
Since many people are confused. I'll post some snippets. This is an assignment, so I cannot simply post all of it online as that'd be inappropriate. But I think it's okay to post the function itself and have people analyze it. I'm aware it's a bit messy atm since I've edited it several dozen times to try and figure out the solution. Sorry for the confusion. Keep in mind that not all the code is there. just the function in question, and some of the structure.

Body:
Response to the originally posted code:

typedef struct{
    variables
}item;

void myFunc(item *itemPointer){
    item newItem;
    newItem.variable = stuff;
}

int main(){
    item * catcher;
    myFunc(catcher);
    printf("%s\n", catcher.variable);
}

A few issues.

Your program will not compile. variable has to have a type.

void myFunc(item *itemPointer){
    item newItem;
    newItem.variable = stuff;
}

stuff is not defined; item *itemPointer is not used.

item * catcher pointer has to point to allocated memory. It is not initialized.

Pass arguments via pointers and modify member of the structure like this:

void myFunc(item *itemPointer, const char *string){

    itemPointer->variable = string ;
}

Solution like:

void myFunc(item *itemPointer)
{
    itemPointer->variable = stuff;
    // or
    *itemPointer = someItem;
}

is possible, but it assumes that stuff or someItem is a global variable which is not the best programming practice IMO.

Retrieve value from pointer via -> not . operator.

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char * variable;
}item;

void myFunc(item *itemPointer, const char *string){

itemPointer->variable = string ;
}

int main(){
    item * catcher;
    char *new_string = "new string";

    catcher = malloc(sizeof(item));

    myFunc(catcher, new_string);
    printf("%s\n", catcher->variable);
    free(catcher);
    return 0;
}

OUTPUT:

new string


问:
How to save class objects to XML in c#
I have a class and i need to save this class into an XML file. Since i have more objects from this class i need every object to be added under the same root.

I start out with the xml file as this:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
</root>
</code>```

My class looks like this:

```<code>class Save
{
 string a;
 string b;
 List<subClass> L1;
 List<subClass> L2;

 subClass
 {
  string c;
  double d;
 }
}
</code>```

The xml file after saveing should look like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
 <object>
  <Element1>a</Element1>
  <Element2>b</Element2>
  <objectListL1>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL1>
  ...
  <objectListL2>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL2>
  ...
 </object>
</root>
</code>```

Of course objectListL1 and objectListL2 are repeated as often as entries in the List are found. I just want to create a class, fill it with all my data and than do class.Save() and it should add a new object entry to my XMLfile.

答:
I think i found an easy solution:

```<code>XmlSerializer serializer = new XmlSerializer(typeof(CLASSNAME));
            StreamWriter sw = File.AppendText(FILEPATH);
            using (sw)
            {
                serializer.Serialize(sw, OBJECT);
            }
</code>```

This will create a file FILEPATH and serialize everything into it. SInce it is with "AppendText" it can be used with a list ob onjects!

If appending is not needed, instead of the Streamwriter one can use:

```<code>using (TextWriter writer = new StreamWriter(FILEPATH))
</code>```

Title: How to save class objects to XML in c#

Body:
I have a class and i need to save this class into an XML file. Since i have more objects from this class i need every object to be added under the same root.

I start out with the xml file as this:

<?xml version="1.0" encoding="utf-8"?>
<root>
</root>

My class looks like this:

class Save
{
 string a;
 string b;
 List<subClass> L1;
 List<subClass> L2;

 subClass
 {
  string c;
  double d;
 }
}

The xml file after saveing should look like this:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <object>
  <Element1>a</Element1>
  <Element2>b</Element2>
  <objectListL1>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL1>
  ...
  <objectListL2>
   <Element3>c</Element3>
   <Element4>d</Element4>
  </objectListL2>
  ...
 </object>
</root>

Of course objectListL1 and objectListL2 are repeated as often as entries in the List are found. I just want to create a class, fill it with all my data and than do class.Save() and it should add a new object entry to my XMLfile.

Body:
I think i found an easy solution:

XmlSerializer serializer = new XmlSerializer(typeof(CLASSNAME));
            StreamWriter sw = File.AppendText(FILEPATH);
            using (sw)
            {
                serializer.Serialize(sw, OBJECT);
            }

This will create a file FILEPATH and serialize everything into it. SInce it is with "AppendText" it can be used with a list ob onjects!

If appending is not needed, instead of the Streamwriter one can use:

using (TextWriter writer = new StreamWriter(FILEPATH))


问:
Sort the contents of a large file with low RAM
You have a large file around 50GB containing numbers. You need to read the file, sort the contents and copy the sorted contents to another new file.
Condition - you have only 1GB RAM on the computer. However disk space is not an issue.</p>

答:
When we sort items where all the items fit in the memory, we call it internal sorting. When we sort items where items is too big to store in the memory, we call it external sorting.

Art  of Computer Programming Vol 3: Sorting and Searching on Page 248 discuss detail algorithm for external sorting (one is merge  sort).

You also mention that file contains 50GB of numbers. Maybe there is a lot of duplicated number. You might as well using counting sort if there are a lotof duplicated.


问:
tf.contrib.signal.stft returns an empty matrix
This is the piece of code I run:

```<code>import tensorflow as tf

sess = tf.InteractiveSession()

filename = 'song.mp3' # 30 second mp3 file
SAMPLES_PER_SEC = 44100

audio_binary = tf.read_file(filename)

pcm = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='mp3', samples_per_second=SAMPLES_PER_SEC, channel_count = 1)
stft = tf.contrib.signal.stft(pcm, frame_length=1024, frame_step=512, fft_length=1024)

sess.close()
</code>```

The mp3 file is properly decoded because print(pcm.eval().shape) returns:

```<code>(1323119, 1)
</code>```

And there are even some actual non-zero values when I print them with print(pcm.eval()[1000:1010]):

```<code>[[ 0.18793298]
 [ 0.16214484]
 [ 0.16022217]
 [ 0.15918455]
 [ 0.16428113]
 [ 0.19858395]
 [ 0.22861415]
 [ 0.2347789 ]
 [ 0.22684409]
 [ 0.20728172]]
</code>```

But for some reason print(stft.eval().shape) evaluates to:

```<code>(1323119, 0, 513) # why the zero dimension?
</code>```

And therefore print(stft.eval()) is:

```<code>[]
</code>```

According to this the second dimension of the tf.contrib.signal.stft output is equal to the number of frames. Why are there no frames though?

答:
It seems that tf.contrib.ffmpeg.decode_audio returned a tensor of shape (?, 1) which is one signal of ? samples.

However tf.contrib.signal.stft expects a (signal_count, samples) tensor as input, therefore one has to transpose it beforehand.

Modifying the call like this does the trick:

```<code>stft = tf.contrib.signal.stft(tf.transpose(pcm), frame_length=1024, frame_step=512, fft_length=1024)
</code>```

Body:
This is the piece of code I run:

import tensorflow as tf

sess = tf.InteractiveSession()

filename = 'song.mp3' # 30 second mp3 file
SAMPLES_PER_SEC = 44100

audio_binary = tf.read_file(filename)

pcm = tf.contrib.ffmpeg.decode_audio(audio_binary, file_format='mp3', samples_per_second=SAMPLES_PER_SEC, channel_count = 1)
stft = tf.contrib.signal.stft(pcm, frame_length=1024, frame_step=512, fft_length=1024)

sess.close()

The mp3 file is properly decoded because print(pcm.eval().shape) returns:

(1323119, 1)

And there are even some actual non-zero values when I print them with print(pcm.eval()[1000:1010]):

[[ 0.18793298]
 [ 0.16214484]
 [ 0.16022217]
 [ 0.15918455]
 [ 0.16428113]
 [ 0.19858395]
 [ 0.22861415]
 [ 0.2347789 ]
 [ 0.22684409]
 [ 0.20728172]]

But for some reason print(stft.eval().shape) evaluates to:

(1323119, 0, 513) # why the zero dimension?

And therefore print(stft.eval()) is:

[]

According to this the second dimension of the tf.contrib.signal.stft output is equal to the number of frames. Why are there no frames though?

Body:
It seems that tf.contrib.ffmpeg.decode_audio returned a tensor of shape (?, 1) which is one signal of ? samples.

However tf.contrib.signal.stft expects a (signal_count, samples) tensor as input, therefore one has to transpose it beforehand.

Modifying the call like this does the trick:

stft = tf.contrib.signal.stft(tf.transpose(pcm), frame_length=1024, frame_step=512, fft_length=1024)


问:
columns with same name but other with calculated one Linq
I have data in database like

```<code>1     CP     12
2     OB     8
1     CP     19
3     AB     22
2     OB     33
1     CP     19
3     AB     22
</code>```

What I want after running query on it

```<code>2     OB     41
1     CP     60
3     AB     44
</code>```

What I tried

```<code> var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName, x.Weight }).Select(y => new
{
oilType = y.Key.OilTypeName,
weight = y.Sum(z => z.Weight)
});
</code>```

But I failed... Give me a in similar format

Thanks

答:
The number and the name seem redundant, so I skipped the number. I assume you have a class like this:

```<code>public class OilVolume
{
    public int Volume { get; set; }
    public string Name { get; set; }
    public OilVolume(string name, int value)
    {
        this.Name = name;
        this.Volume = value;
    }

    public override string ToString(){
        return $"{Name} {Volume}";
    }
}
</code>```

Then the query for your desired output would be:

```<code>var oilSums = db.OilVolumes
  .GroupBy(oil => oil.Name)
  .Select(group => new OilVolume(group.Key,  group.Sum(oil => oil.Volume)))
  .OrderByDescending(oil => oil.Volume);
</code>```

and the output of

```<code>foreach (var oil in oilSums)
 Console.WriteLine(oil);
</code>```

is

```<code>CP 50
AB 44
OB 41
</code>```

I assume the CP 60in your example is a mistake?

Body:
I have data in database like

1     CP     12
2     OB     8
1     CP     19
3     AB     22
2     OB     33
1     CP     19
3     AB     22

What I want after running query on it

2     OB     41
1     CP     60
3     AB     44

What I tried

 var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName, x.Weight }).Select(y => new
{
oilType = y.Key.OilTypeName,
weight = y.Sum(z => z.Weight)
});

But I failed... Give me a in similar format

Thanks

Body:
The number and the name seem redundant, so I skipped the number. I assume you have a class like this:

public class OilVolume
{
    public int Volume { get; set; }
    public string Name { get; set; }
    public OilVolume(string name, int value)
    {
        this.Name = name;
        this.Volume = value;
    }

    public override string ToString(){
        return $"{Name} {Volume}";
    }
}

Then the query for your desired output would be:

var oilSums = db.OilVolumes
  .GroupBy(oil => oil.Name)
  .Select(group => new OilVolume(group.Key,  group.Sum(oil => oil.Volume)))
  .OrderByDescending(oil => oil.Volume);

and the output of

foreach (var oil in oilSums)
 Console.WriteLine(oil);

is

CP 50
AB 44
OB 41

I assume the CP 60in your example is a mistake?


问:
Password recovery using SMS with Firebase
I want to implement password recovery on Android using SMS to mobile phone using Firebase. But now I can find only password recovery using email(Send a password reset email). So, how can I implement this feature but using SMS and mobile phone number using Firebase? Or what workaround I can implement if there is no way to do it using default Firebase methods(preferably using some other Firebase methods)?

答:
This is only a bad workaround since we don't have a "Password recovery with SMS" in Firebase.

Step 1: Authenticate the user with Phone number.
Step 2: Delete the user and save the UserId.
Step 3: Create new user with same email Id.
Step 4: This will generate a new user with different UserId. Replace the old UserId whereever stored with the new one.

Hope it works..!