问:
OpenCover Cannot instrument .exe as no PDB/MDB could be loaded
I have a ASP.NET Core project(target to .NETFramework,Version=v4.6.1) that was working under VS2015.
When I converted to VS2017 I am not able to make OpenCover working.
When build.PS1 runs

C:\OpenCover\4.6.519\tools\OpenCover.Console.exe -register:user
  -target:"C:\Program Files\dotnet\dotnet.exe" -targetargs:" test "C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\AdminPortal.UnitTests.csproj"
  "
  -output:"C:\GitRepos\AdminPortal\Build..\OUTPUT\Test-Output\projectCoverageReport.xml"
  -log:Verbose  -oldStyle

the output (truncated for brevity) is the following:

C:\OpenCover\4.6.519\tools\OpenCover.Console.exe -register:user
  -target:"C:\Program Files\dotnet\dotnet.exe" -targetargs:" test "C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\AdminPortal.UnitTests.csproj"
  "
  -output:"C:\GitRepos\AdminPortal\Build..\OUTPUT\Test-Output\projectCoverageReport.xml"
  -log:Verbose  -oldStyle Executing: C:\Program Files\dotnet\dotnet.exe

  Cannot instrument C:\Program Files\dotnet\sdk\1.0.3\dotnet.dll as no
  PDB/MDB could be loaded
  ...
  Cannot instrument C:\Program Files\dotnet\sdk\1.0.3\Microsoft.TestPlatform.Build.dll as no PDB/MDB
  could be loaded

  Build started, please wait...

  ...

  Cannot instrument
  C:\Program Files\dotnet\sdk\1.0.3\NuGet.Packaging.dll as no PDB/MDB
  could be loaded

  Cannot instrument RefEmit_InMemoryManifestModule as no
  PDB/MDB could be loaded Build completed.

Test run for
   C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\bin\Debug\net461\AdminPortal.UnitTests.dll(.NETFramework,Version=v4.6.1)
  Cannot instrument C:\Program Files\dotnet\sdk\1.0.3\vstest.console.dll
  as no PDB/MDB could be loaded

  Cannot instrument C:\Program
  Files\dotnet\sdk\1.0.3\Microsoft.TestPlatform.CoreUtilities.dll as no
  PDB/MDB could be loaded

  Cannot instrument C:\Program
  Files\dotnet\sdk\1.0.3\Microsoft.VisualStudio.TestPlatform.ObjectModel.dll
  as no PDB/MDB could be loaded Microsoft (R) Test Execution Command
  Line Tool Version 15.0.0.0 Copyright (c) Microsoft Corporation.  All
  rights reserved.

Cannot instrument RefEmit_InMemoryManifestModule as no PDB/MDB could
  be loaded Build completed. Test run for
  C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\bin\Debug\net461\AdminPortal.UnitTests.dll(.NETFramework,Version=v4.6.1)
  Cannot instrument C:\Program Files\dotnet\sdk\1.0.3\vstest.console.dll
  as no PDB/MDB could be loaded Microsoft (R) Test Execution Command
  Line Tool Version 15.0.0.0 Copyright (c) Microsoft Corporation.  All
  rights reserved. Starting test execution, please wait...

   ... Cannot
  instrument C:\Program
  Files\dotnet\sdk\1.0.3\TestHost\msdia140typelib_clr0200.dll as no
  PDB/MDB could be loaded

  Cannot instrument
  C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\bin\Debug\net461\AdminPortal.exe
  as no PDB/MDB could be loaded ...

Total tests: 39. Passed: 37. Failed: 0. Skipped: 2. Test Run
  Successful. Test execution time: 6.4838 Seconds

Committing...

   No results, this could be for a number of reasons. The
  most common reasons are:

      1) missing PDBs for the assemblies that match the filter please review the
      output file and refer to the Usage guide (Usage.rtf) about filters.

      2) the profiler may not be registered correctly, please refer to the Usage
      guide and the -register switch.

I  have the .PDB files in bin folder (e.g. C:\GitRepos\AdminPortal\Source\test\AdminPortal.UnitTests\bin\Debug\net461\AdminPortal.pdb),
so I don't know why opencover couldn't load it. What could be the reason?

I tried to specify  -targetdir:(as suggested here ) and -oldStyle , but it has no difference.

I also tried to specify -searchdirs: (from https://github.com/sawilde/opencover/wiki/Usage)
and re-register profiler
regsvr32 /n /i:user C:OpenCover.4.5.3723\x86\OpenCover.Profiler.dll (From OpenCover/NUnit can't find PDB files) - also make no difference.

Is it related to new portable PDB format mentioned in https://github.com/OpenCover/opencover/issues/610 ?

But I target NETFramework v4.6.1, not Core 1.1.  Can I explicitly specify to dotnet test or msbuild, which PDB format to use?

Is any tool available to show, does the .PDB file  has old or new  format ?
I tried https://github.com/Microsoft/microsoft-pdb/blob/master/cvdump/cvdump.exe as suggested at Reading a .pdb file,
but it does not return anything.

答:
In unrelated discussion https://developercommunity.visualstudio.com/content/problem/15197/vs2017rc-locks-files-in-obj-folder-blocking-builds.html it was suggested to
Change the PDB format in the project properties from Portable PDB to Full PDB.

If you prefer to use UI, in Visual Studio open
Project Properties->Build ->Advanced->Output->Debugging Information change to Full from Portable.
It will add to  csproj file setting with specific build condition

```<code><PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard1.6|AnyCPU'">
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>
</code>```

Normally you want to apply it for all options, so Remove the condition to have just the following (You can just paste the PropertyGroup below to your .csproj, if you didn't use Visual Studio before)

```<code><PropertyGroup >
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>
</code>```

And OpenCover will be able to instrument your projects.

Update 19 Apr 2019: As OpenCover still doesn’t have .net core support #595, consider to use CoverLet, that has OpenCover compatible output format.

Body:
In unrelated discussion https://developercommunity.visualstudio.com/content/problem/15197/vs2017rc-locks-files-in-obj-folder-blocking-builds.html it was suggested to
Change the PDB format in the project properties from Portable PDB to Full PDB.

If you prefer to use UI, in Visual Studio open
Project Properties->Build ->Advanced->Output->Debugging Information change to Full from Portable.
It will add to  csproj file setting with specific build condition

<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard1.6|AnyCPU'">
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>

Normally you want to apply it for all options, so Remove the condition to have just the following (You can just paste the PropertyGroup below to your .csproj, if you didn't use Visual Studio before)

<PropertyGroup >
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>

And OpenCover will be able to instrument your projects.

Update 19 Apr 2019: As OpenCover still doesn’t have .net core support #595, consider to use CoverLet, that has OpenCover compatible output format.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to run integration task after run task in gradle?
My Application is Spring boot application exposing some rest api

To run  my integration tests , , first the application need to be up and running , as my application gradle based , how to make sure when i execute  gradle command from command prompt , first application run and the integration tests will run .

```<code>task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') {
    testClassesDir = sourceSets.integration.output.classesDir
    classpath = sourceSets.integration.runtimeClasspath
    outputs.upToDateWhen { false }
}

task appRunAndIntegrtationTest {
    dependsOn 'run'
    dependsOn 'integration'
    tasks.findByName('integration').mustRunAfter 'run'
}
</code>```

i added above code to build.gradle , but application up and running , thats it , it stayed their only , integration tests are not running , can anyone has idea on this please .

update : @Strelok , as mentioned , the application started up and integration task is not running .

update 1 : i found one gradle plugin

https://github.com/marc0der/gradle-spawn-plugin

i am trying to use like below

```<code>task startServer(type: SpawnProcessTask, dependsOn: 'assemble') {
    command "java -jar ${projectDir}/build/libs/example.jar"
    ready 'Started Application'
}

task stopServer(type: KillProcessTask)
</code>```

but am getting below exception

*> Could not get unknown property 'SpawnProcessTask' for root project 'example-api' of type org.gradle.api.Project.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.*

please someone please suggest on this

答:
I suggest a different approach: start and stop your application from your test framework. Test frameworks support setup and cleanup steps for your test suite (e.g. BeforeClass and AfterClass in JUnit), start the application in the setup step and stop it in the cleanup step. This approach will make your tests more self-contained, their success/failure will not depend on factors outside the test code.

Even if you prefer to run the application outside the test framework, I suggest wrapping this logic (i.e. starting the app, running the tests, stopping the app) in a Java class, and executing this class from Gradle via a task of type JavaExec. It will be much more clear than handling all this via Gradle tasks.

Finally, if you still insist on Gradle tasks, it's like the commenters said: the "run" task probably blocks execution while the app is running. Tha only sane way to handle this is to have a task that starts the app in the background, and another that stops it after the tests finished (use finalizedBy).

ContentLicense: CC BY-SA 3.0

Body:
My Application is Spring boot application exposing some rest api

To run  my integration tests , , first the application need to be up and running , as my application gradle based , how to make sure when i execute  gradle command from command prompt , first application run and the integration tests will run .

task integration(type: Test, description: 'Runs the integration tests.', group: 'Verification') {
    testClassesDir = sourceSets.integration.output.classesDir
    classpath = sourceSets.integration.runtimeClasspath
    outputs.upToDateWhen { false }
}

task appRunAndIntegrtationTest {
    dependsOn 'run'
    dependsOn 'integration'
    tasks.findByName('integration').mustRunAfter 'run'
}

i added above code to build.gradle , but application up and running , thats it , it stayed their only , integration tests are not running , can anyone has idea on this please .

update : @Strelok , as mentioned , the application started up and integration task is not running .

update 1 : i found one gradle plugin

https://github.com/marc0der/gradle-spawn-plugin

i am trying to use like below

task startServer(type: SpawnProcessTask, dependsOn: 'assemble') {
    command "java -jar ${projectDir}/build/libs/example.jar"
    ready 'Started Application'
}

task stopServer(type: KillProcessTask)

but am getting below exception

*> Could not get unknown property 'SpawnProcessTask' for root project 'example-api' of type org.gradle.api.Project.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.*

please someone please suggest on this


问:
Get deadlock detection from running programm or dump in Java
I have a piece of running java software that is jammed. I would like to get a view inside but have got no idea how to do that.

Is there some tool that I can give a PID and it will tell me where every thread is currently located and maybe a few values of the variables as well? I'm running linux.

I more or less know what is causing the problem, but there a still a few possible cases, therefor pinpointing it would be nice.

I can't reproduce the error because it only appears every few days and never appeared while debugging, so this is a unique change of getting to know the enemy.

Any ideas?

答: On recent JVMs (OpenJDK/Oracle Java 7 or above), if you take a heap dump (using either VisualVM or jmap), it also includes a dump of the stacks of all currently running threads, with links to the corresponding objects in the heap. You can then view the stacks by opening the heap dump in VisualVM.</p>


问:
Javascript Expression - data extraction
I'm not very familiar with english and still less with javascript, sorry for that.

I have lots of extracted datas in a field named LT, I need to extract a particular data from LT field in javascript, this data is a number after "Relevé N° :" or sometimes after "N° de relevé :" expression is never exactly the same.

I actually use that: record.fields.LT.substring(record.fields.LT.indexOf("relev")).slice(10, 19);

But that dont match because sometimes there is more than one space or the "R" is uppercase etc..

Some help would be appreciated ;-)

Thanks
Bryan

EDIT: thank you both for your answers, here is some screenshots for a better understanding 1

I try first suggestion and it ask for missing ; and ) but when i add it, nothing remain in field as you can see on picture2 2

and when i try second answer, there is a syntax problem(seems to be the "(?:")

答:
I am not sure what you are asking for, but as per my understanding, the following regex should help.

```<code> (?:((Relevé N° : )|(N° de relevé : )))[0-9]{7,8}
</code>```

This uses a non-capturing group (not available in all regex implementations.) It will say, hey the String better have phrase like Relevé N° : or N° de relevé :, but I don't want this phrase to be part of my match, just the numbers (which is of length of 7 or 8) that follow.

Hope this helps! :)

Title: Javascript Expression - data extraction

Body:
I am not sure what you are asking for, but as per my understanding, the following regex should help.

 (?:((Relevé N° : )|(N° de relevé : )))[0-9]{7,8}

This uses a non-capturing group (not available in all regex implementations.) It will say, hey the String better have phrase like Relevé N° : or N° de relevé :, but I don't want this phrase to be part of my match, just the numbers (which is of length of 7 or 8) that follow.

Hope this helps! :)


