答:
Once you call things their proper C++ names, the question becomes very easy to understand.

Suppose I have a class that has local variables, like this one:

Classes do not have local variables; only functions and constructors do. Your class has member variables.

My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap?

Unlike local variables, which are placed in the automatic storage (often nicknamed "the stack") member variables go wherever the object goes. If the object is in the automatic storage, its member variables are in the automatic storage as well. If the object is in dynamic storage area (often nicknamed "the heap") then its member variables are in the heap, too.

Title: How is a object with local variables stored in the heap?


来源: stackexchange

问:
How do I send sensor data from raspberry pi to my computer
How do I send data from a text file which is constantly being written with new data, from a remote server(my raspberry pi) to my computer over a wifi network?</p>

答:
Maybe consider using serial USB connection or something like that.
Another method would be to make a local server on your PC and have the PI connect to it via WiFi.

For the serial connection, this might help you: http://elinux.org/RPi_Serial_Connection

ContentLicense: CC BY-SA 3.0


问:
No manifests exist for the current culture
teaching myself about .Net Core asp.

I have added a resource file to my solution.
I have added a test string to this resource file.
I am now trying to access this test string/key within my controller.

So, in my startup.cs I have this:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

    services.AddMvc()
       .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(
        opts =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                    new CultureInfo("en-GB"),
                    new CultureInfo("en-US"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr"),
            };

            opts.DefaultRequestCulture = new RequestCulture("en");
            // Formatting numbers, dates, etc.
            opts.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            opts.SupportedUICultures = supportedCultures;
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorkerContext context)
{
    app.UseStaticFiles();

    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
</code>```

In my Controller I have this:

```<code>public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;
    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }
}
</code>```

My resource file stored here:

My properties for this resource file are:

I set a breakpoint here:

_localizer = localizer;

I inspect this variable and as you see the manifest has not been found...

What am i not understanding please?

答:
Issue 1

Based on https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization

You're supposed to put your Resources in a folder called Resources under the root. You have it under the Properties folder...

This code block (slightly different from yours)

Statup.cs

```<code>services.AddLocalization(options => options.ResourcesPath = "Resources");
</code>```

resolves to that folder for me in my projects.

Issue 2

The other issue is your naming isn't done right. Take a look at the section called Working With Resource Files which will do a better job of explaining it to you than me putting it here.

Body:
teaching myself about .Net Core asp.

I have added a resource file to my solution.
I have added a test string to this resource file.
I am now trying to access this test string/key within my controller.

So, in my startup.cs I have this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

    services.AddMvc()
       .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(
        opts =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                    new CultureInfo("en-GB"),
                    new CultureInfo("en-US"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr"),
            };

            opts.DefaultRequestCulture = new RequestCulture("en");
            // Formatting numbers, dates, etc.
            opts.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            opts.SupportedUICultures = supportedCultures;
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WorkerContext context)
{
    app.UseStaticFiles();

    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

In my Controller I have this:

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;
    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }
}

My resource file stored here:

My properties for this resource file are:

I set a breakpoint here:

_localizer = localizer;

I inspect this variable and as you see the manifest has not been found...

What am i not understanding please?

Body:
Issue 1

Based on https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization

You're supposed to put your Resources in a folder called Resources under the root. You have it under the Properties folder...

This code block (slightly different from yours)

Statup.cs

services.AddLocalization(options => options.ResourcesPath = "Resources");

resolves to that folder for me in my projects.

Issue 2

The other issue is your naming isn't done right. Take a look at the section called Working With Resource Files which will do a better job of explaining it to you than me putting it here.


问:
Organisation of fields in a form HTML5 & Bootstrap 3
I want to sort out the fields to be filled (inputs, selects, ...) on the right to make place for larger column labels, and paste the warning-signs next to the fields (as described in the image). I tried quite a few configurations, but nothing works.

Very cordially and thank you very much in advance.

Image

Here is my cshtml page :

```<code><div ng-app="SupportDemandeApp" ng-controller="SupportDemandeCtrl">
<form class="form-horizontal" id="supportDemandeForm" name="supportDemandeForm" method="post" ng-submit="validationSupportDemande(supportDemandeForm.$valid)" novalidate>
<fieldset>
    <legend><b>Données de la revue</b></legend>

    <div class="form-group" ng-class="{ 'has-error': supportDemandeForm.inputMontantGlobalAffaire.$touched && supportDemandeForm.inputMontantGlobalAffaire.$invalid }">
        <label for="inputMontantGlobalAffaire" class="col-lg-2 control-label">Montant global prévu de l'affaire (en K€)<span style="color:red"> *</span></label>
        <div class="col-lg-10">
            <input type="number" class="form-control" id="inputMontantGlobalAffaire" name="inputMontantGlobalAffaire" ng-model="inputMontantGlobalAffaire" ng-change="montantAnnuel()" pattern="[0-9]+(\\.[0-9][0-9]?)?" data-toggle="popover" data-trigger="hover" data-placement="right" data-content="Build + RUN + Infrastructure" required>
            <div class="help-block" ng-messages="supportDemandeForm.inputMontantGlobalAffaire.$error" ng-if="supportDemandeForm.inputMontantGlobalAffaire.$touched"><div ng-message="required">Champ requis</div></div>
        </div>
    </div>

    <div class="form-group" ng-class="{ 'has-error': supportDemandeForm.selectTypeContrat.$touched && supportDemandeForm.selectTypeContrat.$invalid }">
        <label for="selectTypeContrat" class="col-lg-2 control-label">Type de contrat (IS/OS)<span style="color:red"> *</span></label>
        <div class="col-lg-10">
            <select class="form-control" id="selectTypeContrat" name="selectTypeContrat" ng-model="selectedTypeContrat.type" ng-init="typeContrat()" ng-change="montantAnnuel()" ng-options="type for type in types" data-toggle="popover" data-trigger="hover" data-placement="right" data-content="Voir définitions dans l'onglet Type de contrat" required></select>
            <div class="help-block" ng-messages="supportDemandeForm.selectTypeContrat.$error" ng-if="supportDemandeForm.selectTypeContrat.$touched"><div ng-message="required">Champ requis</div></div>
        </div>
    </div>

    <div class="form-group has-warning has-feedback" ng-class="{ 'has-warning': !supportDemandeForm.selectTypeFacturation.$touched }">
        <label for="selectTypeFacturation" class="col-lg-2 control-label">Type de facturation</label>
        <div class="col-lg-10">
            <select class="form-control" id="selectTypeFacturation" name="selectTypeFacturation" ng-model="selectTypeFacturation">
                <option></option>
                <option>Régie</option>
                <option>Forfait</option>
                <option>Régie & Forfait</option>
            </select>
            <i class="glyphicon glyphicon-warning-sign form-control-feedback" ng-class="{ 'has-warning': !supportDemandeForm.selectTypeFacturation.$touched }" ng-if="!supportDemandeForm.selectTypeFacturation.$touched"></i>
        </div>
    </div>

    </fieldset>

