问:
Can't run EF migration where DbContext connection string is set at runtime and separate project from application
I have a class library project that has a DbContext class in it that looks like this:

```<code>public DbContext() : base(ContextInitializer.GetConnectionStringName())
    {
</code>```

So that the user (other programmers) can set this on their application startup when they can use my API and entities on whatever database they choose in whatever project and set the connection string then. Now I am trying to generate a migration configuration in my class library. I've tried:

```<code>Enable-Migrations -ProjectName "ClassLibraryProject" -ContextTypeName "MyDbContext" -StartUpProjectName "MyWebApp" -ConnectionString "MyConnectionString" -ConnectionProviderName "System.Data.SqlClient"
</code>```

Based on other answers on here who encounter the same error, and it doesn't help. I still get:

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
  At C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:718 char:5
  +     $domain.SetData('project', $project)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject'
  in assembly  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
  Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not marked as serializable." At
  C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:719
  char:5
  +     $domain.SetData('contextProject', $contextProject)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject'
  in assembly  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
  Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not marked as serializable." At
  C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:720
  char:5
  +     $domain.SetData('startUpProject', $startUpProject)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Other answers I've seen on here say use -StartUpProjectName param, and I did that but still get the error. I thought it was because my projects were in nested folders in the solution I am working in, but supplying the project names as "path/ProjectName" triggered an error that project wasn't found, so that can't be it.

EDIT: I found this: EF 6 with a dnx project, my project is Asp.NET Core class library targeting 461 runtime and being used in Asp.NET Core Web app. So there is no way to run a migration in a class library using EF 6 with ASP.NET Core?

答:
I m Using Visual Studio 2017

where I was able to successfully run a migration,, it does require
Installation of following NuGet Packages in your class library where DbContext located

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Body:
I have a class library project that has a DbContext class in it that looks like this:

public DbContext() : base(ContextInitializer.GetConnectionStringName())
    {

So that the user (other programmers) can set this on their application startup when they can use my API and entities on whatever database they choose in whatever project and set the connection string then. Now I am trying to generate a migration configuration in my class library. I've tried:

Enable-Migrations -ProjectName "ClassLibraryProject" -ContextTypeName "MyDbContext" -StartUpProjectName "MyWebApp" -ConnectionString "MyConnectionString" -ConnectionProviderName "System.Data.SqlClient"

Based on other answers on here who encounter the same error, and it doesn't help. I still get:

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable."
  At C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:718 char:5
  +     $domain.SetData('project', $project)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject'
  in assembly  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
  Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not marked as serializable." At
  C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:719
  char:5
  +     $domain.SetData('contextProject', $contextProject)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type
  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject'
  in assembly  'Microsoft.VisualStudio.ProjectSystem.VS.Implementation,
  Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is
  not marked as serializable." At
  C:\Users\me.nuget\packages\EntityFramework\6.1.3\tools\EntityFramework.psm1:720
  char:5
  +     $domain.SetData('startUpProject', $startUpProject)
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SerializationException

Other answers I've seen on here say use -StartUpProjectName param, and I did that but still get the error. I thought it was because my projects were in nested folders in the solution I am working in, but supplying the project names as "path/ProjectName" triggered an error that project wasn't found, so that can't be it.

EDIT: I found this: EF 6 with a dnx project, my project is Asp.NET Core class library targeting 461 runtime and being used in Asp.NET Core Web app. So there is no way to run a migration in a class library using EF 6 with ASP.NET Core?


来源: stackexchange

问:
How to change link's logo in wordpress?
i wanna change a link in logo header in wordpress, but i don't know how to change that, i've try to change header.php , unfortunately, that's not working

header.php

```<code><?php
<head>
    <meta charset="<?php bloginfo('charset'); ?>" />
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
    <div id="body-content-wrapper">

        <header id="header-main-fixed">

            <div id="header-content-wrapper">

                <div id="header-top">
                    <div id="weglot_here"></div>
                    <? //php fart_display_social_sites(); ?>
                </div>

                    <div class="clear"></div>

                <div id="header-logo">
                    <?php fart_show_website_logo_image_and_title(); ?>
                </div><!-- #header-logo -->

                <nav id="navmain">

                    <?php wp_nav_menu( array( 'theme_location' => 'primary',
                                              'fallback_cb'    => 'wp_page_menu',

                                              ) ); ?>
                </nav><!-- #navmain -->

                <div class="clear">

                </div><!-- .clear -->

            </div><!-- #header-content-wrapper -->

        </header><!-- #header-main-fixed -->

        <div id="header-spacer">

        </div><!-- #header-spacer -->
</code>```

anyone can help me?

答:
Locate the fart_show_website_logo_image_and_title() function inside functions.php and change the href attribute in the line below to the one you want:

```<code>    echo '<a href="' . esc_url( home_url('/') ) . '" title="' . esc_attr( get_bloginfo('name') ) . '">';
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to change link's logo in wordpress?

Body:
i wanna change a link in logo header in wordpress, but i don't know how to change that, i've try to change header.php , unfortunately, that's not working

header.php

<?php

    <meta charset="<?php bloginfo('charset'); ?>" />
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
    <?php wp_head(); ?>

<body <?php body_class(); ?>>

                    <? //php fart_display_social_sites(); ?>

                    <?php fart_show_website_logo_image_and_title(); ?>

                    <?php wp_nav_menu( array( 'theme_location' => 'primary',
                                              'fallback_cb'    => 'wp_page_menu',

                                              ) ); ?>

anyone can help me?

Body:
Locate the fart_show_website_logo_image_and_title() function inside functions.php and change the href attribute in the line below to the one you want:

    echo '<a href="' . esc_url( home_url('/') ) . '" title="' . esc_attr( get_bloginfo('name') ) . '">';


问:
Swift/iOS storing the encryption key best pratice
Does anyone have suggestions/best practice to store the encryption key(s) for iPhone apps?

Also with Firebase remote config feature, has anyone implemented that in their project in order to change the keys if needed/required?!

答:
For storing your key(s) use
keychain.
As the documentation says:

Keychain Services provides secure storage of passwords, keys, certificates, and notes for one or more users.

You can also use a simple Swift wrapper - KeychainAccess


问:
How view error on VPS Debian for odoo module
I'm install odoo 9 on debian, after copy custom module from my VMware and try install module can't install only stay "Cancel install".

How view error, why module can't install. On VMware work fine.

答:
Try find this path  </p>

```<code>/var/log/odoo/odoo-server.log
</code>```

Body:
Try find this path

/var/log/odoo/odoo-server.log


问:
Sorting a vector using array version of quick sort
I'm coding  a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth), so I tried with the following code:

```<code>void ParticleRenderer::sortParticles(Particle **particles, int low, int high)
{
    if (low >= high)
        return;
    Particle *temp = particles[low];
    while (true)
    {
        while (compareParticles(temp, particles[high]) >= 0 && low < high)
            high--;
        if (low == high)
            break;
        else
            particles[low++] = particles[high];
        while (compareParticles(temp, particles[low]) < 0 && low < high)
            low++;
        if (low == high)
            break;
        else
            particles[high--] = particles[low];
    }
    particles[high] = temp;
    int middle = high;
    sortParticles(particles, low, middle - 1);
    sortParticles(particles, middle + 1, high);
}

double ParticleRenderer::compareParticles(Particle *particle1, Particle *particle2)
{
    return  getCameraDistance(particle1) - getCameraDistance(particle2);
}

double ParticleRenderer::getCameraDistance(Particle *particle)
{
    glm::vec3 distance = mCamera.getPosition() - particle->getPosition();
    return glm::length(distance);
}
</code>```

The following code is used to test the sorting:

```<code>sortParticles(&mParticles[0], 0, mParticles.size() - 1);

for (Particle *particle : mParticles)
    std::cout << getCameraDistance(particle) << std::endl;
</code>```

What I get on the console are all unsorted particles. Can someone explain why the sorting doesn't work?

答: Actually my recursive quicksort was wrong. While testing with a vector of ints I used a slightly different version, in wich the partitioning of the array was performed in another function. This version is flawed since I'm passing to the recursive quicksort (divide and conquer I understand..) the same high and low indices that are used in the algorithm...so I'm passing the same index...hence no sorting.</p>

Body:
I'm coding  a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth), so I tried with the following code:

void ParticleRenderer::sortParticles(Particle **particles, int low, int high)
{
    if (low >= high)
        return;
    Particle *temp = particles[low];
    while (true)
    {
        while (compareParticles(temp, particles[high]) >= 0 && low < high)
            high--;
        if (low == high)
            break;
        else
            particles[low++] = particles[high];
        while (compareParticles(temp, particles[low]) < 0 && low < high)
            low++;
        if (low == high)
            break;
        else
            particles[high--] = particles[low];
    }
    particles[high] = temp;
    int middle = high;
    sortParticles(particles, low, middle - 1);
    sortParticles(particles, middle + 1, high);
}

double ParticleRenderer::compareParticles(Particle *particle1, Particle *particle2)
{
    return  getCameraDistance(particle1) - getCameraDistance(particle2);
}

double ParticleRenderer::getCameraDistance(Particle *particle)
{
    glm::vec3 distance = mCamera.getPosition() - particle->getPosition();
    return glm::length(distance);
}

The following code is used to test the sorting:

sortParticles(&mParticles[0], 0, mParticles.size() - 1);

for (Particle *particle : mParticles)
    std::cout << getCameraDistance(particle) << std::endl;

What I get on the console are all unsorted particles. Can someone explain why the sorting doesn't work?


问:
How to add a new vendor
I am new to prestashop and trying to add a 3rd party library in vendor folder which i could use in my custom module. I have added composer.json in my module as well but unable to get the 3rd party library installed in prestashop vendor folder.

Any help/guidance would be much appreciated.

答:
I used the fzaninotto/faker library and I got it working like this :
Composer.json at the root of my module :

```<code>{
    "require": {
        "fzaninotto/faker": "^1.6"
    }
}
</code>```

then run

```<code>composer install
</code>```

Now in order to use this package I created a file called faker.php at the root of my module that starts with including the correct files :

```<code><?php

require('vendor/autoload.php');
require('../../config/config.inc.php');

$faker = Faker\Factory::create('fr_FR');
</code>```

Basicly this is a 3 step process :
 1. Create your composer.json
 2. Run composer install
 3. Include the autoload.php that is in the newly created vendor directory, make sure you use the correct relative path

Title: How to add a new vendor

Body:
I used the fzaninotto/faker library and I got it working like this :
Composer.json at the root of my module :

{
    "require": {
        "fzaninotto/faker": "^1.6"
    }
}

then run

composer install

Now in order to use this package I created a file called faker.php at the root of my module that starts with including the correct files :

<?php

require('vendor/autoload.php');
require('../../config/config.inc.php');

$faker = Faker\Factory::create('fr_FR');

Basicly this is a 3 step process :
 1. Create your composer.json
 2. Run composer install
 3. Include the autoload.php that is in the newly created vendor directory, make sure you use the correct relative path


问:
Btrieve (file) owner problems
I've been tasked with exporting a bunch of tables from a Btrieve (Pervasive) database but one of the tables is putting up a fight. I'm using the Pervasice Control Centre but when I run a SELECT * FROM <troublesome table> I get this error:

```<code>ODBC Error: SQLSTATE = S1000, Native error code = 0
Unable to open table: <troublesome table>.
The owner namme is invalid(Btrieve Error 51)
</code>```

I've Google'd this and found out that there can be an "owner" to a DDF file but, if I understand this correctly, all tables are in that file. But there's just one table causing this error so I have no idea what's going on.

Could someone please offer some assistance.

答:
There can be an owner name on a Btrieve file as well as the DDF.  In this case, it seems that the Btrieve file has an owner name that is required to even read the file (an owner name can allow read only access without the owner name or no access).<br>
Depending on the version of PSQL you are using, you can issue a SET OWNER= command before executing the SELECT statement.  For full documentation on SET OWNER, take a look at http://docs.pervasive.com/products/database/psqlv11/wwhelp/wwhimpl/js/html/wwhelp.htm#href=sqlref/syntaxref.3.76.html.
As far as determining the Owner name, you'll have to ask the developer of the program.  There is no default owner name and not master owner name.  </p>

Title: Btrieve (file) owner problems

Body:
I've been tasked with exporting a bunch of tables from a Btrieve (Pervasive) database but one of the tables is putting up a fight. I'm using the Pervasice Control Centre but when I run a SELECT * FROM <troublesome table> I get this error:

ODBC Error: SQLSTATE = S1000, Native error code = 0
Unable to open table: <troublesome table>.
The owner namme is invalid(Btrieve Error 51)

I've Google'd this and found out that there can be an "owner" to a DDF file but, if I understand this correctly, all tables are in that file. But there's just one table causing this error so I have no idea what's going on.

Could someone please offer some assistance.

Body:
There can be an owner name on a Btrieve file as well as the DDF.  In this case, it seems that the Btrieve file has an owner name that is required to even read the file (an owner name can allow read only access without the owner name or no access).

Depending on the version of PSQL you are using, you can issue a SET OWNER= command before executing the SELECT statement.  For full documentation on SET OWNER, take a look at http://docs.pervasive.com/products/database/psqlv11/wwhelp/wwhimpl/js/html/wwhelp.htm#href=sqlref/syntaxref.3.76.html.
As far as determining the Owner name, you'll have to ask the developer of the program.  There is no default owner name and not master owner name.

ContentLicense: CC BY-SA 2.5


问:
Enterprise Architect: Hide only "top" labels of connectors programmatically
I want to hide the "top" part of all connector labels of a diagram. For this, I tried to set up a script, but it currently hides ALL labels (also the "bottom" labels which I want to preserve):

```<code>// Get a reference to the current diagram
var currentDiagram as EA.Diagram;
currentDiagram = Repository.GetCurrentDiagram();

if (currentDiagram != null)
{
    for (var i = 0; i < currentDiagram.DiagramLinks.Count; i++)
    {
        var currentDiagramLink as EA.DiagramLink;
        currentDiagramLink = currentDiagram.DiagramLinks.GetAt(i);

        currentDiagramLink.Geometry = currentDiagramLink.Geometry
            .replace(/HDN=0/g, "HDN=1")
            .replace(/LLT=;/, "LLT=HDN=1;")
            .replace(/LRT=;/, "LRT=HDN=1;");
        if (!currentDiagramLink.Update())
        {
            Session.Output(currentDiagramLink.GetLastError());
        }
    }
}
</code>```

When I hide only the top labels manually (context menu of a connector/Visibility/Set Label Visibility), the Geometry property of the DiagramLinks remains unchanged, so I guess the detailed label visibility information must be contained somewhere else in the model.

Does anyone know how to change my script?

Thanks in advance!

EDIT:
The dialog for editing the detailed label visibility looks as follows:

My goal is unchecking the "top label" checkboxes programmatically.

答:
In the Geometry attribute you will find a partial string like

```<code>LLT=CX=36:CY=13:OX=0:OY=0:HDN=0:BLD=0:ITA=0:UND=0:CLR=-1:ALN=1:DIR=0:ROT=0;
</code>```

So in between LLT and the next semi-colon you need to locate the HDN=0 and replace that with HDN=1. A simple global change like above wont work. You need a wild card like in the regex LLT=([^;]+); to work correctly.

Body:
I want to hide the "top" part of all connector labels of a diagram. For this, I tried to set up a script, but it currently hides ALL labels (also the "bottom" labels which I want to preserve):

// Get a reference to the current diagram
var currentDiagram as EA.Diagram;
currentDiagram = Repository.GetCurrentDiagram();

if (currentDiagram != null)
{
    for (var i = 0; i < currentDiagram.DiagramLinks.Count; i++)
    {
        var currentDiagramLink as EA.DiagramLink;
        currentDiagramLink = currentDiagram.DiagramLinks.GetAt(i);

        currentDiagramLink.Geometry = currentDiagramLink.Geometry
            .replace(/HDN=0/g, "HDN=1")
            .replace(/LLT=;/, "LLT=HDN=1;")
            .replace(/LRT=;/, "LRT=HDN=1;");
        if (!currentDiagramLink.Update())
        {
            Session.Output(currentDiagramLink.GetLastError());
        }
    }
}

When I hide only the top labels manually (context menu of a connector/Visibility/Set Label Visibility), the Geometry property of the DiagramLinks remains unchanged, so I guess the detailed label visibility information must be contained somewhere else in the model.

Does anyone know how to change my script?

Thanks in advance!

EDIT:
The dialog for editing the detailed label visibility looks as follows:

My goal is unchecking the "top label" checkboxes programmatically.

Body:
In the Geometry attribute you will find a partial string like

LLT=CX=36:CY=13:OX=0:OY=0:HDN=0:BLD=0:ITA=0:UND=0:CLR=-1:ALN=1:DIR=0:ROT=0;

So in between LLT and the next semi-colon you need to locate the HDN=0 and replace that with HDN=1. A simple global change like above wont work. You need a wild card like in the regex LLT=([^;]+); to work correctly.


问:
How to insert value into foreign key in SQL server? (Avoid the duplicate key.)
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

```<code>create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
</code>```

Here are my insert statements

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
</code>```

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

答:
You have not set sinNum as identity. Make it auto incremented and then change your insert query as below.

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values ((SELECT ISNULL(MAX(sinNum)+1,0) FROM person WITH(SERIALIZABLE, UPDLOCK)),
'female', 24, 'dds', 2121)
</code>```

You can use simpler version also, but it doesn't guarantee concurrency:

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values (NULL,
'female', 24, 'dds', 2121)
</code>```

Body:
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)