答:
If the pattern you are looking for is only either 'Relevé N° :' or 'N° de relevé :' case insentitive, you can use a regex to capture the number that follows.

var testStrings = [
      "abc Relevé N° :12345678 string1",
      "123Relevé N° :1234567 string2",
      "aRelevé N° :1234567 string3",
      "N° de relevé :12345678 string4",
      "abc N° de relevé :12345678 string5"
    ];
    var myRegexp = /(Relevé N° :|N° de relevé :)([0-9]{7,8})/i;
    testStrings.forEach(function(str) {
      var match = myRegexp.exec(str)
      console.log(str + '   -> ' + match[2])
    })```

Title: Javascript Expression - data extraction

Body:
I'm not very familiar with english and still less with javascript, sorry for that.

I have lots of extracted datas in a field named LT, I need to extract a particular data from LT field in javascript, this data is a number after "Relevé N° :" or sometimes after "N° de relevé :" expression is never exactly the same.

I actually use that: record.fields.LT.substring(record.fields.LT.indexOf("relev")).slice(10, 19);

But that dont match because sometimes there is more than one space or the "R" is uppercase etc..

Some help would be appreciated ;-)

Thanks
Bryan

EDIT: thank you both for your answers, here is some screenshots for a better understanding 1

I try first suggestion and it ask for missing ; and ) but when i add it, nothing remain in field as you can see on picture2 2

and when i try second answer, there is a syntax problem(seems to be the "(?:")


问:
C++ "const" keyword explanation
When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

```<code>const int x = 5;
</code>```

I know that this means that x is a constant variable and probably stored in read-only memory.

But what are

```<code>void myfunc( const char x );
</code>```

and

```<code>int myfunc( ) const;
</code>```

?

答:
The const qualifier means that a variable/pointer defined as const may not be changed by your program and it will receive its value either from an explicit initialization or by a hardware-dependent means.

A pointer that is defined as const in the parameter declarations, the function code will not modify what it points to. Basically, you can use the pointer and it pretty much functions as a "read-only".

For example:-

```<code>void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') cout << '-'; //printing - when a space is encountered
        else cout << *x;
        x++;
    }
}
</code>```

The above function is fine and won't show any errors. But if foo had any thing that could change the string passed. say a function that replaces spaces with $. Not print $ but changing it to $. Something like this:-

```<code>void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') *x = '$'; //printing - when a space is encountered
        else cout << *x;
        x++;
    }
}
</code>```

then it would not compile i.e. an assignment error to a read-only memory location.

ContentLicense: CC BY-SA 2.5

Title: C++ "const" keyword explanation

Body:
When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

const int x = 5;

I know that this means that x is a constant variable and probably stored in read-only memory.

But what are

void myfunc( const char x );

and

int myfunc( ) const;

?

Body:
The const qualifier means that a variable/pointer defined as const may not be changed by your program and it will receive its value either from an explicit initialization or by a hardware-dependent means.

A pointer that is defined as const in the parameter declarations, the function code will not modify what it points to. Basically, you can use the pointer and it pretty much functions as a "read-only".

For example:-

void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') cout << '-'; //printing - when a space is encountered
        else cout << *x;
        x++;
    }
}

The above function is fine and won't show any errors. But if foo had any thing that could change the string passed. say a function that replaces spaces with $. Not print $ but changing it to $. Something like this:-

void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') *x = '$'; //printing - when a space is encountered
        else cout << *x;
        x++;
    }
}

then it would not compile i.e. an assignment error to a read-only memory location.


问:
Mapping a generated database column to a Grails domain class property
In my Grails 2.5.X app, I have a domain class that looks like this:

```<code>class FormData {

    String submittedFields
    Boolean submitted

    static constraints = {
        submittedFields nullable: true
    }

    static mapping = {
        // can I do something here to map submitted to a generated
        // column of the form_data table
    }
}
</code>```

I would like to map the submitted property to a generated column of the form_data table, i.e. a column that would be created by the SQL statement

```<code>alter table form_data add submitted tinyint
GENERATED ALWAYS AS (if(submitted_fields is null,0,1));
</code>```

Specifically, this generated column should be created when I create the schema from the domain model, e.g. by running the schema-export script.

A consequence of submitted being mapped to a generated column is that the corresponding domain class property should be read-only, or at least, assigning a value to it should have no effect.

答:
If you want to handle the value of the column on database side only, and dont want it to be inserted or updated from grails/hibernate side. you can make the column as insertable:false updatetable:false

```<code>static mapping = {
 submitted insertable:false, updateable:false
}
</code>```

Now, even if the value is changed in grails, the new value will not be updated in database.

Body:
In my Grails 2.5.X app, I have a domain class that looks like this:

class FormData {

    String submittedFields
    Boolean submitted

    static constraints = {
        submittedFields nullable: true
    }

    static mapping = {
        // can I do something here to map submitted to a generated
        // column of the form_data table
    }
}

I would like to map the submitted property to a generated column of the form_data table, i.e. a column that would be created by the SQL statement

alter table form_data add submitted tinyint
GENERATED ALWAYS AS (if(submitted_fields is null,0,1));

Specifically, this generated column should be created when I create the schema from the domain model, e.g. by running the schema-export script.

A consequence of submitted being mapped to a generated column is that the corresponding domain class property should be read-only, or at least, assigning a value to it should have no effect.

Body:
If you want to handle the value of the column on database side only, and dont want it to be inserted or updated from grails/hibernate side. you can make the column as insertable:false updatetable:false

static mapping = {
 submitted insertable:false, updateable:false
}

Now, even if the value is changed in grails, the new value will not be updated in database.


问:
Divide string before integer value using php
I have some random type string and I want them to separate from each other.
My string is like these:

```<code> 1.  GPF#: AUDITKT0059 800,126.00
 2.  GPF#: IV EMP KK 8 58,971.00
 3.  GPF#: GAKU 000006 317,253.00