</form>
</code>```

答: You should manipulate with .col-lg-2 of .control-label( make it larger to make text in one line ) and set max-width to the form(making it boxed and not full width) to get the same result as in the image.

Body:
I want to sort out the fields to be filled (inputs, selects, ...) on the right to make place for larger column labels, and paste the warning-signs next to the fields (as described in the image). I tried quite a few configurations, but nothing works.

Very cordially and thank you very much in advance.

Image

Here is my cshtml page :

<form class="form-horizontal" id="supportDemandeForm" name="supportDemandeForm" method="post" ng-submit="validationSupportDemande(supportDemandeForm.$valid)" novalidate>
<fieldset>
    <legend>Données de la revue</legend>

        Montant global prévu de l'affaire (en K€) *

            <input type="number" class="form-control" id="inputMontantGlobalAffaire" name="inputMontantGlobalAffaire" ng-model="inputMontantGlobalAffaire" ng-change="montantAnnuel()" pattern="[0-9]+(\\.[0-9][0-9]?)?" data-toggle="popover" data-trigger="hover" data-placement="right" data-content="Build + RUN + Infrastructure" required>

Champ requis

        Type de contrat (IS/OS) *

            <select class="form-control" id="selectTypeContrat" name="selectTypeContrat" ng-model="selectedTypeContrat.type" ng-init="typeContrat()" ng-change="montantAnnuel()" ng-options="type for type in types" data-toggle="popover" data-trigger="hover" data-placement="right" data-content="Voir définitions dans l'onglet Type de contrat" required></select>

Champ requis

        Type de facturation

            <select class="form-control" id="selectTypeFacturation" name="selectTypeFacturation" ng-model="selectTypeFacturation">
                <option></option>
                <option>Régie</option>
                <option>Forfait</option>
                <option>Régie & Forfait</option>
            </select>

    </fieldset>

</form>


问:
Not able to resolve the warnings being given by tensorflow
Whenever I run any script using Tensor Flow, I get the following warnings:

```<code>The TensorFlow library wasn't compiled to use SSE instructions, but
these are available on your machine and could speed up CPU
computations
</code>```

I tried to follow the method posted on this stack overflow post and entered the following command on the command line:

```<code>bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k //tensorflow/tools/pip_package:build_pip_package
</code>```

However I get the following error

```<code>The 'build' command is only supported from within a workspace.
</code>```

How do I solve this error and then make the tensor flow compile using SSE instructions

答:
The Installing Tensorflow from Sources page explains the procedure pretty well, make sure you have all the requirements met before running the build step.

If you wish to automate the ./configure (tensorflow-cpu) step you can run the following command from TF's root directory:

```<code># CPU default configuration
tensorflow/tools/ci_build/builds/configured CPU
</code>```

and then run the build command with native optimization:

```<code># build with native optimization
bazel build -c opt --copt=-march=native tensorflow/tools/pip_package:build_pip_package
</code>```

Body:
Whenever I run any script using Tensor Flow, I get the following warnings:

The TensorFlow library wasn't compiled to use SSE instructions, but
these are available on your machine and could speed up CPU
computations

I tried to follow the method posted on this stack overflow post and entered the following command on the command line:

bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k //tensorflow/tools/pip_package:build_pip_package

However I get the following error

The 'build' command is only supported from within a workspace.

How do I solve this error and then make the tensor flow compile using SSE instructions

Body:
The Installing Tensorflow from Sources page explains the procedure pretty well, make sure you have all the requirements met before running the build step.

If you wish to automate the ./configure (tensorflow-cpu) step you can run the following command from TF's root directory:

# CPU default configuration
tensorflow/tools/ci_build/builds/configured CPU

and then run the build command with native optimization:

# build with native optimization
bazel build -c opt --copt=-march=native tensorflow/tools/pip_package:build_pip_package


问:
Rewrite the algorithm in java stream with less effort?
I was learning about Streams in Java 8.

For example, If I have to double a number:

```<code>Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);
</code>```

If I have to square a number, then I can use below:

```<code>Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);
</code>```

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

```<code>  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);
</code>```

Is it possible to rewrite this (3 statements) in single line like :

```<code>Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);
</code>```

This is giving me a compiler error. Is it possible to do it?

答:
Looks like Java does not implicitly assume lambda expression of being a specific Functional type. I had to add casting to make it work:

```<code>Arrays.stream( new int[]{ 1, 2, 3, 4 } )
.map( ( (IntUnaryOperator)( e -> e*2 ) ).andThen(f->f*f) )
.forEach(System.out::println);
</code>```

I, personally don't like this and would prefer to use double map calls. I am curious to see a better idea.

Body:
I was learning about Streams in Java 8.

For example, If I have to double a number:

Arrays.stream(intArray).map(e->e*2).forEach(System.out::println);

If I have to square a number, then I can use below:

Arrays.stream(intArray).map(e->e*e).forEach(System.out::println);

But If I have to apply both functions on same Integer array using "andThen" method java.util.function.Function, I am doing it via:

  Function<Integer, Integer> times2 = e -> e * 2;

  Function<Integer, Integer> squared = e -> e * e;

 Arrays.stream(intArray).map(times2.andThen(squared)).forEach(System.out::println);

Is it possible to rewrite this (3 statements) in single line like :

Arrays.stream(intArray).map(e->e*2.andThen(f->f*f)).forEach(System.out::println);

This is giving me a compiler error. Is it possible to do it?

Body:
Looks like Java does not implicitly assume lambda expression of being a specific Functional type. I had to add casting to make it work:

Arrays.stream( new int[]{ 1, 2, 3, 4 } )
.map( ( (IntUnaryOperator)( e -> e*2 ) ).andThen(f->f*f) )
.forEach(System.out::println);

I, personally don't like this and would prefer to use double map calls. I am curious to see a better idea.


问:
Casting Const to non Const in c
I'm working on a school project in which I need to reproduce many of the C library functions. I'm just struggling with one specific aspect of it.

If you look at the man page for memchr you will see that it takes a const void * as input and returns a plain void *. I would assume that somewhere in the function they are casting from const to non const for the return variable.

However, when I do this (clang -Weverything +Werror) it won't compile. It works without the -Weverything tag but I would prefer to use it if possible anyway.

Is there any "correct" way to do this?

答:
This hack will do it. In practice sizeof(void *) is equal to sizeof(size_t) on every but the most obscure platforms. Nevertheless, I'd advise against using this. You should drop -Weverything instead. Standard C functions date back as far as 70', and the initial C compilers were much less strict than today's Clang or GCC with all of the warnings enabled. The fact that you'll find something "unsafe" in some of them is unavoidable.

```<code>void * memchr_(const void * ptr_, int c, size_t num);