Here are my insert statements

insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

Body:
You have not set sinNum as identity. Make it auto incremented and then change your insert query as below.

insert into person (sinNum,gender,age,emailAddr, phoneNum) values ((SELECT ISNULL(MAX(sinNum)+1,0) FROM person WITH(SERIALIZABLE, UPDLOCK)),
'female', 24, 'dds', 2121)

You can use simpler version also, but it doesn't guarantee concurrency:

insert into person (sinNum,gender,age,emailAddr, phoneNum) values (NULL,
'female', 24, 'dds', 2121)


问:
No automatic update of my launcher app
I make an Android launcher app and I published this app in the store.
The problem is it seem the people don't receive the update of the app automatically...
They have to go to the store and click to the update button.

It's the same when Sync is enabled in settings & background Data is not restricted.

Maybe because it's a launcher and the Google Play Store doesn't update the app who are being used (to not reload it) ?

答:
Google Play can take upto 24 hours to push application updates across all its servers.

Just wait for a while, and all your eligible users should receive the update. However, if your update adds feature requests that some devices don't support, they will not get the update. And one more thing you must make sure that the app u have installed in ur mobile is not apk built with debug keystore.. the play store will show always as "Open" button instead of "Update" if the play store app certificate doesn't match with installed app certificate. I realized this when i did trial and error with debug and signed apk's. Only signed apk worked. And use versionCode for comparing versions instead of version Name.

Title: No automatic update of my launcher app


问:
jquery not working while submitting a form
```<code>$(document).ready(function(){
  $("#name").blur(function(){
    var name = $("#name").val();
      if ( $(this).val().match('^[a-zA-Z]{3,16}$') )
    {
    $("#check_name").html("Good Name").hide();
    }
else {
  $("#check_name").html("That's not a name.");
    }
</code>```

It is inserting the values if it is wrong.It is not validating data when we submit a form.need help soon.

答:
This will work:

```<code>$(function(){
  $("#name").blur(function(e){
    var name = $(e.target).val();
    if ( name.match('^[a-zA-Z]{3,16}$') )  {
        $("#check_name").html("Good Name").hide();
    }else {
        $("#check_name").html("That's not a name.").show();
    }
    })
});
</code>```

If you also want to see "Good Name", remove the .hide() ;)