</code>```

I want to get the GPF value but the issue is last values coming with string.I just want the value like AUDITKT0059,IV EMP KK 8 and GAKU 000006.I tried by exploding with GPF and then space but this not the way it works.So any suggestion? Thanks
I tried like this :

```<code>$gpf = explode("GPF#:", $data[$c]);

             $gpfs = explode(" ", $gpf[1]);
             print_r($gpfs);
            echo " GPF# ".$gpfs[0]."<br />\n";
</code>```

答:
Here I use Regular Expression to extract data, please try

```<code>$data = [
    "GPF#: AUDITKT0059 800,126.00",
    "GPF#: IV EMP KK 8 58,971.00",
    "GPF#: GAKU 000006 317,253.00",
];
foreach ($data as $string) {
    $match = [];
    preg_match("/^GPF#: ([A-Z0-9 ]{11}) .*$/", $string, $match);
    echo "GPF#: " . $match[1], PHP_EOL;
}
</code>```

The result will be

```<code>GPF#: AUDITKT0059
GPF#: IV EMP KK 8
GPF#: GAKU 000006
</code>```

Body:
I have some random type string and I want them to separate from each other.
My string is like these:

 1.  GPF#: AUDITKT0059 800,126.00
 2.  GPF#: IV EMP KK 8 58,971.00
 3.  GPF#: GAKU 000006 317,253.00

I want to get the GPF value but the issue is last values coming with string.I just want the value like AUDITKT0059,IV EMP KK 8 and GAKU 000006.I tried by exploding with GPF and then space but this not the way it works.So any suggestion? Thanks
I tried like this :

$gpf = explode("GPF#:", $data[$c]);

             $gpfs = explode(" ", $gpf[1]);
             print_r($gpfs);
            echo " GPF# ".$gpfs[0]."
\n";

Body:
Here I use Regular Expression to extract data, please try

$data = [
    "GPF#: AUDITKT0059 800,126.00",
    "GPF#: IV EMP KK 8 58,971.00",
    "GPF#: GAKU 000006 317,253.00",
];
foreach ($data as $string) {
    $match = [];
    preg_match("/^GPF#: ([A-Z0-9 ]{11}) .*$/", $string, $match);
    echo "GPF#: " . $match[1], PHP_EOL;
}

The result will be

GPF#: AUDITKT0059
GPF#: IV EMP KK 8
GPF#: GAKU 000006


问:
Why does one method for allocating memory fail compared to another that works?
If my intention was to create a dynamically sized array of structs. Could someone explain to me how one method that allocates memory to resize the array works the way it should; compared to one that fails after x number of elements are added to the array?

The following method uses malloc() (incorrectly). Could someone explain how to properly allocate memory to the array?

```<code>struct some_struct{...data members...}*collection = NULL;
    int total_elements;
    int space_allocated; // the number of elements allocated to the array

    void resize_array(){
        if(total_elements == space_allocated) {
            if(space_allocated == 0)
                space_allocated =2;
            else
                space_allocated *= 2;
            //where collection is a pointer to a struct
            collection = malloc(space_allocated * sizeof(struct some_struct));

            if(collection == NULL){
                fprintf(stderr,"NO MEMORY ALLOCATED");
                exit(EXIT_FAILURE);
            }
        }
    }
</code>```

Compared to another method that uses realloc() correctly to dynamically allocate memory for the array. What is the significance of a void* type variable used to hold the memory?

```<code>    void resize_array(){

        if(total_elements == space_allocated){
            if(space_allocated == 0)
                space_allocated = 2;
            else
                space_allocated *= 2;
                //why is a variable of type void allowed? What does that mean?
                void* tmp = realloc(collection, ((num_allocated)*
                sizeof(struct some_struct)));
                if(!_tmp){
                    fprintf(stderr,"NO MEMORY ALLOCATED");
                    exit(EXIT_FAILURE);
                }
                //what is the significance of the pointer cast?
                collection = (some_struct*) _tmp;
        }
    }
</code>```

答:
You can use a void * type, but I prefer to use the correct type

```<code>struct some_struct *tmp = realloc(collection, num_allocated * sizeof *tmp);
</code>```

The temporary variable is used to avoid memory leaks in the error path:

```<code>if (!tmp) {
    perror("realloc()");
    free(collection);
    goto err;
}