int main(void)
{
    unsigned char ary[] = { 1, 6, 2, 45, 23, 75, 23, 43, 23 },
                  * ptr = NULL;

    ptr = memchr_(ary, 23, sizeof(ary) / sizeof(ary[0]));
    printf("ary = %p, ptr = %p, *ptr = %u\n", (void *)ary, (void *)ptr, *ptr);
    return 0;
}

void * memchr_(const void * ptr_, int c, size_t num)
{
    size_t i;
    const unsigned char * ptr = ptr_;

    for(i = 0; i < num; i++) {
        if(ptr[i] == (unsigned char)c) {
            /* Casting to size_t first so that the compiler doesn't complain */
            return (unsigned char *)(size_t)ptr + i;
        }
    }
    return NULL;
}
</code>```

Title: Casting Const to non Const in c

Body:
This hack will do it. In practice sizeof(void *) is equal to sizeof(size_t) on every but the most obscure platforms. Nevertheless, I'd advise against using this. You should drop -Weverything instead. Standard C functions date back as far as 70', and the initial C compilers were much less strict than today's Clang or GCC with all of the warnings enabled. The fact that you'll find something "unsafe" in some of them is unavoidable.

void * memchr_(const void * ptr_, int c, size_t num);

int main(void)
{
    unsigned char ary[] = { 1, 6, 2, 45, 23, 75, 23, 43, 23 },
                  * ptr = NULL;

    ptr = memchr_(ary, 23, sizeof(ary) / sizeof(ary[0]));
    printf("ary = %p, ptr = %p, *ptr = %u\n", (void *)ary, (void *)ptr, *ptr);
    return 0;
}

void * memchr_(const void * ptr_, int c, size_t num)
{
    size_t i;
    const unsigned char * ptr = ptr_;

    for(i = 0; i < num; i++) {
        if(ptr[i] == (unsigned char)c) {
            /* Casting to size_t first so that the compiler doesn't complain */
            return (unsigned char *)(size_t)ptr + i;
        }
    }
    return NULL;
}


问:
Trouble sending data between PHP and Python
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

```<code>exec("python print.py",$output,$ret_code);

echo $output[0];
</code>```

The python script -

```<code>from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']
</code>```

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks

答:
Two things. Are you sure the script is completing? It could be hanging on the searcher() call. Second, I suppose searcher() could be redirecting stdout.

My guess is that your script isn't completing, or it's timing out or something.

EDIT Looks like this code depends on the current working directory. You mention below that it runs fine in the interpreter - in the same wd as the webserver sets up?

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to set up a very basic search engine using the Whoosh modules in python called on from PHP. I had it working until I upgraded the modules for some additional features I needed. At which point an odd bug seemed to appear. Any print statement after the line "searcher = ixtemp.searcher()" is not being received by the PHP script.

The python search script is called from PHP and the first result is displayed with the following commands

exec("python print.py",$output,$ret_code);

echo $output[0];

The python script -

from whoosh.index import open_dir

ixtemp = open_dir("index")

searcher = ixtemp.searcher()

results = searcher.find("content", u""+"test")

for k in results:
    print k['filename']

Running the PHP now gives the following error -

Notice: Undefined offset: 0 in
  /opt/lampp/htdocs/new/search.php on
  line 17

The python script is working when I run it by itself. After a little investigation it seems that any print statements before the line "searcher = ixtemp.searcher()" can be read by the PHP, but all after are not received by the PHP script. I've also tried the popen() and proc_open functions too, but they have the same problem.

Any ideas on what the problem is or how I can work around it?

Thanks


问:
Javafx: Reusable collections using FXML
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>
```

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

答:
You can use <fx:reference> to reference existing objects by their fx:id. Using this tag you can reuse the ObservableList:

<HBox xmlns:fx="http://javafx.com/fxml/1" spacing="10">
    <children>
        <ChoiceBox prefWidth="150.0">
            <items>
                <FXCollections fx:id="test" fx:factory="observableArrayList">
                    <String fx:value="1" />
                    <String fx:value="2" />
                    <String fx:value="3" />
                    <String fx:value="4" />
                    <String fx:value="5" />
                    <String fx:value="6" />
                    <String fx:value="7" />
                    <String fx:value="8" />
                    <String fx:value="9" />
                </FXCollections>
            </items>
        </ChoiceBox>
        <ChoiceBox prefWidth="150.0">
            <items>
                <fx:reference source="test" />
            </items>
        </ChoiceBox>
    </children>