Body:
$(document).ready(function(){
  $("#name").blur(function(){
    var name = $("#name").val();
      if ( $(this).val().match('^[a-zA-Z]{3,16}$') )
    {
    $("#check_name").html("Good Name").hide();
    }
else {
  $("#check_name").html("That's not a name.");
    }

It is inserting the values if it is wrong.It is not validating data when we submit a form.need help soon.

Body:
This will work:

$(function(){
  $("#name").blur(function(e){
    var name = $(e.target).val();
    if ( name.match('^[a-zA-Z]{3,16}$') )  {
        $("#check_name").html("Good Name").hide();
    }else {
        $("#check_name").html("That's not a name.").show();
    }
    })
});

If you also want to see "Good Name", remove the .hide() ;)


问:
Python - How to pass a directory as MapReduce input
I've written a simple MapReduce example in Python. If the input was a file, for example text file, for running the code we simply use the following pattern: cat <data> | map | sort | reduce, for example in my case it is: cat data | ./mapper.py | sort | ./reducer.py and all things work right.

But I changed my mapper and reducer to read data from a directory that contains .gz files. So I should pass the path of the directory as input. I test the following terminal command cat dat/ | ./mapper.py | sort | ./reducer.py while the directory containing data is dat/, but I faced error:

```<code>cat: dat/: Is a directory
Traceback (most recent call last):
  File "./mapper.py", line 9, in <module>
    for filename in glob.glob(sys.stdin + '*.gz'):
TypeError: unsupported operand type(s) for +: 'file' and 'str'
</code>```

How can I pass a directory as input to Mapreduce in Python?

The following is my code:

mapper.py

```<code>#!/usr/bin/env python
import sys
#import timeit
import glob
import gzip

QUALITY = '01459'
MISSING = '+9999'
for filename in glob.glob(sys.stdin + '*.gz'):
    f = gzip.open(filename, 'r')
    for line in f:
        val = line.strip()
        (year, temp, q) = (val[15:19], val[87:92], val[92:93])
        if temp != MISSING and q in QUALITY:
            print " %s\t%s" % (year, temp)
</code>```

reducer.py

```<code>#!/usr/bin/env python
import sys

max_val = -sys.maxint
key = ''
for line in sys.stdin:
    (key, val) = line.strip().split('\t')
    max_val = max(max_val, int(val))
print "The last IF %s\t%s" % (key, max_val)
</code>```

答:
The line for filename in glob.glob(sys.stdin + '*.gz'): expects a string from the stdin. Hence, simply pass a string (echo) instead of file contents (cat):

```<code>$ echo dat/ | ./mapper.py | sort | ./reducer.py
</code>```

However, why do you pass arguments via pipes? Usually arguments are directly passed and read by python via sys.argv (or even better via an interpreter such as "argparse").

Body:
I've written a simple MapReduce example in Python. If the input was a file, for example text file, for running the code we simply use the following pattern: cat <data> | map | sort | reduce, for example in my case it is: cat data | ./mapper.py | sort | ./reducer.py and all things work right.

But I changed my mapper and reducer to read data from a directory that contains .gz files. So I should pass the path of the directory as input. I test the following terminal command cat dat/ | ./mapper.py | sort | ./reducer.py while the directory containing data is dat/, but I faced error:

cat: dat/: Is a directory
Traceback (most recent call last):
  File "./mapper.py", line 9, in <module>
    for filename in glob.glob(sys.stdin + '*.gz'):
TypeError: unsupported operand type(s) for +: 'file' and 'str'

How can I pass a directory as input to Mapreduce in Python?

The following is my code:

mapper.py

#!/usr/bin/env python
import sys
#import timeit
import glob
import gzip

QUALITY = '01459'
MISSING = '+9999'
for filename in glob.glob(sys.stdin + '*.gz'):
    f = gzip.open(filename, 'r')
    for line in f:
        val = line.strip()
        (year, temp, q) = (val[15:19], val[87:92], val[92:93])
        if temp != MISSING and q in QUALITY:
            print " %s\t%s" % (year, temp)

reducer.py

#!/usr/bin/env python
import sys

max_val = -sys.maxint
key = ''
for line in sys.stdin:
    (key, val) = line.strip().split('\t')
    max_val = max(max_val, int(val))
print "The last IF %s\t%s" % (key, max_val)

Body:
The line for filename in glob.glob(sys.stdin + '*.gz'): expects a string from the stdin. Hence, simply pass a string (echo) instead of file contents (cat):

$ echo dat/ | ./mapper.py | sort | ./reducer.py

However, why do you pass arguments via pipes? Usually arguments are directly passed and read by python via sys.argv (or even better via an interpreter such as "argparse").


问:
Django with PyPy
Are there some reasons of using Django with PyPy?
I read PyPy increases perfomance.</p>

答: Unlikely. A Django application is almost always I/O-bound, usually because of the database connection. PyPy wouldn't help with that at all, even if it was purely compatible (which I'm not sure it is).</p>

Title: Django with PyPy


问:
Treat Userform as a Function
I have created a VBA UserForm which is essentially a glorified input box

Just like an input box can be employed like this

```<code>Dim returnVal As String
returnVal = InputBox("Write some string")
</code>```

I would like my userform to run like this

```<code>Dim returnVal As customClass
Set returnVal = MyUserForm([some arguments])
</code>```

ie. the MyUserForm() code passes some arguments to the userform, and when the userform is closed, it gets some arguments back (in the form of a custom class rather than a plain string)

What's the best way of structuring my userform to allow this functionality?

Currently, I'm just declaring some variables and the custom class publicly. I'm catching command button clicks and Query_close() events to hide the form, then I read the outputVal and close the form completely. I don't like this because I'd like my form to be totally self contained, and I think the capturing of events is messy.

In simplified code (read/return a string):

```<code>Function myUf(inVal As String) As String
Dim frm As New frmTest
frm.inputval = inVal
frm.Init 'sets caption. We cannot rely on userform initialize as this runs before inputval is set
         'We could pass a variable here to save writing to the public variable
frm.Show
myUf = frm.outputVal
Set frm = Nothing
End Function
</code>```

And in my Userform called frmTest with a textbox called tb1

```<code>Public inputval As String
Public outputVal As String

Public Sub Init()
Me.Caption = inputval 'setting caption, but could pass this anywhere
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
outputVal = tb1 'reading value from textbox, but could return anything here
Me.Hide
End Sub
</code>```

答: There's no way to one-liner the code like you want to, unfortunately. If all your userform code is self-contained then the only way for it to pass values out is to change the values of public variables. Mat's Mug's answer here is the layout I usually use when trying to simulate functions like 'InputBox' but you still can't get it in one line without writing a separate function. Using userform properties allows you to contain more of your code within the form itself.</p>

Title: Treat Userform as a Function

Body:
I have created a VBA UserForm which is essentially a glorified input box

Just like an input box can be employed like this

Dim returnVal As String
returnVal = InputBox("Write some string")

I would like my userform to run like this

Dim returnVal As customClass
Set returnVal = MyUserForm([some arguments])

ie. the MyUserForm() code passes some arguments to the userform, and when the userform is closed, it gets some arguments back (in the form of a custom class rather than a plain string)

What's the best way of structuring my userform to allow this functionality?

Currently, I'm just declaring some variables and the custom class publicly. I'm catching command button clicks and Query_close() events to hide the form, then I read the outputVal and close the form completely. I don't like this because I'd like my form to be totally self contained, and I think the capturing of events is messy.

In simplified code (read/return a string):

Function myUf(inVal As String) As String
Dim frm As New frmTest
frm.inputval = inVal
frm.Init 'sets caption. We cannot rely on userform initialize as this runs before inputval is set
         'We could pass a variable here to save writing to the public variable
frm.Show
myUf = frm.outputVal
Set frm = Nothing
End Function

And in my Userform called frmTest with a textbox called tb1

Public inputval As String
Public outputVal As String

Public Sub Init()
Me.Caption = inputval 'setting caption, but could pass this anywhere
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode <> 1 Then Cancel = 1
outputVal = tb1 'reading value from textbox, but could return anything here
Me.Hide
End Sub


问:
Call a function once page load after button click
There is a scenario where I need a function like xyz() to be called once a button on page is clicked and page is loaded using javascript/jquery.
I can't call xyz() directly on  or inside document.ready() or  $(window).on('load', function ()).
I need the function to be called once a button is clicked and page has loaded completely.
Below is working code on page load but not my requirement

```<code><body onload="xyz();">
    <form id="form1" runat="server">
        <div id="vizContainer" style="width: 800px; height: 700px;">
        </div>
    </form>
</body>
</code>```

Now below is my required code on button click and it is not working

```<code><body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="functiongetdata()" />
            <div id="vizContainer" style="width: 800px; height: 700px;">
            </div>
        </form>
    </body>
 <script type="text/javascript">
        function functiongetdata() {
            xyz();
        }
    </script>
</code>```

答:
you can use something like this

```<code>$(function() {
        $('button.start').click(function() {
            $('img.lazy').lazy({
                bind: "event"
            });
        });

        $('button.loadAll').click(function() {
            $('.lazy').lazy({
                bind: "event",
                delay: 0
            });
        });
    });
</code>```

Refer this link for clear example
http://jquery.eisbehr.de/lazy/example_load-elements-by-events

Body:
There is a scenario where I need a function like xyz() to be called once a button on page is clicked and page is loaded using javascript/jquery.
I can't call xyz() directly on  or inside document.ready() or  $(window).on('load', function ()).
I need the function to be called once a button is clicked and page has loaded completely.
Below is working code on page load but not my requirement

    <form id="form1" runat="server">

    </form>

Now below is my required code on button click and it is not working

        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="functiongetdata()" />

        </form>

Body:
you can use something like this

$(function() {
        $('button.start').click(function() {
            $('img.lazy').lazy({
                bind: "event"
            });
        });

        $('button.loadAll').click(function() {
            $('.lazy').lazy({
                bind: "event",
                delay: 0
            });
        });
    });

Refer this link for clear example
http://jquery.eisbehr.de/lazy/example_load-elements-by-events


问:
How to put all mp3 files from raw folder into a list by name and other metadata?
I'm developing an app that can play MP3 files. I want to convert mp3 files inside the raw folder into an ArrayList of song objects, using the mp3 file's name as its title. Here's my code. I've taken it from this question's answer but it doesn't seem to work for me.

```<code>public void getSongList() {
    try {
        Log.d("Test", "reached");
        Field[] fields = R.raw.class.getDeclaredFields();

        Log.d("Test", "reached2");
        for (Field f : fields) {
            allSongs.addSong(new Song(0, f.getName(), ""));
        }
        Log.d("Test", "reached3");
    } catch (Exception e) {
        Log.d("Test", "reached4");
        Log.d("Test", allSongs.getSongs().size() + "");
        Log.d("Test", e.toString());
        return;
    }
}
</code>```

Here are the logs:

```<code>07-03 15:50:52.497 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached
07-03 15:50:52.497 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached2
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached4
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: 0
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: java.lang.NullPointerException: Attempt to invoke virtual method 'void poc.cevt.hmi.com.musicplayerapp.AllSongs.addSong(poc.cevt.hmi.com.musicplayerapp.Song)' on a null object reference
</code>```

I have one mp3 file inside my raw folder. The Song's first and third parameters are ID and artist respectively, I'm just trying to get the title to work for now. Any alternative/better solutions to what I have are also welcome.

答: allSongs is null, and so you are getting a NullPointerException on your call to addSong().

Body:
I'm developing an app that can play MP3 files. I want to convert mp3 files inside the raw folder into an ArrayList of song objects, using the mp3 file's name as its title. Here's my code. I've taken it from this question's answer but it doesn't seem to work for me.

public void getSongList() {
    try {
        Log.d("Test", "reached");
        Field[] fields = R.raw.class.getDeclaredFields();

        Log.d("Test", "reached2");
        for (Field f : fields) {
            allSongs.addSong(new Song(0, f.getName(), ""));
        }
        Log.d("Test", "reached3");
    } catch (Exception e) {
        Log.d("Test", "reached4");
        Log.d("Test", allSongs.getSongs().size() + "");
        Log.d("Test", e.toString());
        return;
    }
}

Here are the logs:

07-03 15:50:52.497 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached
07-03 15:50:52.497 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached2
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: reached4
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: 0
07-03 15:50:52.498 17106-17106/poc.cevt.hmi.com.musicplayerapp D/Test: java.lang.NullPointerException: Attempt to invoke virtual method 'void poc.cevt.hmi.com.musicplayerapp.AllSongs.addSong(poc.cevt.hmi.com.musicplayerapp.Song)' on a null object reference

I have one mp3 file inside my raw folder. The Song's first and third parameters are ID and artist respectively, I'm just trying to get the title to work for now. Any alternative/better solutions to what I have are also welcome.


问:
Define a priority for termination of K8s pods
I have a bunch of pods running in the same cluster. Sometimes there are not enough resources and some pods need to terminate.

That's OK, but how do I set the priority of which pods are killed first?

It usually kills my most important service first :\

Thanks!

答:
I suggest you take a look at resource QoS.

Have you important stuff (including monitoring) specify limit=request which in turn will land them in the guaranteed QoS class.

Specifically,

The system computes pod level requests and limits by summing up per-resource requests and limits across all containers. When request == limit, the resources are guaranteed (...)

Also, overstepping CPU limits only results in throttling, so it's more important to get memory limits (per container) right.


问:
SQLConnection code
When trying to establish a connection I get the exception below:

```<code>System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Login failed for user ''.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>
</code>```

I keep getting the above error, here is my code:

```<code>SqlConnection conn =
  new SqlConnection(@"Data Source = Computer-DELL\SQLEXPRESS;Initial Catalog = Drivers");

conn.open();
</code>```

答:
Assuming they have permission, local user:</p>

```<code>SqlConnection conn = new SqlConnection(@"Data Source = Computer-DELL\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;")
conn.open();
</code>```

Title: SQLConnection code

Body:
When trying to establish a connection I get the exception below:

System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Login failed for user ''.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>

I keep getting the above error, here is my code:

SqlConnection conn =
  new SqlConnection(@"Data Source = Computer-DELL\SQLEXPRESS;Initial Catalog = Drivers");

conn.open();

Body:
Assuming they have permission, local user:

SqlConnection conn = new SqlConnection(@"Data Source = Computer-DELL\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;")
conn.open();


答:
Use .test instead of .match to check for occurence. Also, is your regex correct, will it handle every name? Validate the regex somewhere on regex tester as well.

Https://stackoverflow.com/questions/8606117/javascript-regexp-using-val-match-method

Title: jquery not working while submitting a form


问:
Oracle 9i: Supposedly missing right parenthesis
I have a simple function written in Oracle 9i (version 9.2.0.4.0) to simulate an in-line IF. For those interested, here's the code:

```<code>create or replace
FUNCTION IIF
   (testExpression NUMBER,
    trueResult NUMBER,
    falseResult NUMBER)
RETURN NUMBER
AS
BEGIN
   /*
      A simple in-line IF function for use with SQL queries. If the test
      expression evaluates to any non-zero value, it is considered to be
      true, and the trueResult is returned. Otherwise, falseResult is
      returned.
   */
   IF (testExpression is null) or (testExpression = 0) THEN
      return falseResult;
   ELSE
      return trueResult;
   END IF;
END IIF;
</code>```

This isn't rocket science. Now, here's the big mystery: if I execute the following SQL statements, everything is just fine, and works exactly as I expect:

```<code>SELECT IIF(1, 'true', 'false') FROM DUAL;
SELECT IIF(0, 'false', 'true') FROM DUAL;
</code>```

However, the following generates a really bizarre error from Oracle:

```<code>SELECT IIF((0 = 1), 'false', 'true') FROM DUAL;
</code>```

That error is as follows:

```<code>ORA-00907: missing right parenthesis.
</code>```

Clearly, that isn't the case. Would anyone happen to have an explanation for this little bit of bizarreness?

It's taking a whole lot of self-control at the moment to restrain myself from hurling the Oracle server out the window. Oracle seems rife with these kinds of inanities.

EDIT: Is there some kind of magic syntax I have to use to use an equality operator in a select statement?

答:
There is no BOOLEAN type in the Oracle database, so you can't use an expression like "(1=0)".

Even if there were a BOOLEAN type, you have declared the first argument to be of type NUMBER. You have to pass it a number, or something that can be implicitly converted to one.

Finally, I don't understand how any of your examples actually produced anything besides "invalid number", since your second and third arguments can't be converted to numbers, either.

OwnerDisplayName: Mike Hofer

Body:
I have a simple function written in Oracle 9i (version 9.2.0.4.0) to simulate an in-line IF. For those interested, here's the code:

create or replace
FUNCTION IIF
   (testExpression NUMBER,
    trueResult NUMBER,
    falseResult NUMBER)
RETURN NUMBER
AS
BEGIN
   /*
      A simple in-line IF function for use with SQL queries. If the test
      expression evaluates to any non-zero value, it is considered to be
      true, and the trueResult is returned. Otherwise, falseResult is
      returned.
   */
   IF (testExpression is null) or (testExpression = 0) THEN
      return falseResult;
   ELSE
      return trueResult;
   END IF;
END IIF;

This isn't rocket science. Now, here's the big mystery: if I execute the following SQL statements, everything is just fine, and works exactly as I expect:

SELECT IIF(1, 'true', 'false') FROM DUAL;
SELECT IIF(0, 'false', 'true') FROM DUAL;

However, the following generates a really bizarre error from Oracle:

SELECT IIF((0 = 1), 'false', 'true') FROM DUAL;

That error is as follows:

ORA-00907: missing right parenthesis.

Clearly, that isn't the case. Would anyone happen to have an explanation for this little bit of bizarreness?

It's taking a whole lot of self-control at the moment to restrain myself from hurling the Oracle server out the window. Oracle seems rife with these kinds of inanities.

EDIT: Is there some kind of magic syntax I have to use to use an equality operator in a select statement?

OwnerDisplayName: DCookie

LastEditorDisplayName: DCookie


问:
Why does spread syntax convert my string into an array?
Why does spread syntax convert my string into an array?

```<code>var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]
</code>```

Why is w not a string?

答:
There are two things going on here.

First, you're using array destructuring. This allows you to take an iterable and assign values from it to individual variables.

Second, you're using a rest parameter. This converts any remaining output of the iterable into an array.

So your string 'hello' is iterated into its individual characters, the first one is ignored (because you omitted the destination), then the remaining characters are turned into an array and assigned to w.

Body:
Why does spread syntax convert my string into an array?

var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]

Why is w not a string?


问:
Is there any way to move horizontal scroll bar the sheet one column to the left using POI?
I have written a program that reads Excel template sheet. In which the first column was hidden. Now, I have a code that un-hide the excel column programmatically (so Column start from A1).

I'm using Apache POI 3.16 version.

When I open a file, it should show me a column from A1 instead it shows me from B1 column.
When I write below code for XLS, It working properly but didn't work for an XLSX format.

```<code>sheet.showInPane(0, 0);
</code>```

I need to manually move the horizontal scroll bar to view my first column. How should I achieve this programmatically to auto-scroll to the first column for XLSX format?

Here is my full code.

```<code>public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
        Workbook workBook =null;
        Sheet sheet = null;
        if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
             // Get the workbook instance for XLS file
            workBook = new HSSFWorkbook(new FileInputStream(inputFile));
        }else{
            // Get the workbook instance for XLSX file
            workBook = new XSSFWorkbook(new FileInputStream(inputFile));
        }
        sheet = workBook.getSheetAt(0);
        Row row = null;
        if(sheet.isColumnHidden(0)){
            sheet.setColumnHidden(0, false);
            sheet.setActiveCell(new CellAddress("A1"));
            sheet.showInPane(0, 0);
            sheet.createFreezePane(0, 1);

             Iterator<Row> rowIterator = sheet.iterator();
                int rowIndex = 1;
                while (rowIterator.hasNext()) {
                    row = rowIterator.next();
                    if(rowIndex == 1){
                        rowIndex++;
                        continue;
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue("error message");
                    rowIndex++;
                }
        }
        return workBook;
    }
</code>```

答:
Here is the answer to my question. Please refer this  Source</p>

```<code>public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
        Workbook workBook =null;
        Sheet sheet = null;
        if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
             // Get the workbook instance for XLS file
            workBook = new HSSFWorkbook(new FileInputStream(inputFile));
        }else{
            // Get the workbook instance for XLSX file
            workBook = new XSSFWorkbook(new FileInputStream(inputFile));
        }
        sheet = workBook.getSheetAt(0);
        Row row = null;
        if(sheet.isColumnHidden(0)){
            sheet.setColumnHidden(0, false);

            if(sheet instanceof XSSFSheet){
                CTWorksheet ctWorksheet = null;
                CTSheetViews ctSheetViews = null;
                CTSheetView ctSheetView = null;
                XSSFSheet tempSheet = (XSSFSheet) sheet;
                 // First step is to get at the CTWorksheet bean underlying the worksheet.
                ctWorksheet = tempSheet.getCTWorksheet();
                // From the CTWorksheet, get at the sheet views.
                ctSheetViews = ctWorksheet.getSheetViews();
                // Grab a single sheet view from that array
                ctSheetView = ctSheetViews.getSheetViewArray(ctSheetViews.sizeOfSheetViewArray() - 1);
                // Se the address of the top left hand cell.
                ctSheetView.setTopLeftCell("A1");
            }else{
                 sheet.setActiveCell(new CellAddress("A1"));
                 sheet.showInPane(0, 0);
            }

             Iterator<Row> rowIterator = sheet.iterator();
                int rowIndex = 1;
                while (rowIterator.hasNext()) {
                    row = rowIterator.next();
                    if(rowIndex == 1){
                        rowIndex++;
                        continue;
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue("error message");
                    rowIndex++;
                }
        }
        return workBook;
    }
</code>```

Body:
I have written a program that reads Excel template sheet. In which the first column was hidden. Now, I have a code that un-hide the excel column programmatically (so Column start from A1).

I'm using Apache POI 3.16 version.

When I open a file, it should show me a column from A1 instead it shows me from B1 column.
When I write below code for XLS, It working properly but didn't work for an XLSX format.

sheet.showInPane(0, 0);

I need to manually move the horizontal scroll bar to view my first column. How should I achieve this programmatically to auto-scroll to the first column for XLSX format?

Here is my full code.

public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
        Workbook workBook =null;
        Sheet sheet = null;
        if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
             // Get the workbook instance for XLS file
            workBook = new HSSFWorkbook(new FileInputStream(inputFile));
        }else{
            // Get the workbook instance for XLSX file
            workBook = new XSSFWorkbook(new FileInputStream(inputFile));
        }
        sheet = workBook.getSheetAt(0);
        Row row = null;
        if(sheet.isColumnHidden(0)){
            sheet.setColumnHidden(0, false);
            sheet.setActiveCell(new CellAddress("A1"));
            sheet.showInPane(0, 0);
            sheet.createFreezePane(0, 1);

             Iterator<Row> rowIterator = sheet.iterator();
                int rowIndex = 1;
                while (rowIterator.hasNext()) {
                    row = rowIterator.next();
                    if(rowIndex == 1){
                        rowIndex++;
                        continue;
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue("error message");
                    rowIndex++;
                }
        }
        return workBook;
    }