collection = tmp;
</code>```

You can always use realloc() when collection is initialized as NULL.  But you should verify that num_allocated * sizeof *tmp does not overflow.

Body:
If my intention was to create a dynamically sized array of structs. Could someone explain to me how one method that allocates memory to resize the array works the way it should; compared to one that fails after x number of elements are added to the array?

The following method uses malloc() (incorrectly). Could someone explain how to properly allocate memory to the array?

struct some_struct{...data members...}*collection = NULL;
    int total_elements;
    int space_allocated; // the number of elements allocated to the array

    void resize_array(){
        if(total_elements == space_allocated) {
            if(space_allocated == 0)
                space_allocated =2;
            else
                space_allocated *= 2;
            //where collection is a pointer to a struct
            collection = malloc(space_allocated * sizeof(struct some_struct));

            if(collection == NULL){
                fprintf(stderr,"NO MEMORY ALLOCATED");
                exit(EXIT_FAILURE);
            }
        }
    }

Compared to another method that uses realloc() correctly to dynamically allocate memory for the array. What is the significance of a void* type variable used to hold the memory?

    void resize_array(){

        if(total_elements == space_allocated){
            if(space_allocated == 0)
                space_allocated = 2;
            else
                space_allocated *= 2;
                //why is a variable of type void allowed? What does that mean?
                void* tmp = realloc(collection, ((num_allocated)*
                sizeof(struct some_struct)));
                if(!_tmp){
                    fprintf(stderr,"NO MEMORY ALLOCATED");
                    exit(EXIT_FAILURE);
                }
                //what is the significance of the pointer cast?
                collection = (some_struct*) _tmp;
        }
    }

Body:
You can use a void * type, but I prefer to use the correct type

struct some_struct *tmp = realloc(collection, num_allocated * sizeof *tmp);

The temporary variable is used to avoid memory leaks in the error path:

if (!tmp) {
    perror("realloc()");
    free(collection);
    goto err;
}

collection = tmp;

You can always use realloc() when collection is initialized as NULL.  But you should verify that num_allocated * sizeof *tmp does not overflow.


问:
IONIC 2 Native Push Notification Neither Redirecting nor showing
Previously I was using Ionic cloud PUSH and everything was working fine. Now I want to manage it from my server.

I already have had installed phonegap-plugin-push with sender ID as the same was being used by IONIC cloud push.

Imported the Native PUSH:

```<code>import { StatusBar, Splashscreen, GoogleAnalytics, Push } from 'ionic-native'; // Native Push
</code>```

Below is how I have initiated PUSH:

```<code>let push = Push.init({
      android: {
        icon: "blicon",
        iconColor: "#AE2829",
        senderID: Config.fcmSenderID
      },
      ios: {
        alert: "true",
        badge: "true",
        sound: "true"
      },
      windows: {}
});
</code>```

Below is how Device token is getting saved to server, working fine:-

```<code>push.on('registration', (data) => {

    // SAVE TO Server
        this.device_details.device_token = data.registrationId;
        var form = new FormData();
        form.append("user_device_token", this.device_details.device_token);
        form.append("user_device_type", this.device_details.device_type);
        //console.log(form);
        this.webService.saveToken(form)
        .subscribe(response => {
           console.log(response.message);
        }, error => {
           console.log("Oooops!" + error);
        });
    // SAVE TO Server
});
</code>```

Everything is working as supposed so far and I am able to receive push notification in my device, now it comes to handle the receieved push parameter.

```<code>push.on('notification', function(data) {
    if(data.additionalData.foreground == false) {
        this.nav.push(DetailPage, {id: data.additionalData.pageid});
    } else {
        let confirm = this.alertCtrl.create({
          title: data.title,
          message: data.message,
          buttons: [
            {
              text: 'Check Later',
              role: 'cancel'
            },
            {
              text: 'Check Now',
              handler: () => {
                if(data.additionalData.postid !== undefined) {
                    this.nav.push(DetailPage, {id: data.additionalData.pageid});
                }
              }
            }
          ]
        });
        confirm.present();
    }
</code>```

Whenever I try to use ALERT command it pop'ups every value that I send with payload but nothing else happens.

It do not push to the detail page with ID parameter and do not even show the Alertcontrol box.

Please help me resolving this issue.

Thanks Sanny

答:
Setting up Ionic 2 App to generate device token
            For Android, follow FCM setup instructions. It will give you SERVER_KEY and SENDER_ID. SERVER_KEY is used by server to send push notification and SENDER_ID is used by device to generate device token. For iOS, nothing required to generate device token.</p>

```<code>        Replace YOUR_SENDER_ID in config.xml with above SENDER_ID

        <plugin name="phonegap-plugin-push" spec="1.8.2">
        <variable name="SENDER_ID" value="YOUR_SENDER_ID"/>
        </plugin>

        Add device token generation code in your main app constructor like below and replace YOUR_SENDER_ID in Push.init() method with above SENDER_ID

        import {Component, ViewChild} from "@angular/core";
        import {AlertController, Nav, Platform} from "ionic-angular";
        import {StatusBar} from "@ionic-native/status-bar";
        import {SplashScreen} from "@ionic-native/splash-screen";
        import {Push, PushObject, PushOptions} from "@ionic-native/push";
        import {TabsPage} from "../pages/tabs/tabs";
        import {DetailsPage} from "../pages/details/details";

        @Component({
        template: '<ion-nav [root]="rootPage"></ion-nav>'
        })
        export class Ionic2PushApp {
        @ViewChild(Nav) nav: Nav;
        rootPage: any;

        constructor(public platform: Platform,
                    public statusBar: StatusBar,
                    public splashScreen: SplashScreen,
                    public push: Push,
                    public alertCtrl: AlertController) {
            this.rootPage = TabsPage;
            platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();
            this.initPushNotification();
            });
        }

        initPushNotification() {
            if (!this.platform.is('cordova')) {
            console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
            return;
            }
            const options: PushOptions = {
            android: {
                senderID: "YOUR_SENDER_ID"
            },
            ios: {
                alert: "true",
                badge: false,
                sound: "true"
            },
            windows: {}
            };
            const pushObject: PushObject = this.push.init(options);

            pushObject.on('registration').subscribe((data: any) => {
            console.log("device token ->", data.registrationId);
            //TODO - send device token to server
            });

            pushObject.on('notification').subscribe((data: any) => {
            console.log('message', data.message);
            //if user using app and push notification comes
            if (data.additionalData.foreground) {
                // if application open, show popup
                let confirmAlert = this.alertCtrl.create({
                title: 'New Notification',
                message: data.message,
                buttons: [{
                    text: 'Ignore',
                    role: 'cancel'
                }, {
                    text: 'View',
                    handler: () => {
                    //TODO: Your logic here
                    this.nav.push(DetailsPage, {message: data.message});
                    }
                }]
                });
                confirmAlert.present();
            } else {
                //if user NOT using app and push notification comes
                //TODO: Your logic on click of push notification directly
                this.nav.push(DetailsPage, {message: data.message});
                console.log("Push notification clicked");
            }
            });

            pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
        }
        }
</code>```

Body:
Previously I was using Ionic cloud PUSH and everything was working fine. Now I want to manage it from my server.

I already have had installed phonegap-plugin-push with sender ID as the same was being used by IONIC cloud push.

Imported the Native PUSH:

import { StatusBar, Splashscreen, GoogleAnalytics, Push } from 'ionic-native'; // Native Push

Below is how I have initiated PUSH:

let push = Push.init({
      android: {
        icon: "blicon",
        iconColor: "#AE2829",
        senderID: Config.fcmSenderID
      },
      ios: {
        alert: "true",
        badge: "true",
        sound: "true"
      },
      windows: {}
});

Below is how Device token is getting saved to server, working fine:-

push.on('registration', (data) => {

    // SAVE TO Server
        this.device_details.device_token = data.registrationId;
        var form = new FormData();
        form.append("user_device_token", this.device_details.device_token);
        form.append("user_device_type", this.device_details.device_type);
        //console.log(form);
        this.webService.saveToken(form)
        .subscribe(response => {
           console.log(response.message);
        }, error => {
           console.log("Oooops!" + error);
        });
    // SAVE TO Server
});

Everything is working as supposed so far and I am able to receive push notification in my device, now it comes to handle the receieved push parameter.

push.on('notification', function(data) {
    if(data.additionalData.foreground == false) {
        this.nav.push(DetailPage, {id: data.additionalData.pageid});
    } else {
        let confirm = this.alertCtrl.create({
          title: data.title,
          message: data.message,
          buttons: [
            {
              text: 'Check Later',
              role: 'cancel'
            },
            {
              text: 'Check Now',
              handler: () => {
                if(data.additionalData.postid !== undefined) {
                    this.nav.push(DetailPage, {id: data.additionalData.pageid});
                }
              }
            }
          ]
        });
        confirm.present();
    }

Whenever I try to use ALERT command it pop'ups every value that I send with payload but nothing else happens.

It do not push to the detail page with ID parameter and do not even show the Alertcontrol box.

Please help me resolving this issue.

Thanks Sanny

Body:
Setting up Ionic 2 App to generate device token
            For Android, follow FCM setup instructions. It will give you SERVER_KEY and SENDER_ID. SERVER_KEY is used by server to send push notification and SENDER_ID is used by device to generate device token. For iOS, nothing required to generate device token.

        Replace YOUR_SENDER_ID in config.xml with above SENDER_ID

        <plugin name="phonegap-plugin-push" spec="1.8.2">
        <variable name="SENDER_ID" value="YOUR_SENDER_ID"/>
        </plugin>

        Add device token generation code in your main app constructor like below and replace YOUR_SENDER_ID in Push.init() method with above SENDER_ID

        import {Component, ViewChild} from "@angular/core";
        import {AlertController, Nav, Platform} from "ionic-angular";
        import {StatusBar} from "@ionic-native/status-bar";
        import {SplashScreen} from "@ionic-native/splash-screen";
        import {Push, PushObject, PushOptions} from "@ionic-native/push";
        import {TabsPage} from "../pages/tabs/tabs";
        import {DetailsPage} from "../pages/details/details";

        @Component({
        template: '<ion-nav [root]="rootPage"></ion-nav>'
        })
        export class Ionic2PushApp {
        @ViewChild(Nav) nav: Nav;
        rootPage: any;

        constructor(public platform: Platform,
                    public statusBar: StatusBar,
                    public splashScreen: SplashScreen,
                    public push: Push,
                    public alertCtrl: AlertController) {
            this.rootPage = TabsPage;
            platform.ready().then(() => {
            this.statusBar.styleDefault();
            this.splashScreen.hide();
            this.initPushNotification();
            });
        }

        initPushNotification() {
            if (!this.platform.is('cordova')) {
            console.warn("Push notifications not initialized. Cordova is not available - Run in physical device");
            return;
            }
            const options: PushOptions = {
            android: {
                senderID: "YOUR_SENDER_ID"
            },
            ios: {
                alert: "true",
                badge: false,
                sound: "true"
            },
            windows: {}
            };
            const pushObject: PushObject = this.push.init(options);

            pushObject.on('registration').subscribe((data: any) => {
            console.log("device token ->", data.registrationId);
            //TODO - send device token to server
            });

            pushObject.on('notification').subscribe((data: any) => {
            console.log('message', data.message);
            //if user using app and push notification comes
            if (data.additionalData.foreground) {
                // if application open, show popup
                let confirmAlert = this.alertCtrl.create({
                title: 'New Notification',
                message: data.message,
                buttons: [{
                    text: 'Ignore',
                    role: 'cancel'
                }, {
                    text: 'View',
                    handler: () => {
                    //TODO: Your logic here
                    this.nav.push(DetailsPage, {message: data.message});
                    }
                }]
                });
                confirmAlert.present();
            } else {
                //if user NOT using app and push notification comes
                //TODO: Your logic on click of push notification directly
                this.nav.push(DetailsPage, {message: data.message});
                console.log("Push notification clicked");
            }
            });

            pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
        }
        }


问:
Unable to set recyclerview below cardview
I am trying to set my recyclerview under the cardview but i don t know exactly the solution:

My layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="4dp"
            card_view:cardCornerRadius="4dp">

            <RelativeLayout
                android:id="@+id/rel"
                android:padding="10dp"
                android:layoutDirection="ltr"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/txt_competition"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/X"
                    android:textColor="#000000"
                    android:textAlignment="center"
                    android:textSize="18sp"
                    android:layout_marginTop="20dp"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                   />
                <LinearLayout
                    android:orientation="vertical"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:layout_gravity="start"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/linearLayout2">

                    <ImageView
                        android:id="@+id/image_team1"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:adjustViewBounds="true"
                        android:layout_gravity="start"
                        android:src="@drawable/placemahdi"
                        android:scaleType="fitXY"

                        />

                    <TextView
                        android:id="@+id/name_team1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="15sp"
                        android:layout_gravity="center"
                        android:textAlignment="center"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:orientation="vertical"
                    android:layout_marginRight="10dp"
                    android:layout_marginEnd="10dp"
                    android:id="@+id/linear_team2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end">

                    <ImageView
                        android:id="@+id/image_team2"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:layout_gravity="end"
                        android:src="@drawable/placemahdi"
                        android:adjustViewBounds="true"
                        />

                    <TextView
                        android:id="@+id/name_team2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:textAlignment="center"
                        android:textSize="15sp" />

                </LinearLayout>

                <TextView
                    android:textAlignment="center"
                    android:layout_centerInParent="true"
                    android:text="توقع النتيجة"
                    android:id="@+id/divide"
                    android:textColor="@android:color/holo_red_light"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_vote0"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_forwardplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignLeft="@+id/between"
                    android:layout_alignStart="@+id/between" />
                <Button
                    android:id="@+id/button_vote1"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_backplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true" />

                <TextView
                    android:id="@+id/between"
                    android:textSize="14sp"
                    android:text="0"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/button_vote1"
                    android:layout_alignRight="@+id/button_vote1"
                    android:layout_alignEnd="@+id/button_vote1"
                  />
                <Button
                    android:id="@+id/button_vote2"
                    android:text="X"
                    android:layout_centerHorizontal="true"
                    android:textColor="#FFFFFF"
                    android:layout_alignParentBottom="true"
                    android:textStyle="bold"
                    android:background="@drawable/round_button"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/button_vote01"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_backplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignRight="@+id/between1"
                    android:layout_alignEnd="@+id/between1" />
                <Button
                    android:id="@+id/button_vote10"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_forwardplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true" />

                <TextView
                    android:id="@+id/between1"
                    android:text="0"
                    android:textSize="14sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/button_vote10"
                    android:layout_alignLeft="@+id/button_vote10"
                    android:layout_alignStart="@+id/button_vote10"/>

            </RelativeLayout>

        </android.support.v7.widget.CardView>
    </android.support.v4.widget.SwipeRefreshLayout>

    <RelativeLayout
        android:id="@+id/re2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutDirection="ltr">

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_vote"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </android.support.v4.widget.NestedScrollView>

    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

I have tried to set the "re2" relativelayout gravity to center it works on many android phones but on smaller screen some of  recyclerview parts hide under the cardview.

I have tried also setting the gravity to bottom so it starts from bottom with marginbottom=15dp but also there s a lot of blank spaces between recyclerview and cardview

This is a screenshot for the layout:

How can i set the recyclerview to start directly below the cardview ?

答:
The reason your views are overlapping is because of the CoordinatorLayout. CoordinatorLayout extends a FrameLayout. These are designed to place views that overlap each other.

What you need is a ListView. It is specifically designed to show children in lists in the order that they are added in the XML file. So, if your CoordinatorLayout doesn't serve any other purpose, then change it to a LinearLayout. Something like the following :-

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearLayout"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
      .
      .
      .
      .

</LinearLayout>
</code>```