</HBox>
```

Title: Javafx: Reusable collections using FXML

Body:
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

Body:
You can use <fx:reference> to reference existing objects by their fx:id. Using this tag you can reuse the ObservableList:

<HBox xmlns:fx="http://javafx.com/fxml/1" spacing="10">
    <children>
        <ChoiceBox prefWidth="150.0">
            <items>
                <FXCollections fx:id="test" fx:factory="observableArrayList">
                    <String fx:value="1" />
                    <String fx:value="2" />
                    <String fx:value="3" />
                    <String fx:value="4" />
                    <String fx:value="5" />
                    <String fx:value="6" />
                    <String fx:value="7" />
                    <String fx:value="8" />
                    <String fx:value="9" />
                </FXCollections>
            </items>
        </ChoiceBox>
        <ChoiceBox prefWidth="150.0">
            <items>
                <fx:reference source="test" /> <!-- reuse other list here -->
            </items>
        </ChoiceBox>
    </children>
</HBox>


问:
Order of magnitude of few statements in apriori analysis
If we have following statements in loops,

n = n/3

n = n-1

n = n-2

I want to know if we have the above statements what are their orders of magnitude and then how to write their big O notation?

I searched for these statements on Google, but I didn't get any good result. If you have any link for this please refer to me.

答: The three statements are O(1), as they are mere arithmetic operations on scalar variables.</p>


问:
Display names using matching ID from two tables and returning a name value from the one pool of names
I have two tables. Using SQL I want to find the names from the one pool of names. e.g.:

```<code>if foodid1 = foodID return foodName,
if foodid2 = foodID return foodName,
if foodid3 = foodid return foodname
</code>```

My tables look like:

```<code>food table               order table
FoodID   FoodName        OrderID   FoodID1   FoodID2    FoodID3
1         chicken           1        1         2           3
2          fish             2        3         4           5
3          lamb             3        1         3           2
4          pie
5         steak
</code>```

I want a query that returns a value something like:

```<code>OrderID    FoodID1   FooDID2   FoodID3
1          chicken   fish      lamb
2          lamb      pie       steak
3          chicken   lamb      fish
</code>```

I can get it to display the related IDs and the first set of names but I get errors when I alter the code for more. Not sure on the correct syntax for this query.

```<code>SELECT [ORDER TABLE].OID, [ORDER TABLE].FID1, [FOOD TABLE].[Food Name], [ORDER TABLE].FID2
FROM [FOOD TABLE] INNER JOIN [ORDER TABLE] ON [FOOD TABLE].[FID] = [ORDER TABLE].[FID2];
</code>```

答:
If you are set on using that data structure, I recommend Mureinik's answer, as it definitely gives you the result you explicitly asked for. However, I am curious why you have set up your data with three different food_IDs. Ask yourself, are the following two orders different?

1) Steak, Chicken, Pie

2) Pie, Steak, Chicken

If the answer is no and you are able to modify your structure, I would recommend you leave the FoodTable as is, and set up the Order table like this:

```<code>OrderID|FoodID
1       1
1       2
1       3
2       3
2       4
2       5
3       1
3       3
3       2
</code>```

Then your select query will look like this:

```<code>SELECT o.OrderID, f.FoodName
FROM [Order Table] o LEFT JOIN [Food Table] f ON o.FoodID = f.FoodID
</code>```

Body:
I have two tables. Using SQL I want to find the names from the one pool of names. e.g.:

if foodid1 = foodID return foodName,
if foodid2 = foodID return foodName,
if foodid3 = foodid return foodname

My tables look like:

food table               order table
FoodID   FoodName        OrderID   FoodID1   FoodID2    FoodID3
1         chicken           1        1         2           3
2          fish             2        3         4           5
3          lamb             3        1         3           2
4          pie
5         steak

I want a query that returns a value something like:

OrderID    FoodID1   FooDID2   FoodID3
1          chicken   fish      lamb
2          lamb      pie       steak
3          chicken   lamb      fish

I can get it to display the related IDs and the first set of names but I get errors when I alter the code for more. Not sure on the correct syntax for this query.

SELECT [ORDER TABLE].OID, [ORDER TABLE].FID1, [FOOD TABLE].[Food Name], [ORDER TABLE].FID2
FROM [FOOD TABLE] INNER JOIN [ORDER TABLE] ON [FOOD TABLE].[FID] = [ORDER TABLE].[FID2];

Body:
If you are set on using that data structure, I recommend Mureinik's answer, as it definitely gives you the result you explicitly asked for. However, I am curious why you have set up your data with three different food_IDs. Ask yourself, are the following two orders different?

1) Steak, Chicken, Pie

2) Pie, Steak, Chicken

If the answer is no and you are able to modify your structure, I would recommend you leave the FoodTable as is, and set up the Order table like this:

OrderID|FoodID
1       1
1       2
1       3
2       3
2       4
2       5
3       1
3       3
3       2

Then your select query will look like this:

SELECT o.OrderID, f.FoodName
FROM [Order Table] o LEFT JOIN [Food Table] f ON o.FoodID = f.FoodID


问:
How is a object with local variables stored in the heap?
Suppose I have a class that has local variables, like this one:

```<code>class Object{
 private:
 int number1, number2, number3;

 public:
 Object(){
 number1=0;
 number2=0;
 number3=0;
 }

}
</code>```

Now let's suppose I use it in my main program:

```<code>int main (){
Object obj1();
}
</code>```

I created my object locally in main. Since I did not use "new" it does not use the heap. All the object's variables (and the object itself) are stored in the stack.

Now suppose I used new in main, like this:

```<code>int main (){
Object p= new obj1();
}
</code>```

Now I only have one variable in my main: a pointer that points to obj1 in the heap.

My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap? My object's variables number1, number2 and number3 do not use new. They are local variables and local variables need a local scope. I get that the object "p" is on the heap because we used "new". But what about its members? They don't use new. Is there some kind of automatic cast so that these local variables are made dynamic?

答: This is the basic Object Oriented concept. Declaring a class with member does not allocate any memory unless you create an object of that class (also called instantiating the class). An exception to this is when you declare your say "number1" as static. In that case, it will belong to the class and every object will get the same memory holding value of "number1". In that case, it will be called "class variable" rather than "member variable". Hope this helps!</p>

Body:
Suppose I have a class that has local variables, like this one:

class Object{
 private:
 int number1, number2, number3;

 public:
 Object(){
 number1=0;
 number2=0;
 number3=0;
 }

}

Now let's suppose I use it in my main program:

int main (){
Object obj1();
}

I created my object locally in main. Since I did not use "new" it does not use the heap. All the object's variables (and the object itself) are stored in the stack.

Now suppose I used new in main, like this:

int main (){
Object p= new obj1();
}

Now I only have one variable in my main: a pointer that points to obj1 in the heap.

My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap? My object's variables number1, number2 and number3 do not use new. They are local variables and local variables need a local scope. I get that the object "p" is on the heap because we used "new". But what about its members? They don't use new. Is there some kind of automatic cast so that these local variables are made dynamic?


问:
Is there a rails gem that pulls tweets from twitter into a object I can iterate?
Is there a ruby gem that will pull all recent tweets and pack it into a nice ruby object I can just iterate from and display on a web page?</p>

答:
Here you go - http://twitter.rubyforge.org/

I use this with my plugin on Heroku as well. It is working fine.

```<code>oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')