Body:
Here is the answer to my question. Please refer this  Source

public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
        Workbook workBook =null;
        Sheet sheet = null;
        if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
             // Get the workbook instance for XLS file
            workBook = new HSSFWorkbook(new FileInputStream(inputFile));
        }else{
            // Get the workbook instance for XLSX file
            workBook = new XSSFWorkbook(new FileInputStream(inputFile));
        }
        sheet = workBook.getSheetAt(0);
        Row row = null;
        if(sheet.isColumnHidden(0)){
            sheet.setColumnHidden(0, false);

            if(sheet instanceof XSSFSheet){
                CTWorksheet ctWorksheet = null;
                CTSheetViews ctSheetViews = null;
                CTSheetView ctSheetView = null;
                XSSFSheet tempSheet = (XSSFSheet) sheet;
                 // First step is to get at the CTWorksheet bean underlying the worksheet.
                ctWorksheet = tempSheet.getCTWorksheet();
                // From the CTWorksheet, get at the sheet views.
                ctSheetViews = ctWorksheet.getSheetViews();
                // Grab a single sheet view from that array
                ctSheetView = ctSheetViews.getSheetViewArray(ctSheetViews.sizeOfSheetViewArray() - 1);
                // Se the address of the top left hand cell.
                ctSheetView.setTopLeftCell("A1");
            }else{
                 sheet.setActiveCell(new CellAddress("A1"));
                 sheet.showInPane(0, 0);
            }

             Iterator<Row> rowIterator = sheet.iterator();
                int rowIndex = 1;
                while (rowIterator.hasNext()) {
                    row = rowIterator.next();
                    if(rowIndex == 1){
                        rowIndex++;
                        continue;
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue("error message");
                    rowIndex++;
                }
        }
        return workBook;
    }