Body:
I am trying to set my recyclerview under the cardview but i don t know exactly the solution:

My layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardCornerRadius="4dp"
            card_view:cardCornerRadius="4dp">

            <RelativeLayout
                android:id="@+id/rel"
                android:padding="10dp"
                android:layoutDirection="ltr"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/txt_competition"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/X"
                    android:textColor="#000000"
                    android:textAlignment="center"
                    android:textSize="18sp"
                    android:layout_marginTop="20dp"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                   />
                <LinearLayout
                    android:orientation="vertical"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:layout_gravity="start"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/linearLayout2">

                    <ImageView
                        android:id="@+id/image_team1"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:adjustViewBounds="true"
                        android:layout_gravity="start"
                        android:src="@drawable/placemahdi"
                        android:scaleType="fitXY"

                        />

                    <TextView
                        android:id="@+id/name_team1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="15sp"
                        android:layout_gravity="center"
                        android:textAlignment="center"/>

                </LinearLayout>

                <LinearLayout
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:orientation="vertical"
                    android:layout_marginRight="10dp"
                    android:layout_marginEnd="10dp"
                    android:id="@+id/linear_team2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end">

                    <ImageView
                        android:id="@+id/image_team2"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:layout_gravity="end"
                        android:src="@drawable/placemahdi"
                        android:adjustViewBounds="true"
                        />

                    <TextView
                        android:id="@+id/name_team2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:textAlignment="center"
                        android:textSize="15sp" />

                </LinearLayout>

                <TextView
                    android:textAlignment="center"
                    android:layout_centerInParent="true"
                    android:text="توقع النتيجة"
                    android:id="@+id/divide"
                    android:textColor="@android:color/holo_red_light"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_vote0"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_forwardplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignLeft="@+id/between"
                    android:layout_alignStart="@+id/between" />
                <Button
                    android:id="@+id/button_vote1"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_backplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true" />

                <TextView
                    android:id="@+id/between"
                    android:textSize="14sp"
                    android:text="0"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/button_vote1"
                    android:layout_alignRight="@+id/button_vote1"
                    android:layout_alignEnd="@+id/button_vote1"
                  />
                <Button
                    android:id="@+id/button_vote2"
                    android:text="X"
                    android:layout_centerHorizontal="true"
                    android:textColor="#FFFFFF"
                    android:layout_alignParentBottom="true"
                    android:textStyle="bold"
                    android:background="@drawable/round_button"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/button_vote01"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_backplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignRight="@+id/between1"
                    android:layout_alignEnd="@+id/between1" />
                <Button
                    android:id="@+id/button_vote10"
                    android:layout_width="50dp"
                    android:layout_height="wrap_content"
                    android:background="@drawable/ic_forwardplus"
                    android:textStyle="bold"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true" />

                <TextView
                    android:id="@+id/between1"
                    android:text="0"
                    android:textSize="14sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignBaseline="@+id/button_vote10"
                    android:layout_alignLeft="@+id/button_vote10"
                    android:layout_alignStart="@+id/button_vote10"/>

            </RelativeLayout>

        </android.support.v7.widget.CardView>
    </android.support.v4.widget.SwipeRefreshLayout>

    <RelativeLayout
        android:id="@+id/re2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutDirection="ltr">

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_vote"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </android.support.v4.widget.NestedScrollView>

    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

I have tried to set the "re2" relativelayout gravity to center it works on many android phones but on smaller screen some of  recyclerview parts hide under the cardview.

I have tried also setting the gravity to bottom so it starts from bottom with marginbottom=15dp but also there s a lot of blank spaces between recyclerview and cardview

This is a screenshot for the layout:

How can i set the recyclerview to start directly below the cardview ?

Body:
The reason your views are overlapping is because of the CoordinatorLayout. CoordinatorLayout extends a FrameLayout. These are designed to place views that overlap each other.

What you need is a ListView. It is specifically designed to show children in lists in the order that they are added in the XML file. So, if your CoordinatorLayout doesn't serve any other purpose, then change it to a LinearLayout. Something like the following :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearLayout"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
      .
      .
      .
      .

</LinearLayout>


问:
codeigniter upload image store userfile in database rather than image name
Database output: userfile rather than image name?
rather than
CONTROLLER:
my upload directory is fine but when i use another method and call it when needed it doesnt give my desired output.. im very sorry for novicity

`

```<code> public function uploadImage()
    {
        $config['upload_path'] = './uploads/files';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '2048';
        $config['max_width'] = '2000';
        $config['max_height'] = '2000';
        $this->load->library('upload', $config);
        if ( !$this->upload->do_upload()){
            $error = array('error' => $this->upload->display_errors());
            echo "<script>window.alert('failed to load UserFile');</script>";
        }else{
            $data = array('upload_data' => $this->upload->data());
            $post_image = $_FILES['userfile']['name'];
            echo "<script>window.alert('your image has been successfully uploaded');</script>";
        }
    }
</code>```

`