client = Twitter::Base.new(oauth)
client.friends_timeline.each  { |tweet| puts tweet.inspect }
</code>```

then you can just display a timeline as you want.

Body:
Here you go - http://twitter.rubyforge.org/

I use this with my plugin on Heroku as well. It is working fine.

oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')

client = Twitter::Base.new(oauth)
client.friends_timeline.each  { |tweet| puts tweet.inspect }

then you can just display a timeline as you want.


问:
Android: How to show a graph for every minutes values
I am making one application like share market. I want to show graph for every minutes changes in price for share. I tried time series line graph of MPAndroidChart.

But it is look like:
MPAndroidChare Line graph

But I want to show data like:

I want to show like this

Which library should i use?

答:
You can show such data using handler. I show you a sample code..</p>

```<code>public class MainActivity extends AppCompatActivity {

Handler starter, repeater;
Runnable r = new Runnable() {
    @Override
    public void run() {
        //Do whatever  in this space it will loop until the app pauses and resume when app resume
        // and update this space at an interval of one minute

        repeater.postDelayed(this, 60000);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

@Override
protected void onResume() {
    super.onResume();
    starter = new Handler();
    repeater = new Handler();
    starter.post(r);
}

@Override
protected void onPause() {
    repeater.removeCallbacks(r);
    super.onPause();
}
}
</code>```

Body:
You can show such data using handler. I show you a sample code..

public class MainActivity extends AppCompatActivity {

Handler starter, repeater;
Runnable r = new Runnable() {
    @Override
    public void run() {
        //Do whatever  in this space it will loop until the app pauses and resume when app resume
        // and update this space at an interval of one minute

        repeater.postDelayed(this, 60000);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

@Override
protected void onResume() {
    super.onResume();
    starter = new Handler();
    repeater = new Handler();
    starter.post(r);
}

@Override
protected void onPause() {
    repeater.removeCallbacks(r);
    super.onPause();
}
}


问:
Tkinter Screen Change as Altered Display - Easy way to rectify?
I understand that a few others have asked similar questions although i cant find any that match my specific issue so please be gentle.

My issue is every display i use results in my Tkinter display completely changing and im having to reposition and resize everything again through trial and error which is massively time consuming. Is there an easy way around this? I've used place and pixel sizes in the script so i think its everytime the resolution changes im having to start over.

Anyway I thought i set the resolution to the Rpi touchscreen and built the GUI to that. However, now i've bought the touchscreen the GUI isn't even close to fitting it.

I'm not that keen on having to resize and reposition everything again so if there is an easy way to achieve what i'm after i'd be grateful if someone could share it. If not, i'll just have to get on with it.

Cheers
chris

答:
You probably want to utilize the width and height aspects of your screen, and make your program relative to those instead of making everything fixed/static.

You can do this by calling winfo_width() or winfo_height() on your widget to get it's size. After you have this, instead of making an oval at 200 pixels if your screen is 400 pixels in width, you can make it relative, i.e. at width/2 (if you declare winfo_width()as a variable).


问:
Techniques for implementing -hash on mutable Cocoa objects
The documentation for -hash says it must not change while a mutable object is stored in a collection, and similarly the documentation for -isEqual: says the -hash value must be the same for equal objects.

Given this, does anybody have any suggestions for the best way to implement -hash such that it meets both these conditions and yet is actually calculated intelligently (i.e. doesn't just return 0)? Does anybody know how the mutable versions of framework-provided classes do this?

The simplest thing to do is of course just forget the first condition (about it not changing) and just make sure I never accidentally mutate an object while it's in a collection, but I'm wondering if there's any solution that's more flexible.

EDIT: I'm wondering here whether it's possible to maintain the 2 contracts (where equal objects have equal hashes, and hashes don't change while the object is in a collection) when I'm mutating the internal state of the object. My inclination is to say "no", unless I do something stupid like always return 0 for the hash, but that's why I'm asking this question.

答:
Interesting question, but I think what you want is logically impossible.  Say you start with 2 objects, A and B.  They're both different, and they start with different hash codes.  You add both to some hash table.  Now, you want to mutate A, but you can't change the hash code because it's already in the table.  However, it's possible to change A in such a way that it .equals() B.

In this case, you have 2 choices, neither of which works:

Change the hashcode of A to equal B.hashcode, which violates the constraint of not changing hash codes while in a hash table.

Don't change the hashcode, in which case A.equals(B) but they don't have the same hashcodes.

It seems to me that there's no possible way to do this without using a constant as a hashcode.

OwnerDisplayName: Kevin Ballard

LastEditorDisplayName: Kevin Ballard

OwnerDisplayName: Outlaw Programmer

LastEditorDisplayName: Chris Hanson


问:
Sticky Footer on a Site with 100% height
I'm trying to get a sticky footer on a page with 100% heigth in every tag.
My problem is that, if the content is bigger than the display and I scroll downwards, the footer is no longer at the bottom of the page.
The footer stays at the position like this: Picture of the footer

Here is an example:(Sorry that was the wrong link..)
http://jsfiddle.net/qt3m1p4c/

```<code><html style:"height: 100%">
   <body style:"height: 100%">
        A lot of Content
   </body>
   <footer style:"position: absolute; bottom: 0;">
        Sticky Footer
   </footer>
</html>
</code>```

Does someone no how to fix this, without removing the heigth attributes?

答:
Put the footer INSIDE the content wrapper and change the CSS as follows:

```<code>.pageContentWrapper {
    padding-bottom:100px;
    min-height: 100%;
    position: relative;
    box-sizing: border-box;
}
.footer {
    position: absolute;
    [...]
}
</code>```

Here's a fiddle: (EDITED, I forgot to add box-sizing: border-box; at first): http://jsfiddle.net/uc6y5dhs/1/

Body:
I'm trying to get a sticky footer on a page with 100% heigth in every tag.
My problem is that, if the content is bigger than the display and I scroll downwards, the footer is no longer at the bottom of the page.
The footer stays at the position like this: Picture of the footer

Here is an example:(Sorry that was the wrong link..)
http://jsfiddle.net/qt3m1p4c/

        A lot of Content

        Sticky Footer

Does someone no how to fix this, without removing the heigth attributes?

Body:
Put the footer INSIDE the content wrapper and change the CSS as follows:

.pageContentWrapper {
    padding-bottom:100px;
    min-height: 100%;
    position: relative;
    box-sizing: border-box;
}
.footer {
    position: absolute;
    [...]
}

Here's a fiddle: (EDITED, I forgot to add box-sizing: border-box; at first): http://jsfiddle.net/uc6y5dhs/1/


问:
Filter array of multibyte strings ending in a specific letter and conditionally mutate the retained strings
A now write this function for my script. It works well type but a little slows down. Consider the function and if you have options for optimally ask me to help.

Here is my code:

```<code>function izada($array) {
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $value);
        }
        if(mb_substr($value, -1) !== "ӣ") {
            unset($array[$key]);
        }
        if(substr_count($value, "ӣ") == 2) {
            unset($array[$key]);
        }
        $array = array_filter(array_unique(array_merge($array, $result)));
    }
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") > 2 || substr_count($value, "ӣ") < 1) {
            unset($array[$key]);
        }
    }
    return $array;
}
</code>```

Input and function call:

```<code>$array = array (
  "забони тоҷикӣ",
  "хуҷандӣ бӯстонӣ",
  "Тоҷикистон Ватанам",
  "Ғафуровӣ Мичуринӣ Савхозӣ",
  "Конверторӣ хуруфҳо"
);

$array = izada($array);