问:
How can i configure this milestone in HighStock
How can i configure points that i showed on below:

答:
The highlighted part is a Navigator. Navigator series could be adjusted in navigator.series.

Simple demo from API reference: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/navigator/series/


问:
Re Duplicates in Oracle query
I have a requirement to include Student details along with Postcode and Borough in my query.

Query gives correct results when I include the Postcode.

```<code>SELECT DISTINCT
 t1.StuID,
 t1.Forename,
 t1.Surname,
 t1.dob,
 t2.a_reference "Postcode",
  FROM
student t1, address t2
WHERE t1.s_address = t2.a_id

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU
</code>```

However, When I add the Borough field I see duplicates as below

```<code>    SELECT DISTINCT
     t1.StuID,
     t1.Forename,
     t1.Surname,
     t1.dob,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID, t1.Forename, t1.Surname,
     t1.dob, t2.a_reference, t3.el_name

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Barnsbury
AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Islington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Tollington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Islington
</code>```

Any idea where am I going wrong?

Thanks
Ar

答:
should remove the   t3.el_name from group by

```<code>   SELECT
     t1.StuID,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID,
     t2.a_reference
</code>```

Title: Re Duplicates in Oracle query

Body:
I have a requirement to include Student details along with Postcode and Borough in my query.