```<code>public function signupPost()
{

    if ($this->form_validation->run('signup') == FALSE) {
        //fails wont continue to next page
        $this->signup_view();
    } else {
        //upload image
        $this->uploadImage();
        //insert data into the database
        $data = array(
            'userId' => $this->input->post('userId'),
            'userfile'  => $this->input->post('userfile'),
            );
        //user data has successfully signed up
        $this->User->signup_client($data);
        redirect('http://localhost/GFC/index.php/main','refresh');
    }
}
</code>```

VIEW:

```<code><?php
        $attributes = array("name" => "signupform");
        $hidden = array('userId' => 'userId', 'userfile' => 'userfile');
        echo form_open_multipart("Client_Dashboard/signupPost", $attributes, $hidden);
    ?>
<div class="w3-row">
                    <input type="file" name="userfile" size="20" style="margin-left:30%; margin-top:8%;"/>
                    <span class="text-danger"><?php echo form_error('userfile'); ?></span>
                </div>

    <div class="container" style="padding:0%;">
        <br>
        <input type="submit" value="Register" class=" w3-btn w3-teal w3-large w3-hover-white w3-padding-large" />

    </div>
        <?php echo form_close(); ?>
</code>```

答:
You are not specifying the input and not returning the name of image to your function</p>

```<code>function uploadImage() {
  $config['upload_path'] = './uploads/files';
  $config['allowed_types'] = 'gif|jpg|png|jpeg';
  $config['max_size'] = '2048';
  $config['max_width'] = '2000';
  $config['max_height'] = '2000';
  $this->load->library('upload', $config);

  if (!$this->upload->do_upload('userfile')){
    $error = array('error' => $this->upload->display_errors());
    // var_dump($error); die; // check error
  } else {
    $fileName = $this->upload->data();
    return $fileName;
  }
}

function signupPost() {

  if ($this->form_validation->run('signup') == FALSE) {
    // fails wont continue to next page
    $this->signup_view();
  } else {
    // upload image
    $data['UserFile'] = $this->uploadImage();
    // insert data into the database
    $data = array(
       'userId' => $this->input->post('userId'),
       'password' => $this->input->post('password'),
       'emailAddress' => $this->input->post('emailAddress'),
       'userfile'  => $this->input->post('userfile'),
       'branchId'  => $this->input->post('branchId')
    );

   // user data has successfully signed up
   $this->User->signup_client($data);
   redirect('http://localhost/GFC/index.php/main', 'refresh');
 }
}
</code>```

Body:
Database output: userfile rather than image name?
rather than
CONTROLLER:
my upload directory is fine but when i use another method and call it when needed it doesnt give my desired output.. im very sorry for novicity

`

 public function uploadImage()
    {
        $config['upload_path'] = './uploads/files';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '2048';
        $config['max_width'] = '2000';
        $config['max_height'] = '2000';
        $this->load->library('upload', $config);
        if ( !$this->upload->do_upload()){
            $error = array('error' => $this->upload->display_errors());
            echo "";
        }else{
            $data = array('upload_data' => $this->upload->data());
            $post_image = $_FILES['userfile']['name'];
            echo "";
        }
    }

`

public function signupPost()
{

    if ($this->form_validation->run('signup') == FALSE) {
        //fails wont continue to next page
        $this->signup_view();
    } else {
        //upload image
        $this->uploadImage();
        //insert data into the database
        $data = array(
            'userId' => $this->input->post('userId'),
            'userfile'  => $this->input->post('userfile'),
            );
        //user data has successfully signed up
        $this->User->signup_client($data);
        redirect('http://localhost/GFC/index.php/main','refresh');
    }
}

VIEW:

<?php
        $attributes = array("name" => "signupform");
        $hidden = array('userId' => 'userId', 'userfile' => 'userfile');
        echo form_open_multipart("Client_Dashboard/signupPost", $attributes, $hidden);
    ?>

                    <input type="file" name="userfile" size="20" style="margin-left:30%; margin-top:8%;"/>
                    <?php echo form_error('userfile'); ?>

        <input type="submit" value="Register" class=" w3-btn w3-teal w3-large w3-hover-white w3-padding-large" />

        <?php echo form_close(); ?>

Body:
You are not specifying the input and not returning the name of image to your function

function uploadImage() {
  $config['upload_path'] = './uploads/files';
  $config['allowed_types'] = 'gif|jpg|png|jpeg';
  $config['max_size'] = '2048';
  $config['max_width'] = '2000';
  $config['max_height'] = '2000';
  $this->load->library('upload', $config);

  if (!$this->upload->do_upload('userfile')){
    $error = array('error' => $this->upload->display_errors());
    // var_dump($error); die; // check error
  } else {
    $fileName = $this->upload->data();
    return $fileName;
  }
}

function signupPost() {

  if ($this->form_validation->run('signup') == FALSE) {
    // fails wont continue to next page
    $this->signup_view();
  } else {
    // upload image
    $data['UserFile'] = $this->uploadImage();
    // insert data into the database
    $data = array(
       'userId' => $this->input->post('userId'),
       'password' => $this->input->post('password'),
       'emailAddress' => $this->input->post('emailAddress'),
       'userfile'  => $this->input->post('userfile'),
       'branchId'  => $this->input->post('branchId')
    );

   // user data has successfully signed up
   $this->User->signup_client($data);
   redirect('http://localhost/GFC/index.php/main', 'refresh');
 }
}


问:
Changing email address every time in selenium
I need some good suggestions for my query. Actually i am writing the automation test suit for my integration environment using selenium cucumber. When i enter an email address and proceed to complete the process, then that email address will be stored in the database. So, i can't use the same address for next time in the next scenario, because it is already stored in database and its saying that you are already a user. Now i am changing email addresses before running my test suit manually. It is not a good approach because i need a full automation test suit. How to create a dynamic way to enter new email id automatically every time?</p>

答:
I would have my scenario clean the database before entering a well known e-mail address. This would remove the problem of creating a new e-mail address every time and introduce predictability into the process.

Trouble shooting something that has an element of randomness is something I would prefer to avoid at almost any cost.


问:
I want to pass a string to an obect
I am using a widget which uses class objects as follows:

```<code>$p->data = array(array(array('01-Jan-2017',200),array('02-Feb-2017',210)));
</code>```

but I want to build this array dynamically using data from a Db to extend the array structure  e.g.:

```<code>$wstr = "array(array(array('$varR1C1,$varR1C2),array('$varR2C1',$varR2C3),array('$varR3C1',$varR3C2),array(array('$varR4C1',$varR4C2),array('$varR5C1',$varR5C2),array('$varR6C1',$varR6C2)));"
</code>```

This would enable (with the widget) a Line Chart with 2 lines, each of 3 paired values. if I then try:

```<code>$p->data = $wstr;
</code>```

this doesn't work. How can I cast the string to the object? I have tried JSON_encode, but this doesn't work either i.e.:

```<code>$p->data = substr(json_encode($wstr),1,strlen(json_encode($wstr))-2)
</code>```

where substr gets rid of " from encode (have tried with & without!)

答:
If I understand correctly, in your PHP code you have variables $var1, $var2, $var3, and $var4 and you want to use these to populate the array instead of the hard-coded values in the example?

If so, why not simply

```<code>$p->data = array(array( array($var1, $var2), array($var3, $var4) ));
</code>```

?

BTW, with modern syntax (PHP 5.4 and later) we prefer to use a shorter syntax for arrays (and more familiar to people coming from other languages), in which your code will look like this:

```<code>$p->data = [ [ [$var1, $var2], [$var3, $var4] ] ];
</code>```

Title: I want to pass a string to an obect

Body:
I am using a widget which uses class objects as follows:

$p->data = array(array(array('01-Jan-2017',200),array('02-Feb-2017',210)));

but I want to build this array dynamically using data from a Db to extend the array structure  e.g.:

$wstr = "array(array(array('$varR1C1,$varR1C2),array('$varR2C1',$varR2C3),array('$varR3C1',$varR3C2),array(array('$varR4C1',$varR4C2),array('$varR5C1',$varR5C2),array('$varR6C1',$varR6C2)));"

This would enable (with the widget) a Line Chart with 2 lines, each of 3 paired values. if I then try:

$p->data = $wstr;

this doesn't work. How can I cast the string to the object? I have tried JSON_encode, but this doesn't work either i.e.:

$p->data = substr(json_encode($wstr),1,strlen(json_encode($wstr))-2)

where substr gets rid of " from encode (have tried with & without!)

Body:
If I understand correctly, in your PHP code you have variables $var1, $var2, $var3, and $var4 and you want to use these to populate the array instead of the hard-coded values in the example?

If so, why not simply

$p->data = array(array( array($var1, $var2), array($var3, $var4) ));

?