echo"```";
print_r($array);
echo"```";
</code>```

Result must be:

```<code>Array (
  [0] => забони тоҷикӣ
  [1] => хуҷандӣ, бӯстонӣ
)
</code>```

答:
Jakub's answer is not optimized and is potentially incorrect according to your posted method.

It allows the possibility of a value with 2 ӣ's but not ending with ӣ to qualify.  (If this is acceptable, then you should clarify your question requirements.)

It calls substr_count() 1 to 3 times per iteration (depending on conditional outcomes).  The important thing to consider for efficiency is minimizing function calls.

This is a more accurate / efficient process:

Method: (Demo)

```<code>foreach ($array as $v) {
    if (mb_substr($v, -1) == "ӣ") {
        if (($count = substr_count($v, "ӣ")) == 1) {
            $result[] = $v;
        } elseif ($count == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $v);
        }
    }
}
var_export($result);
</code>```

Output:

```<code>array (
  0 => 'забони тоҷикӣ',
  1 => 'хуҷандӣ, бӯстонӣ',
)
</code>```

Notice that my method first requires the final character to be ӣ, this offers the quickest return without declaring/overwriting $count for non-qualifying values.
$count is used to cache the result of substr_count() for each iteration.  By doing this, the iteration only needs to make the function call once -- improving efficiency.

Update, if my earlier snippet is logically correct, it can be refactored to be a single preg_filter() call including two replacements (one which needs no comma injection and another which injects a comma) (Demo)

```<code>var_export(
    preg_filter(
        ['/^[^ӣ]*(?:ӣ(?! ))?[^ӣ]*ӣ$/u', '/^[^ӣ]*ӣ\K [^ӣ]*ӣ$/u'],
        ['$0', ',$0'],
        $array
    )
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A now write this function for my script. It works well type but a little slows down. Consider the function and if you have options for optimally ask me to help.

Here is my code:

function izada($array) {
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $value);
        }
        if(mb_substr($value, -1) !== "ӣ") {
            unset($array[$key]);
        }
        if(substr_count($value, "ӣ") == 2) {
            unset($array[$key]);
        }
        $array = array_filter(array_unique(array_merge($array, $result)));
    }
    foreach ($array as $key => $value) {
        if(substr_count($value, "ӣ") > 2 || substr_count($value, "ӣ") < 1) {
            unset($array[$key]);
        }
    }
    return $array;
}

Input and function call:

$array = array (
  "забони тоҷикӣ",
  "хуҷандӣ бӯстонӣ",
  "Тоҷикистон Ватанам",
  "Ғафуровӣ Мичуринӣ Савхозӣ",
  "Конверторӣ хуруфҳо"
);

$array = izada($array);

echo"
";
print_r($array);
echo"
";

Result must be:

Array (
  [0] => забони тоҷикӣ
  [1] => хуҷандӣ, бӯстонӣ
)

Body:
Jakub's answer is not optimized and is potentially incorrect according to your posted method.

It allows the possibility of a value with 2 ӣ's but not ending with ӣ to qualify.  (If this is acceptable, then you should clarify your question requirements.)

It calls substr_count() 1 to 3 times per iteration (depending on conditional outcomes).  The important thing to consider for efficiency is minimizing function calls.

This is a more accurate / efficient process:

Method: (Demo)

foreach ($array as $v) {
    if (mb_substr($v, -1) == "ӣ") {
        if (($count = substr_count($v, "ӣ")) == 1) {
            $result[] = $v;
        } elseif ($count == 2) {
            $result[] = str_replace("ӣ ", "ӣ, ", $v);
        }
    }
}
var_export($result);

Output:

array (
  0 => 'забони тоҷикӣ',
  1 => 'хуҷандӣ, бӯстонӣ',
)

Notice that my method first requires the final character to be ӣ, this offers the quickest return without declaring/overwriting $count for non-qualifying values.
$count is used to cache the result of substr_count() for each iteration.  By doing this, the iteration only needs to make the function call once -- improving efficiency.

Update, if my earlier snippet is logically correct, it can be refactored to be a single preg_filter() call including two replacements (one which needs no comma injection and another which injects a comma) (Demo)

var_export(
    preg_filter(
        ['/^[^ӣ]*(?:ӣ(?! ))?[^ӣ]*ӣ$/u', '/^[^ӣ]*ӣ\K [^ӣ]*ӣ$/u'],
        ['$0', ',$0'],
        $array
    )
);


问:
Trying to get listview to work
My question is how do I fix my ListView as it doesn't show anything

So in my main file I have

```<code> private ObservableList<Customer> customers = FXCollections.observableArrayList();
</code>```

two customers are added

```<code>Customer kelly = addCustomer("95432123", "Kelly Lee");
Customer tim = addCustomer("92345678", "Tim Williams");
</code>```

I have a method for returning the ObservableList

```<code>public final ObservableList<Customer> getCustomers() {
    return customers;
}
</code>```

on my XML file I have a listview linking to the controller via

```<code><ListView fx:id="namelistview" layoutX="159.0" layoutY="8.0" prefHeight="200.0" prefWidth="200.0" />
</code>```

So I am stuck on my controller trying to actually have data printed into the ListView in the form

```<code>Kelly Lee: 95432123
</code>```

I currently have this in my Controller file but my listview is still showing up as blank

```<code>public class PizzeriaController extends Controller<Pizzeria> {
ObservableList<Customer> customers = FXCollections.observableArrayList();

@FXML
private ListView<Customer> namelistview;

public void namelistview() {
    namelistview.setItems(getPizzeria().getCustomers());
    }

public void initialize() {
}

public final Pizzeria getPizzeria() {
    return model;
}
}
</code>```

答:
The namelistview.setItems method needs an ObservableList as input, so change:

```<code>namelistview.setItems(getPizzeria().getCustomers());
</code>```

to:

```<code>namelistview.setItems(customers);
</code>```

and put this code inside the initialize method:

```<code>public void initialize() {
    namelistview.setItems(customers);
}
</code>```

Now change:

```<code>public void namelistview() {
     namelistview.setItems(getPizzeria().getCustomers());
}
</code>```

to:

```<code>public void namelistview() {
     customers.add(getPizzeria().getCustomers());
}
</code>```

Title: Trying to get listview to work

Body:
My question is how do I fix my ListView as it doesn't show anything

So in my main file I have

 private ObservableList<Customer> customers = FXCollections.observableArrayList();

two customers are added

Customer kelly = addCustomer("95432123", "Kelly Lee");
Customer tim = addCustomer("92345678", "Tim Williams");

I have a method for returning the ObservableList

public final ObservableList<Customer> getCustomers() {
    return customers;
}

on my XML file I have a listview linking to the controller via

<ListView fx:id="namelistview" layoutX="159.0" layoutY="8.0" prefHeight="200.0" prefWidth="200.0" />

So I am stuck on my controller trying to actually have data printed into the ListView in the form

Kelly Lee: 95432123

I currently have this in my Controller file but my listview is still showing up as blank

public class PizzeriaController extends Controller<Pizzeria> {
ObservableList<Customer> customers = FXCollections.observableArrayList();

@FXML
private ListView<Customer> namelistview;

public void namelistview() {
    namelistview.setItems(getPizzeria().getCustomers());
    }

public void initialize() {
}

public final Pizzeria getPizzeria() {
    return model;
}
}

Body:
The namelistview.setItems method needs an ObservableList as input, so change:

namelistview.setItems(getPizzeria().getCustomers());

to:

namelistview.setItems(customers);

and put this code inside the initialize method:

public void initialize() {
    namelistview.setItems(customers);
}

Now change:

public void namelistview() {
     namelistview.setItems(getPizzeria().getCustomers());
}

to:

public void namelistview() {
     customers.add(getPizzeria().getCustomers());
}


问:
jackson serialize by type with mixing?
I have a something like this as a json and need to convert it to a Java User-Instance by Jackson.

```<code>"userid" : "1",
"myMixes" : [ {
     "data" : {
       "id" : 1,
       "ref": "my-Object-instance"
     },
     "type" : "object"
   }, {
     "data" : [ [ 0, 1], [ 1, 2 ] ],
     "type" : "list"
   }]
</code>```

I have this in my class "User":

```<code>    // jackson should use this, if type="list"
    @JsonProperty("data")
    public List<List<Integer>> data_list = new ArrayList<>();

    // jackson should use this, if type="object"
    @JsonProperty("data")
    public Data data_object;

    @JsonProperty("id")
    public String id;

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data
    @JsonProperty("type")
    public String type;
</code>```

How can I tell jackson to generate a Data-Instance of the json-data-property, if value of json-type-property is called "object" and to generate a List-Instance, if value of json-type-property is called "list".

答:
You can write your own deserializer that checks the type property value of the received json. Something like:</p>

```<code>@JsonDeserialize(using = UserDeserializer.class)
public class UserData {
    ...
}

public class UserDeserializer extends StdDeserializer<Item> {

public UserDeserializer() {
    this(null);
}

public UserDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public UserData deserialize(JsonParser jp, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    String type = node.get("type");
    if(type.equals("object")){
    // deserialize object
    }else if(type.equals("list")){
    // deserialize list
    }
    return new UserData(...);
   }
}
</code>```

Title: jackson serialize by type with mixing?

Body:
I have a something like this as a json and need to convert it to a Java User-Instance by Jackson.

"userid" : "1",
"myMixes" : [ {
     "data" : {
       "id" : 1,
       "ref": "my-Object-instance"
     },
     "type" : "object"
   }, {
     "data" : [ [ 0, 1], [ 1, 2 ] ],
     "type" : "list"
   }]

I have this in my class "User":

    // jackson should use this, if type="list"
    @JsonProperty("data")
    public List<List<Integer>> data_list = new ArrayList<>();

    // jackson should use this, if type="object"
    @JsonProperty("data")
    public Data data_object;

    @JsonProperty("id")
    public String id;

    // if type = "object", then jackson should convert json-data-property to Java-Data-Instance
// if type = "list",then jackson should convert json-data-property to List<List<Integer>> data
    @JsonProperty("type")
    public String type;

How can I tell jackson to generate a Data-Instance of the json-data-property, if value of json-type-property is called "object" and to generate a List-Instance, if value of json-type-property is called "list".

Body:
You can write your own deserializer that checks the type property value of the received json. Something like:

@JsonDeserialize(using = UserDeserializer.class)
public class UserData {
    ...
}

public class UserDeserializer extends StdDeserializer<Item> {

public UserDeserializer() {
    this(null);
}

public UserDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public UserData deserialize(JsonParser jp, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    String type = node.get("type");
    if(type.equals("object")){
    // deserialize object
    }else if(type.equals("list")){
    // deserialize list
    }
    return new UserData(...);
   }
}


问:
generate automatically getter and setter in Android Studio
When I programmed with Android Studio, it seems to me that is a way to generate automatically the getter and the setter of my new java class.

Can anyone tell me how to do it?

答:
Open the class you want, right click anywhere in the code and chose the Generate option:

Then chose what you are trying to generate: setters, getters or both:

Then select the fields you want, and you're done.


问:
Fraction to Recurring Decimal
Working on this problem, and also did a few reference to similar solutions. One thing I am confuse is, why we break the loop as long as there is one repetitive number? Is it possible the number repeat for 2-3 times and then changed to another different number? Thanks.

I mean this part specifically,

```<code>        if (map.containsKey(num)) {
            int index = map.get(num);
            res.insert(index, "(");
            res.append(")");
            break;
        }
</code>```

The problem,

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".

```<code>public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        StringBuilder res = new StringBuilder();
        // "+" or "-"
        res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);

        // integral part
        res.append(num / den);
        num %= den;
        if (num == 0) {
            return res.toString();
        }

        // fractional part
        res.append(".");
        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        map.put(num, res.length());
        while (num != 0) {
            num *= 10;
            res.append(num / den);
            num %= den;
            if (map.containsKey(num)) {
                int index = map.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            }
            else {
                map.put(num, res.length());
            }
        }
        return res.toString();
    }
}
</code>```

thanks in advance,
Lin

答:
Here is my solution in Java to this problem:

```<code>/**
 * Given two integers a and b, return the result as a String.
 * Display the repeating part of the fraction in parenthesis.
 *
 * Runs in O(b)
 *
 * @author Raed Shomali
 */
public class Divider {

    private static final String DOT = ".";
    private static final String ERROR = "ERROR";
    private static final String LEFT_PARENTHESIS = "(";
    private static final String RIGHT_PARENTHESIS = ")";

    public static String divide(final int a, final int b){
        if (b == 0) {
            return ERROR;
        }

        int value = a / b;
        int remainder = a % b;
        return String.valueOf(value) + DOT + divider(remainder, b);
    }

    private static String divider(final int a, final int b) {
        final Map<Integer, Integer> remainderIndexMap = new HashMap<>();
        final List<Integer> values = new ArrayList<>();

        int value;
        int remainder = a;
        while (!remainderIndexMap.containsKey(remainder)) {
            remainderIndexMap.put(remainder, values.size());

            remainder *= 10;
            value = remainder / b;
            remainder = remainder % b;
            values.add(value);
        }

        final int index = remainderIndexMap.get(remainder);
        final StringBuilder result = new StringBuilder();
        for (int i = 0; i < index; i++) {
            result.append(values.get(i));
        }
        result.append(LEFT_PARENTHESIS);
        for (int i = index; i < values.size(); i++) {
            result.append(values.get(i));
        }
        result.append(RIGHT_PARENTHESIS);
        return result.toString();
    }
}
</code>```

Basically, the idea is simple. Using the same long division technique, you know when to stop when you have already seen the same remainder value.

Here are some test cases to show a few different scenarios:

```<code>divide(0, 0)     // "ERROR"
divide(1, 2)     // "0.5(0)"
divide(0, 3)     // "0.(0)"
divide(10, 3)    // "3.(3)"
divide(22, 7)    // "3.(142857)"
divide(100, 145) // "0.(6896551724137931034482758620)"
</code>```

If you are interested in a solution written in Go, you can find it here https://github.com/shomali11/util