Query gives correct results when I include the Postcode.

SELECT DISTINCT
 t1.StuID,
 t1.Forename,
 t1.Surname,
 t1.dob,
 t2.a_reference "Postcode",
  FROM
student t1, address t2
WHERE t1.s_address = t2.a_id

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU

However, When I add the Borough field I see duplicates as below

    SELECT DISTINCT
     t1.StuID,
     t1.Forename,
     t1.Surname,
     t1.dob,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID, t1.Forename, t1.Surname,
     t1.dob, t2.a_reference, t3.el_name

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Barnsbury
AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Islington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Tollington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Islington

Any idea where am I going wrong?

Thanks
Ar

Body:
should remove the   t3.el_name from group by

   SELECT
     t1.StuID,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID,
     t2.a_reference


问:
Java fibonacci stack overflow error
```<code>public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}
</code>```

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

```<code>public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}
</code>```

I wont get error, even I just enter 1, could I ask why?

答:
In the for-Statement you start with 0. This is the first Input to fibonacci-Funktion. Try:</p>

```<code>public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
 int i = sc.nextInt();

 for (int j=1; j<i; j++) {
     System.out.println(fibonacci(j));
 }
</code>```

Title: Java fibonacci stack overflow error

Body:
public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}

I wont get error, even I just enter 1, could I ask why?

Body:
In the for-Statement you start with 0. This is the first Input to fibonacci-Funktion. Try:

public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
 int i = sc.nextInt();

 for (int j=1; j<i; j++) {
     System.out.println(fibonacci(j));
 }


问:
Toast not working in Service
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

```<code><service android:name=".MyService"></service>
</code>```

ClientActivity

```<code>package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}
</code>```

MyService

```<code>package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
</code>```

答:
```<code>Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {

    @Override
    public void run() {
         Toast.makeText(getApplicationContext(),
                       "helllo",
                       Toast.LENGTH_SHORT).show();
    }
});
</code>```

Title: Toast not working in Service

Body:
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

<service android:name=".MyService"></service>

ClientActivity

package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}

MyService

package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}


问:
I am unable to change the directory in cmd
cmd is not able to change the directory using the command

```<code>C:\Windows\system32>CD I:
</code>```

It is going back to same C: directory

The screenshot

答: Just type "I:" and press Enter, then use "CD foldername" to dive into your folders.</p>

Body:
cmd is not able to change the directory using the command

C:\Windows\system32>CD I:

It is going back to same C: directory

The screenshot


问:
Displaying Date and Time separately from a String in localized format in Android
I know there are a lot of similar questions, and so far some of the solutions that I tried, but did not fully answer my question are: this, this, this, this, this, this, this, this, this, this, and a lot more.

I am making an app where I get user's post from server and sort it by date, and also displaying date and time it was created in the post. Right now I have a working solution, and I am doing it by converting string from a server in this format yyyy-MM-dd HH:mm:ss to my custom date and time format.

The problem is: I do not want to hard code a format, but instead I want to display it in the format that user phone has, and do it separately for both date and time. By the local format of the phone I mean - am-pm/24 hour format, and same for the date format - dd-MM-YY, or MM-dd-YYYY, or dd-MM, etc.

So far I have looked through a lot of solutions, most of which have that hardcoded format. I try to avoid, but I think that additional problem is that I want to separate date and time from datetime string. The other problem is that the transformation is not separate for date and time.

In short I want to format 2017-07-04 12:00:00 to 04 Jul 2017 and 12:00 PM, or 07/04/17 and 12:00. ie. Separating date and time into two strings, and displaying them in localized phone format.

My Adapter:

```<code> public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

     private List<UserPosts> postItems;
     private Context context;
     private static final String TAG = UserPosts.class.getSimpleName();

     class PostsViewHolder extends RecyclerView.ViewHolder {
    TextView userPostsTitle, userPostsDate, userPostsTime, userPost, textViewStars, textViewComments;
         ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
         String pCcontactId, postId;

         PostsViewHolder(View itemView) {
             super(itemView);

             userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
             userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
             userPostsTime = (TextView) itemView.findViewById(R.id.userPostsTime);
             userPost = (TextView) itemView.findViewById(R.id.userPost);

             textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
             textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

             imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
             imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
             imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
         }
     }

     public UserPostsAdapter(List<UserPosts> postsList, Context context) {
         this.postItems = postsList;
         this.context = context;
     }

     @Override
     public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

         return new UserPostsAdapter.PostsViewHolder(itemView);
     }

     @Override
     public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
         final UserPosts post = postItems.get(position);

         SQLiteHandler db = new SQLiteHandler(context.getApplicationContext());
         HashMap<String, String> user = db.getUserDetails();
         final String currentUserId = user.get("uid");

         if (post.getTitle() != null && !post.getTitle().isEmpty()) {
             holder.userPostsTitle.setText(post.getTitle());
         } else {
             holder.userPostsTitle.setVisibility(View.GONE);
         }
         holder.userPostsDate.setText(convertDate(postItems.get(position).getCreatedDate()));
         holder.userPostsTime.setText(convertTime(postItems.get(position).getCreatedTime()));
         holder.userPost.setText(post.getPostedText());
         if (Integer.parseInt(post.getLikesNumber()) > 0) {
             holder.textViewStars.setText(post.getLikesNumber());
         }
         holder.textViewComments.setText(post.getCommentsNumber());

         holder.pCcontactId = post.getUserId();
         final String postId = holder.postId = post.getId();

         holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
     });

     ***TRANSFORMING DATE AND TIME SEPARATELY TO CUSTOM FORMAT***
-----------------------------------------------------------------------------
private String convertDate(String time) {

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
    java.util.Locale.getDefault());

    SimpleDateFormat(datePattern);

      DateFormat.getTimeInstance(DateFormat.SHORT).parse(mTimeDisplay.getText().toString());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {

    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat("HH:mm", Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}
-----------------------------------------------------------------------------
     @Override
     public int getItemCount() {
         return postItems.size();
     }
 }
</code>```

答:
Let me explain in steps:

You can get to know default date format of device.

You must know the format of date that the server is sending to you.

Make a instance of calendar and set the dateTime as it is coming
from server.

Then you can format date and time as following (input to
SimpleDateFormat is the format that you determined in step 1):

Code:

```<code>String formattedDate = new SimpleDateFormat("yyyy-MM dd", Locale.getDefault())
        .format(Calendar.getInstance().getTime());

String formattedTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        .format(Calendar.getInstance().getTime());
</code>```

Body:
I know there are a lot of similar questions, and so far some of the solutions that I tried, but did not fully answer my question are: this, this, this, this, this, this, this, this, this, this, and a lot more.

I am making an app where I get user's post from server and sort it by date, and also displaying date and time it was created in the post. Right now I have a working solution, and I am doing it by converting string from a server in this format yyyy-MM-dd HH:mm:ss to my custom date and time format.