BTW, with modern syntax (PHP 5.4 and later) we prefer to use a shorter syntax for arrays (and more familiar to people coming from other languages), in which your code will look like this:

$p->data = [ [ [$var1, $var2], [$var3, $var4] ] ];


问:
Set orientation horizontal to items inside menu in a NavigationView
I have a NavigationView that has an app:headerLayout and an app:menu that has three groups of items. One of this groups is made for social media:

```<code>    <menu>
        <item
            android:id="@+id/nav_facebook"
            android:icon="@drawable/ic_facebook"
            android:title="@string/nav_drawer_facebook" />
        <item
            android:id="@+id/nav_twitter"
            android:icon="@drawable/ic_twitter"
            android:title="@string/nav_drawer_twitter" />
        <item
            android:id="@+id/nav_instagram"
            android:icon="@drawable/ic_instagram"
            android:title="@string/nav_drawer_instagram" />
        <item
            android:id="@+id/nav_google_plus"
            android:icon="@drawable/ic_google"
            android:title="@string/nav_drawer_googleplus" />
        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/ic_menu_share"
            android:title="@string/nav_drawer_share" />
    </menu>
</code>```

So my question is if there is any way to make the orientation of this menu horizontal:

At this moment it looks like this:

But I would like it to look like this:

I would like to show the icons next to the other to safe some space. I know I could achieve this doing a custom layout but I would like to know if there is a way to do this with the app:menu.

Any help would be appreciated. Thanxs in advance.

答:
Just add

```<code>app:actionLayout="@layout/action_layout"
</code>```

into an item,
where  action_layout is the layout that you want to show in horizontal orientation here is an example:

```<code><item
   android:id="@+id/nav_manage"
   android:title="layout"
   app:actionLayout="@layout/action_layout" />
</code>```

Body:
I have a NavigationView that has an app:headerLayout and an app:menu that has three groups of items. One of this groups is made for social media:

    <menu>
        <item
            android:id="@+id/nav_facebook"
            android:icon="@drawable/ic_facebook"
            android:title="@string/nav_drawer_facebook" />
        <item
            android:id="@+id/nav_twitter"
            android:icon="@drawable/ic_twitter"
            android:title="@string/nav_drawer_twitter" />
        <item
            android:id="@+id/nav_instagram"
            android:icon="@drawable/ic_instagram"
            android:title="@string/nav_drawer_instagram" />
        <item
            android:id="@+id/nav_google_plus"
            android:icon="@drawable/ic_google"
            android:title="@string/nav_drawer_googleplus" />
        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/ic_menu_share"
            android:title="@string/nav_drawer_share" />
    </menu>

So my question is if there is any way to make the orientation of this menu horizontal:

At this moment it looks like this:

But I would like it to look like this:

I would like to show the icons next to the other to safe some space. I know I could achieve this doing a custom layout but I would like to know if there is a way to do this with the app:menu.

Any help would be appreciated. Thanxs in advance.

Body:
Just add

app:actionLayout="@layout/action_layout"

into an item,
where  action_layout is the layout that you want to show in horizontal orientation here is an example:

<item
   android:id="@+id/nav_manage"
   android:title="layout"
   app:actionLayout="@layout/action_layout" />


问:
Cast Double to Integer in Java
Any way to cast java.lang.Double to java.lang.Integer?

It throws an exception

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"

答:
Try this one</p>

```<code>double doubleValue = 6.5;Double doubleObj = new Double(doubleValue);int intResult = doubleObj.intValue();
</code>```

Title: Cast Double to Integer in Java

Body:
Try this one

double doubleValue = 6.5;Double doubleObj = new Double(doubleValue);int intResult = doubleObj.intValue();


问:
Align elements vertically inside a div
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="welcomeArea">
<div class="welcomeAreaContent">
       <div class="welcomeName">
         TEXT TEXT
         <span class ="circle twittericon"></span>
       </div>
        <div class="verticalLine">
</div>
     </div>
  </div></code>```

The result looks like the following which is not good at all:

答:
You can align inline elements vertically using the vertical-align property.

```<code>.twittericon {
background: url(data:image/png;base64,...) no-repeat center;
background-color: white;
background-size: cover;
vertical-align: middle;
}
</code>```

Otherwise if they are block elements, you can use flexbox.

```<code><ul class="parent">
<li>2</li>
<li>1</li>
</ul>
<style>
.parent { display: flex; align-items: center; }
</style>
</code>```

Title: Align elements vertically inside a div

Body:
I'm trying to align elements vertically inside a div, but I'm stuck with circles.
The red div is 100% width, with my code, but the vertical line does not show, and the circles (that are divs or spans with background images) are not in the middle.

My code:

.welcomeArea{
    margin-top: 70px;
    max-height: 98px;
    height: 98px;
    background-color: #293847;

}

.welcomeAreaContent{
        line-height: 98px;
        color: white;
        margin-left: 5%;
    margin-right: 5%;

}
.welcomeAreaContent > span {
    display:inline-block;
}
.welcomeAreaContent .welcomeName{
    font-weight: bold;
    font-size: 1.7em;
}
.verticalLine {
  border-left: thick solid #ff0000;
  content: "";
}

.circle {
   width: 50px;
   height: 50px;
      border-radius: 50%;
    behavior: url(PIE.htc);
   -moz-border-radius: 50px;
   -webkit-border-radius: 50px;
   border-radius: 50px;
   margin-left: 32px;
   display: inline-block;
}
.twittericon{
    background: url('data:image/png;base64,...') no-repeat center;
    background-color: white;
     background-size: cover;

}

         TEXT TEXT

The result looks like the following which is not good at all:

Body:
You can align inline elements vertically using the vertical-align property.

.twittericon {
background: url(data:image/png;base64,...) no-repeat center;
background-color: white;
background-size: cover;
vertical-align: middle;
}

Otherwise if they are block elements, you can use flexbox.

<ul class="parent">
<li>2</li>
<li>1</li>
</ul>
<style>
.parent { display: flex; align-items: center; }
</style>


问:
Optimization - how to store "bits" in memory?
I'm a newbie in Python and I have a problem with storing information. I've got a task from my 'mentor' and I don't know how to do that.
I have array with numbers 0 and 1, e.g.

```<code>a=[1,1,1,0]
</code>```

I know that's integers, but he told I should keep it as bits.
I was trying to convert my variable to number e.g:

a = 14 and then ab = bin(14).

But when I'm using sys.getsizeof() ab is bigger than a.
I was trying to use bytearray() but I don't understand it, too.
I was thinking that I know how a computer works, but that makes me confused.

How should I keep bits? What should I use? What should I read to understand it? and how to measure how big is my variable (sys.getsizeof() is okay for that? Or should I write it to a binary file?).
We doing it to optimize memory.

答:
I'm not sure I understand the goal, but here's a guess:

```<code>def convert(bits):
    val = 0
    for bit in bits:
        val = (val << 1) | bit
    return val

a = [1, 1, 1, 0]
ab = convert(a)
print(ab, bin(ab))  # -> 14 0b1110
</code>```

The result stored in ab is a single Python integer, which have varying lengths depending on how many bits are required to hold the number. The code above will handle any number of bits (but you could put a limit on it).

Body:
I'm a newbie in Python and I have a problem with storing information. I've got a task from my 'mentor' and I don't know how to do that.
I have array with numbers 0 and 1, e.g.

a=[1,1,1,0]

I know that's integers, but he told I should keep it as bits.
I was trying to convert my variable to number e.g:

a = 14 and then ab = bin(14).

But when I'm using sys.getsizeof() ab is bigger than a.
I was trying to use bytearray() but I don't understand it, too.
I was thinking that I know how a computer works, but that makes me confused.

How should I keep bits? What should I use? What should I read to understand it? and how to measure how big is my variable (sys.getsizeof() is okay for that? Or should I write it to a binary file?).
We doing it to optimize memory.

Body:
I'm not sure I understand the goal, but here's a guess:

def convert(bits):
    val = 0
    for bit in bits:
        val = (val << 1) | bit
    return val

a = [1, 1, 1, 0]
ab = convert(a)
print(ab, bin(ab))  # -> 14 0b1110

The result stored in ab is a single Python integer, which have varying lengths depending on how many bits are required to hold the number. The code above will handle any number of bits (but you could put a limit on it).


问:
prepare to focus first active element in a container
I have a container on a page that should be prepared for focusing, i.e. when user pressed TAB button, the first active element in the container must be focused.

The simplest way I have thought so far is to find the last active element before the container, focus it and then blur it. Will it work? Is there a simpler way? How to find the last active element before the container (cross-browser)?

I do not want to change tabbed elements order, I just want to define the next element that will be selected.

Please use raw javascript, not frameworks.

答:
The only thing I can think of is looping over the container child nodes and try focusing them until you succeed:

```<code><script type="text/javascript">
document.onkeyup = function (e) {
    if (!e)
        e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) {
      FocusFirst(document.getElementById("MyContainer"));
    }
}