Title: Fraction to Recurring Decimal

Body:
Working on this problem, and also did a few reference to similar solutions. One thing I am confuse is, why we break the loop as long as there is one repetitive number? Is it possible the number repeat for 2-3 times and then changed to another different number? Thanks.

I mean this part specifically,

        if (map.containsKey(num)) {
            int index = map.get(num);
            res.insert(index, "(");
            res.append(")");
            break;
        }

The problem,

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        StringBuilder res = new StringBuilder();
        // "+" or "-"
        res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
        long num = Math.abs((long)numerator);
        long den = Math.abs((long)denominator);

        // integral part
        res.append(num / den);
        num %= den;
        if (num == 0) {
            return res.toString();
        }

        // fractional part
        res.append(".");
        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        map.put(num, res.length());
        while (num != 0) {
            num *= 10;
            res.append(num / den);
            num %= den;
            if (map.containsKey(num)) {
                int index = map.get(num);
                res.insert(index, "(");
                res.append(")");
                break;
            }
            else {
                map.put(num, res.length());
            }
        }
        return res.toString();
    }
}

thanks in advance,
Lin

Body:
Here is my solution in Java to this problem:

/**
 * Given two integers a and b, return the result as a String.
 * Display the repeating part of the fraction in parenthesis.
 *
 * Runs in O(b)
 *
 * @author Raed Shomali
 */
public class Divider {

    private static final String DOT = ".";
    private static final String ERROR = "ERROR";
    private static final String LEFT_PARENTHESIS = "(";
    private static final String RIGHT_PARENTHESIS = ")";

    public static String divide(final int a, final int b){
        if (b == 0) {
            return ERROR;
        }

        int value = a / b;
        int remainder = a % b;
        return String.valueOf(value) + DOT + divider(remainder, b);
    }

    private static String divider(final int a, final int b) {
        final Map<Integer, Integer> remainderIndexMap = new HashMap<>();
        final List<Integer> values = new ArrayList<>();

        int value;
        int remainder = a;
        while (!remainderIndexMap.containsKey(remainder)) {
            remainderIndexMap.put(remainder, values.size());

            remainder *= 10;
            value = remainder / b;
            remainder = remainder % b;
            values.add(value);
        }

        final int index = remainderIndexMap.get(remainder);
        final StringBuilder result = new StringBuilder();
        for (int i = 0; i < index; i++) {
            result.append(values.get(i));
        }
        result.append(LEFT_PARENTHESIS);
        for (int i = index; i < values.size(); i++) {
            result.append(values.get(i));
        }
        result.append(RIGHT_PARENTHESIS);
        return result.toString();
    }
}

Basically, the idea is simple. Using the same long division technique, you know when to stop when you have already seen the same remainder value.

Here are some test cases to show a few different scenarios:

divide(0, 0)     // "ERROR"
divide(1, 2)     // "0.5(0)"
divide(0, 3)     // "0.(0)"
divide(10, 3)    // "3.(3)"
divide(22, 7)    // "3.(142857)"
divide(100, 145) // "0.(6896551724137931034482758620)"

If you are interested in a solution written in Go, you can find it here https://github.com/shomali11/util


问:
codeigniter mail sending error 451
Can any one tell me why I'm getting this error with codeigniter when it comes to sending mail.

some time it work fine some times i get this error

451 Please try again later
The following SMTP error was encountered: 451 Please try again later
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.

答: Are you sure your SMTP server is working fine at the time you get this error? If it works sometimes, then that means that your configuration is probably fine. I'd deploy the code of a test server online and then run your code to see if its really a configuration problem or maybe a problem with the SMTP host that you're trying to send the mail through.</p>

Title: codeigniter mail sending error 451


问:
Getting a crash in NSTask
I've had a report from the field of a crash at -launch on NSTask.

The code in question is:

```<code>NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/zsh"];
if(ignore)
{
    [task setArguments:@[scriptPath, recordingFolder, Argument]];
}
else
{
    [task setArguments:@[scriptPath, recordingFolder]];
}

NSPipe *outPipe = [NSPipe pipe];
[task setStandardOutput:outPipe];

NSPipe *errorPipe = [NSPipe pipe];
[task setStandardError:errorPipe];

[task launch];
</code>```

The scriptPath is a script that is included in the app bundle.
The crash says:

```<code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to set posix_spawn_file_actions for fd -1 at index 0 with errno 9'
</code>```

What could be the cause of this? What file descriptor do the posix_spawn_file_actions refer to? Does it mean that the executable script is wrong or that the outPipe or errPipe are not well formed?

I believe it is referring to the posix_spawn function:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/posix_spawn.2.html

And errno 9 is EBADF (bad file number).

答:
If you are calling this code many different times sequentially, you are running out of file descriptors -- you need to close the pipes after you are done. The correct way to do it is to deallocate NSTask and it will close the file channels. Put the NSTask-related code in an autoreleasepool statement:</p>

```<code>@autoreleasepool {
  NSTask* task = [NSTask new];
  ...
  [task launch];
  ...
  [task waitUntilDone];
}
</code>```

Title: Getting a crash in NSTask

Body:
I've had a report from the field of a crash at -launch on NSTask.

The code in question is:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/zsh"];
if(ignore)
{
    [task setArguments:@[scriptPath, recordingFolder, Argument]];
}
else
{
    [task setArguments:@[scriptPath, recordingFolder]];
}

NSPipe *outPipe = [NSPipe pipe];
[task setStandardOutput:outPipe];

NSPipe *errorPipe = [NSPipe pipe];
[task setStandardError:errorPipe];

[task launch];

The scriptPath is a script that is included in the app bundle.
The crash says:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to set posix_spawn_file_actions for fd -1 at index 0 with errno 9'

What could be the cause of this? What file descriptor do the posix_spawn_file_actions refer to? Does it mean that the executable script is wrong or that the outPipe or errPipe are not well formed?

I believe it is referring to the posix_spawn function:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/posix_spawn.2.html

And errno 9 is EBADF (bad file number).

Body:
If you are calling this code many different times sequentially, you are running out of file descriptors -- you need to close the pipes after you are done. The correct way to do it is to deallocate NSTask and it will close the file channels. Put the NSTask-related code in an autoreleasepool statement:

@autoreleasepool {
  NSTask* task = [NSTask new];
  ...
  [task launch];
  ...
  [task waitUntilDone];
}


问:
Unable to find sling project wizard in eclipse
I am new to sling and trying to create a sling project in eclipse but i am unable to find wizard and also i am unable to create a sling server.</p>

答:
I had installed AEM IDE tool into eclipse which included sling within it which was not allowing to include sling in the list of wizards.

I had to open a fresh eclipse window which had no AEM IDE tool installed in it and then install sling IDE tool which will able you to create sling project and also allow you to install sling server.