The problem is: I do not want to hard code a format, but instead I want to display it in the format that user phone has, and do it separately for both date and time. By the local format of the phone I mean - am-pm/24 hour format, and same for the date format - dd-MM-YY, or MM-dd-YYYY, or dd-MM, etc.

So far I have looked through a lot of solutions, most of which have that hardcoded format. I try to avoid, but I think that additional problem is that I want to separate date and time from datetime string. The other problem is that the transformation is not separate for date and time.

In short I want to format 2017-07-04 12:00:00 to 04 Jul 2017 and 12:00 PM, or 07/04/17 and 12:00. ie. Separating date and time into two strings, and displaying them in localized phone format.

My Adapter:

 public class UserPostsAdapter extends RecyclerView.Adapter<UserPostsAdapter.PostsViewHolder> {

     private List<UserPosts> postItems;
     private Context context;
     private static final String TAG = UserPosts.class.getSimpleName();

     class PostsViewHolder extends RecyclerView.ViewHolder {
    TextView userPostsTitle, userPostsDate, userPostsTime, userPost, textViewStars, textViewComments;
         ImageView imageViewDisplayComments, imageViewReply, imageViewCommentStar;
         String pCcontactId, postId;

         PostsViewHolder(View itemView) {
             super(itemView);

             userPostsTitle = (TextView) itemView.findViewById(R.id.userPostsTitle);
             userPostsDate = (TextView) itemView.findViewById(R.id.userPostsDate);
             userPostsTime = (TextView) itemView.findViewById(R.id.userPostsTime);
             userPost = (TextView) itemView.findViewById(R.id.userPost);

             textViewStars = (TextView) itemView.findViewById(R.id.textViewStars);
             textViewComments = (TextView) itemView.findViewById(R.id.textViewComments);

             imageViewCommentStar = (ImageView) itemView.findViewById(R.id.imageViewCommentStar);
             imageViewDisplayComments = (ImageView) itemView.findViewById(R.id.imageViewDisplayComments);
             imageViewReply = (ImageView) itemView.findViewById(R.id.imageViewReply);
         }
     }

     public UserPostsAdapter(List<UserPosts> postsList, Context context) {
         this.postItems = postsList;
         this.context = context;
     }

     @Override
     public UserPostsAdapter.PostsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_user_post, parent, false);

         return new UserPostsAdapter.PostsViewHolder(itemView);
     }

     @Override
     public void onBindViewHolder(final UserPostsAdapter.PostsViewHolder holder, int position) {
         final UserPosts post = postItems.get(position);

         SQLiteHandler db = new SQLiteHandler(context.getApplicationContext());
         HashMap<String, String> user = db.getUserDetails();
         final String currentUserId = user.get("uid");

         if (post.getTitle() != null && !post.getTitle().isEmpty()) {
             holder.userPostsTitle.setText(post.getTitle());
         } else {
             holder.userPostsTitle.setVisibility(View.GONE);
         }
         holder.userPostsDate.setText(convertDate(postItems.get(position).getCreatedDate()));
         holder.userPostsTime.setText(convertTime(postItems.get(position).getCreatedTime()));
         holder.userPost.setText(post.getPostedText());
         if (Integer.parseInt(post.getLikesNumber()) > 0) {
             holder.textViewStars.setText(post.getLikesNumber());
         }
         holder.textViewComments.setText(post.getCommentsNumber());

         holder.pCcontactId = post.getUserId();
         final String postId = holder.postId = post.getId();

         holder.imageViewDisplayComments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
     });

     ***TRANSFORMING DATE AND TIME SEPARATELY TO CUSTOM FORMAT***
-----------------------------------------------------------------------------
private String convertDate(String time) {

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault());
    java.util.Locale.getDefault());

    SimpleDateFormat(datePattern);

      DateFormat.getTimeInstance(DateFormat.SHORT).parse(mTimeDisplay.getText().toString());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {

    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat("HH:mm", Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}
-----------------------------------------------------------------------------
     @Override
     public int getItemCount() {
         return postItems.size();
     }
 }

Body:
Let me explain in steps:

You can get to know default date format of device.

You must know the format of date that the server is sending to you.

Make a instance of calendar and set the dateTime as it is coming
from server.

Then you can format date and time as following (input to
SimpleDateFormat is the format that you determined in step 1):

Code:

String formattedDate = new SimpleDateFormat("yyyy-MM dd", Locale.getDefault())
        .format(Calendar.getInstance().getTime());

String formattedTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        .format(Calendar.getInstance().getTime());


问:
Design Discussion: Modal React Component with Youtube Player
I'm after some design advice. I'm building out a React/Redux app that will, amongst other things, play Youtube videos in a modal dialog.

My initial design was to use lifecycle hooks to initialise the Youtube iframe API in the modal's componentDidMount. The problem with this approach is that the startup cost for the Youtube player is high - there's a noticeable delay between opening the modal, and the player popping in with the video.

What I need to do is initialise the player just once, and then cue up a different video based on which props are sent to the modal. However, I can't think of a nice, idiomatic design for this model.

Ideas I've had so far:

Hack around with the modal so that it never unmounts, but just hides based on some prop value.

This is the design I had with a previous non-React version of this app, but it feels very hacky, and I'd like to come up with something better.

Initialise the youtube player when the app loads, and hold the element in the store, passing it down to the modal via props to be rendered.

This is recommended against in the Redux FAQ

Initialise the youtube player at some higher level of the app which is always mounted, but hide it with CSS. On mounting the modal, move the element inside, and move it out again just before unmounting.

This is probably my favourite idea so far, it just feels like there might be a better idea out there.

Any thoughts on how to design this would be much appreciated!

答:
There is a similar approach to what you described as the last option (preferred one).
It is called portal as far as I can remember.

The basic method is: You make manipulation with element outside of your component in componentDidMount (eg. show) and componentWillUnmount (eg. hide).

One of the powers of React is it's lifecycle methods. You can create components even without .render() method

Examples can be found here
https://github.com/tajo/react-portal

and here
https://github.com/FormidableLabs/react-music

And there is a great talk about this at React Conf, which completely changed my mind about lifecycle methods.
https://youtu.be/395ou6k6C6k


问:
Python's alphabetical sort file error
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

```<code>fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst
</code>```

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

答:
You should be calling split() on the line, not the words in the line.

```<code>for line in file:
    result = line.split()  # this returns a list of values
    for word in result:
        # check if it already is in your list of words
list.sort()
</code>```

Title: Python's alphabetical sort file error

Body:
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

Body:
You should be calling split() on the line, not the words in the line.

for line in file:
    result = line.split()  # this returns a list of values
    for word in result:
        # check if it already is in your list of words
list.sort()


问:
Java's Float.floatToIntBits implementation code in C\C++
I want the source code for java's Float.floatToIntBits() implementation code in C\C++.</p>

答:
Google Codesearch says

```<code>public static int floatToIntBits(float value) {
        int result = floatToRawIntBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & FloatConsts.EXP_BIT_MASK) ==
              FloatConsts.EXP_BIT_MASK) &&
             (result & FloatConsts.SIGNIF_BIT_MASK) != 0)
            result = 0x7fc00000;
        return result;
    }
</code>```

Follow the link for the constants.

Body:
Google Codesearch says

public static int floatToIntBits(float value) {
        int result = floatToRawIntBits(value);
        // Check for NaN based on values of bit fields, maximum
        // exponent and nonzero significand.
        if ( ((result & FloatConsts.EXP_BIT_MASK) ==
              FloatConsts.EXP_BIT_MASK) &&
             (result & FloatConsts.SIGNIF_BIT_MASK) != 0)
            result = 0x7fc00000;
        return result;
    }

Follow the link for the constants.