function FocusFirst(element) {
    try {
        element.focus();
    }
    catch(ex) {}

    if (document.activeElement == element)
        return true;

    for (var i = 0; i < element.childNodes.length; i++) {
        var oChild = element.childNodes[i];
        if (FocusFirst(oChild))
            return true;
    }

    return false;
}
</script>
</code>```

Sample HTML tested with: (IE, Chrome)

```<code><div id="MyContainer">
    <div>hello</div>
    <div><span><input type="text" /></span></div>
    <div><input type="text" /></div>
</div>
</code>```

This will focus the first input box of the container upon tab click.

Body:
The only thing I can think of is looping over the container child nodes and try focusing them until you succeed:

<script type="text/javascript">
document.onkeyup = function (e) {
    if (!e)
        e = window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) {
      FocusFirst(document.getElementById("MyContainer"));
    }
}

function FocusFirst(element) {
    try {
        element.focus();
    }
    catch(ex) {}

    if (document.activeElement == element)
        return true;

    for (var i = 0; i < element.childNodes.length; i++) {
        var oChild = element.childNodes[i];
        if (FocusFirst(oChild))
            return true;
    }

    return false;
}
</script>

Sample HTML tested with: (IE, Chrome)

<div id="MyContainer">
    <div>hello</div>
    <div><span><input type="text" /></span></div>
    <div><input type="text" /></div>
</div>

This will focus the first input box of the container upon tab click.


问:
How to connect to github repository using java and github api
I need to create remote Github repository using java (Using my credentials) and I need to push .Json file to that repo.

I saw some examples using JGit and some other references like http://www.codeaffine.com/2015/11/30/jgit-clone-repository/

I've written small code

```<code>GitHubClient client = new GitHubClient();
client.setCredentials("username", "password");
RepositoryService service = new RepositoryService(client);
Repository repo=new Repository(); repo.setName("newRepo");
service.createRepository(repo);
</code>```

It isn't working

Please help me with a working example. That would be really helpful.

答:
You will find working examples in centic9/jgit-cookbook, regarding:

Repository repository = createNewRepository();

git push (which can push any file you have added/commit, JSON or not)

Body:
I need to create remote Github repository using java (Using my credentials) and I need to push .Json file to that repo.

I saw some examples using JGit and some other references like http://www.codeaffine.com/2015/11/30/jgit-clone-repository/

I've written small code

GitHubClient client = new GitHubClient();
client.setCredentials("username", "password");
RepositoryService service = new RepositoryService(client);
Repository repo=new Repository(); repo.setName("newRepo");
service.createRepository(repo);

It isn't working

Please help me with a working example. That would be really helpful.


问:
Flexbox bug in Internet Explorer 11
I'm having some problems in Internet Explorer 11 with a flexbox grid on this page: http://showit.magnetix.dk/jeppe/sdc-academy/

The section .modules-overview works as wanted, but the .news section (in the top) doesn't. However, the CSS used in very similar, so I can't figure out what the problem is.

Any suggestions or solutions?

Normally I would post useful code here, but since this is a flexbox bug specific for IE11 I felt it was better to post the link above.

答:
Can you try adding.</p>

```<code>.news__item {
     flex: 1 0 25%;
}
</code>```

Title: Flexbox bug in Internet Explorer 11

Body:
Can you try adding.

.news__item {
     flex: 1 0 25%;
}


问:
How do I copy only the required rows from one csv file to other csv file using python?
I am trying to write a program that copies rows of one.csv file to five.csv only if there is atleast one of the following('Urology','Urologist','Urologists','MD','D.name') in second column of one.csv file.

for example:
one.csv file looks like this(below).

```<code>date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
12th June   sth             MS          urologist       very good
</code>```

now after running my code I should get five.csv file with following contents(below).

```<code>date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
</code>```

only the row that has at least one of the following ('Urology','Urologist','Urologists', 'MD','Doctor Name') is supposed to be copied to five.csv.

But, I am getting this instead

```<code>12th may    urologist           MS          urologist       very good
12th June   urologist           MS          urologist       very good
</code>```

There is no heading row and the 'speciality' seems to have doubled by replacing D.name column in the new file. I have been trying to fix this since yesterday but no solution at all.

How do I fix this ?

This is my code :

```<code>import csv
input = open('test.csv', 'rb')
output = open('first_test.csv', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    for row[1] in row:
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)
</code>```

答:
Get rid of the inner loop.

```<code>for row[1] in row:
    ...
</code>```

This bit is unnecessary here, you'll end up iterating over each character in row[1] and perform the same operation multiple times.

While refactoring your code, I recommend using the with statement to handle your files:

```<code>with open('test.csv', 'rb') as input, open('first_test.csv', 'wb') as output:
    writer = csv.writer(output)
    for row in csv.reader(input):
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)
</code>```

You don't have to worry about closing your files now.

Body:
I am trying to write a program that copies rows of one.csv file to five.csv only if there is atleast one of the following('Urology','Urologist','Urologists','MD','D.name') in second column of one.csv file.

for example:
one.csv file looks like this(below).

date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good
12th June   sth             MS          urologist       very good

now after running my code I should get five.csv file with following contents(below).

date        D.name      location        speciality      comment
12th may    sth MD          MS          urologist       very good

only the row that has at least one of the following ('Urology','Urologist','Urologists', 'MD','Doctor Name') is supposed to be copied to five.csv.

But, I am getting this instead

12th may    urologist           MS          urologist       very good
12th June   urologist           MS          urologist       very good

There is no heading row and the 'speciality' seems to have doubled by replacing D.name column in the new file. I have been trying to fix this since yesterday but no solution at all.

How do I fix this ?

This is my code :

import csv
input = open('test.csv', 'rb')
output = open('first_test.csv', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    for row[1] in row:
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)

Body:
Get rid of the inner loop.

for row[1] in row:
    ...

This bit is unnecessary here, you'll end up iterating over each character in row[1] and perform the same operation multiple times.

While refactoring your code, I recommend using the with statement to handle your files:

with open('test.csv', 'rb') as input, open('first_test.csv', 'wb') as output:
    writer = csv.writer(output)
    for row in csv.reader(input):
        if (('Urology' in row[1]) or ('Urologist' in row[1]) or ('Urologists' in row[1]) or ('MD' in row[1]) or ('D.name' in row[1])):
            writer.writerow(row)

You don't have to worry about closing your files now.


问:
insert,update in single button clickin winforms
I am not getting, how to do insert and update of the data in C# WinForms on single button click.</p>

```<code>private void save_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";

        cn.Open();

        string gen;
        if (radioButton1.Checked == true)
            gen = "Male";
        else
            gen = "Female";
        string clas = null;
        clas = comboBox1.Text;

        string section = null;
        section = comboBox2.Text;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";

        cmd.Connection = cn;

        int n = cmd.ExecuteNonQuery();
        if (n > 0)
            MessageBox.Show(n + " Row Inserted.");
        else
            MessageBox.Show("Insertion failed.");

        SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;
</code>```

答:
You can add a deletion before the insertion:

```<code>        private void save_Click(object sender, EventArgs e)
        {
            DeletePerson(id); // add this
            SqlConnection cn = new SqlConnection();

            ...
        }

        public void DeletePerson(int id)
        {
            using(SqlConnection connection = new SqlConnection(credentials))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
                cmd.ExecuteNonQuery();
            }
        }
</code>```

Using responsible to dispose the connection.

Consider using Entity Framework or LINQ to SQL.

You are exposed to SQL injection.

Body:
I am not getting, how to do insert and update of the data in C# WinForms on single button click.

private void save_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";

        cn.Open();

        string gen;
        if (radioButton1.Checked == true)
            gen = "Male";
        else
            gen = "Female";
        string clas = null;
        clas = comboBox1.Text;

        string section = null;
        section = comboBox2.Text;
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";

        cmd.Connection = cn;

        int n = cmd.ExecuteNonQuery();
        if (n > 0)
            MessageBox.Show(n + " Row Inserted.");
        else
            MessageBox.Show("Insertion failed.");

        SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView1.DataSource = dt;

Body:
You can add a deletion before the insertion:

        private void save_Click(object sender, EventArgs e)
        {
            DeletePerson(id); // add this
            SqlConnection cn = new SqlConnection();

            ...
        }

        public void DeletePerson(int id)
        {
            using(SqlConnection connection = new SqlConnection(credentials))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
                cmd.ExecuteNonQuery();
            }
        }

Using responsible to dispose the connection.

Consider using Entity Framework or LINQ to SQL.

You are exposed to SQL injection.