问:
Log4net not working in a ASP.NET MVC Application
Web.config

```<code><configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
  </configSections>
  <log4net configSource="config\log4net.config" />
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <connectionStrings>
    <add name="catalogiDbName" connectionString="Data Source=dbserver;Initial Catalog=Catalogi;User ID=sa;Password=pyrAmid09" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Config\log4net.config

```<code><?xml version="1.0"?>
<log4net>

  <root>
    <priority value="Debug"/>
    <appender-ref ref="AsyncLog4NetAppender" />
  </root>

  <appender name="rollingFile" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="App_Data\Logs\CatalogiTraceLog.%property{log4net:HostName}.txt" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <maximumFileSize value="5MB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value=" %date [P%property{processId}/D%property{appDomainId}/T%thread] %-5level %logger - %message%newline" />
    </layout>
    <encoding value="utf-8" />
  </appender>

  <appender name="AsyncLog4NetAppender" type="Log4Net.Async.ParallelForwardingAppender">
    <appender-ref ref="rollingFile" />
  </appender>

</log4net>
</code>```

AssemblyInfo.cs of my web project

```<code>using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Catalogi.Web.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Catalogi.Web.UI")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("df78b702-d445-4a44-8d80-2888056184b2")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

// Log4net
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
</code>```

I have tried many things in trying to solve this:

Add path to config file in the assembly like

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Config\log4net.config", Watch = true)]

Set copy to output of the log4net.config file

Added <add key="log4net.Internal.Debug" value="true"/> to the web config to view debug

log4net: log4net assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\MichaelV.PROSEC\AppData\Local\Temp\Temporary ASP.NET Files\root\cd31ee63\e12ae4ed\assembly\dl3\4cb568d0\dbc1e838_1decd201\log4net.dll]. (.NET Runtime [4.0.30319.42000] on Microsoft Windows NT 6.3.9600.0)

log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]

log4net: Creating repository for assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\MichaelV.PROSEC\AppData\Local\Temp\Temporary ASP.NET Files\root\cd31ee63\e12ae4ed\assembly\dl3\c63084c3\0184b750_0cf4d201\Catalogi.Core.dll]

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]

log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]

答:
After some struggling on this issue, I have found the solution.

First I had to add a new appsettings key to locate the seperated config file:

```<code><add key="log4net.Config" value="config\log4net.config"/>
</code>```

After that I started to see some more information in the output console. I had to add the package log4net.async first for my Log4Net.Async.ParallelForwardingAppender and after that I had to add the following to the web config because it couldn't load a previous version of the log4net:

```<code>  <dependentAssembly>
    <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0"/>
  </dependentAssembly>
</code>```

Now everything is working.

Body:
Web.config

<configuration>
  <configSections>

  </configSections>
  <log4net configSource="config\log4net.config" />
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <connectionStrings>
    <add name="catalogiDbName" connectionString="Data Source=dbserver;Initial Catalog=Catalogi;User ID=sa;Password=pyrAmid09" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Config\log4net.config

<?xml version="1.0"?>
<log4net>

  <root>
    <priority value="Debug"/>
    <appender-ref ref="AsyncLog4NetAppender" />
  </root>

  <appender name="rollingFile" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="App_Data\Logs\CatalogiTraceLog.%property{log4net:HostName}.txt" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <maximumFileSize value="5MB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value=" %date [P%property{processId}/D%property{appDomainId}/T%thread] %-5level %logger - %message%newline" />
    </layout>
    <encoding value="utf-8" />
  </appender>

  <appender name="AsyncLog4NetAppender" type="Log4Net.Async.ParallelForwardingAppender">
    <appender-ref ref="rollingFile" />
  </appender>

</log4net>

AssemblyInfo.cs of my web project

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Catalogi.Web.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Catalogi.Web.UI")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("df78b702-d445-4a44-8d80-2888056184b2")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

// Log4net
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

I have tried many things in trying to solve this:

Add path to config file in the assembly like

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Config\log4net.config", Watch = true)]

Set copy to output of the log4net.config file

Added <add key="log4net.Internal.Debug" value="true"/> to the web config to view debug

log4net: log4net assembly [log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\MichaelV.PROSEC\AppData\Local\Temp\Temporary ASP.NET Files\root\cd31ee63\e12ae4ed\assembly\dl3\4cb568d0\dbc1e838_1decd201\log4net.dll]. (.NET Runtime [4.0.30319.42000] on Microsoft Windows NT 6.3.9600.0)

log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]

log4net: Creating repository for assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\MichaelV.PROSEC\AppData\Local\Temp\Temporary ASP.NET Files\root\cd31ee63\e12ae4ed\assembly\dl3\c63084c3\0184b750_0cf4d201\Catalogi.Core.dll]

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.

log4net: Assembly [Catalogi.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]

log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]

Body:
After some struggling on this issue, I have found the solution.

First I had to add a new appsettings key to locate the seperated config file:

<add key="log4net.Config" value="config\log4net.config"/>

After that I started to see some more information in the output console. I had to add the package log4net.async first for my Log4Net.Async.ParallelForwardingAppender and after that I had to add the following to the web config because it couldn't load a previous version of the log4net:

  <dependentAssembly>
    <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-2.0.8.0" newVersion="2.0.8.0"/>
  </dependentAssembly>

Now everything is working.


来源: stackexchange

问:
store negative number in char array ( still no requirred/desired solution )
```<code>EDIT:
  platform unix
  type :  ansi c
</code>```

I have data in form ;

```<code>1 2 3 -1 2 -9 1 3 +
-1 2 -3 -4 -
*
</code>```

integer in range between -9 and 9

'+ - *' operator and shows that you should take data which lies at following  line

data is char double pointer

each line must be stored in double pointer char array

```<code>example :   data[0] :=>  1 2 3 -1 2 -9 1 3 +
            more precisely :  data[0][3] must store -1
</code>```

when I take data and store, I could not achieve store -3 ( negative integer ) in data[i][j]
because '-' is a character so 3 is not accepted by data[i][j]

What should I do to handle this problem?

EDIT: MY code ;

```<code>size_t datalen = sizeof( char ) ;

data = ( char ** ) malloc( sizeof (char * ) )
for ( i = 0 ;   ; ++i )
   data[i] = (char * ) malloc ( datalen )
   for ( j = 0 ;  ; ++ j )
         signed char ch;
         if j !=  0
            datalen += 1
            data[i] = ( char * ) realloc ( begin[i], datalen )
         scanf ("%c ", &ch )
         begin[i][j] = ch
         if ch == OP ( op = + , - , * , / )
             break
   if strlen ( begin[i] ) == 1
           break
</code>```

EDIT :
     if you look at ascii table you will be understand why I am not using scanf("%d",&ch)
     http://www.asciitable.com/

答:
If you are sure that integers range between -9 and 9, and want to store them in a char individually, there is a trick, though more number calculation included.

Map {-9, -8, ... , 8, 9} to {0, 1, ..., 17, 18}, by minusing -9 for every number.  At this time, you have all non-negative integers, so do what you want.  At runtime, you should convert the data stoed to its original value by adding -9.

ContentLicense: CC BY-SA 2.5

Body:
EDIT:
  platform unix
  type :  ansi c

I have data in form ;

1 2 3 -1 2 -9 1 3 +
-1 2 -3 -4 -
*

integer in range between -9 and 9

'+ - *' operator and shows that you should take data which lies at following  line

data is char double pointer

each line must be stored in double pointer char array

example :   data[0] :=>  1 2 3 -1 2 -9 1 3 +
            more precisely :  data[0][3] must store -1

when I take data and store, I could not achieve store -3 ( negative integer ) in data[i][j]
because '-' is a character so 3 is not accepted by data[i][j]

What should I do to handle this problem?

EDIT: MY code ;

size_t datalen = sizeof( char ) ;

data = ( char ** ) malloc( sizeof (char * ) )
for ( i = 0 ;   ; ++i )
   data[i] = (char * ) malloc ( datalen )
   for ( j = 0 ;  ; ++ j )
         signed char ch;
         if j !=  0
            datalen += 1
            data[i] = ( char * ) realloc ( begin[i], datalen )
         scanf ("%c ", &ch )
         begin[i][j] = ch
         if ch == OP ( op = + , - , * , / )
             break
   if strlen ( begin[i] ) == 1
           break

EDIT :
     if you look at ascii table you will be understand why I am not using scanf("%d",&ch)
     http://www.asciitable.com/


问:
Drupal Error Message Help: User warning: The following module is missing from the file system: reference_dialog
I am receiving this error message in my Drupal reporting log every time someone visits a page on my site:

User warning: The following module is missing from the file system: reference_dialog. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1128 of D:\htdocs\guides\includes\bootstrap.inc).

I have looked and looked for an answer but cannot find out exactly what I should do.
Here we are the two pages I have already reviewed:

https://www.drupal.org/node/2487215 and https://www.drupal.org/node/2767187

If anyone can helps me, please let me know.

Thank you,
Garret

答:
The specified module is missed in your files ie the reference_dialog module does not exist in your module folder  but you might have enabled the module and areference exist in database.So you get this error message.

To resolve :

Download this module.

if you don't use this module

Disable and uninstall it.

Remove the module from modules folder

.

ContentLicense: CC BY-SA 3.0


问:
Build multiple maven pom files and log in to a single file
I am working on a Java project. In my project multiple dependency projects are these. So I created a bat file to build all projects one by one. Please see the logic I used to achieve this.

```<code>set x=proj1-prx
set y=proj2-prx
set z=proj3-prx

set LIST=(%x% %y% %z% )

echo Checkout and deploy started
for %%G in %LIST% do (
set _module=%%G
set  _value=!%%G!
echo Checkout module - %%G
svn checkout %SVNHOST%/%%G/%REPO% %WORKSPACE%\%%G\%REPO% --username %USER% --password %PASSWORD%
echo Install module to AEM - %%G
mvn clean install -Dskiptests  -f %WORKSPACE%\%%G\%REPO%\pom.xml -l output.log
@ECHO OFF
)
echo Checkout and deploy finished
</code>```

This file is executing well , Log file also creating but each time for loop building a project the build result overrides in to log file. I want build result of all project. Please help me friends

答:
I want build result of all project. Please help me friends

You cannot depend on mavens logger implementation. Use the OS stdout/stderr redirection:

at the beginning of your batch file delete the old log content:

```<code>echo > output.log
</code>```

then change the maven call:

```<code>mvn clean install -Dskiptests  -f %WORKSPACE%\%%G\%REPO%\pom.xml >> output.log 2>&1
</code>```

Body:
I am working on a Java project. In my project multiple dependency projects are these. So I created a bat file to build all projects one by one. Please see the logic I used to achieve this.

set x=proj1-prx
set y=proj2-prx
set z=proj3-prx

set LIST=(%x% %y% %z% )

echo Checkout and deploy started
for %%G in %LIST% do (
set _module=%%G
set  _value=!%%G!
echo Checkout module - %%G
svn checkout %SVNHOST%/%%G/%REPO% %WORKSPACE%\%%G\%REPO% --username %USER% --password %PASSWORD%
echo Install module to AEM - %%G
mvn clean install -Dskiptests  -f %WORKSPACE%\%%G\%REPO%\pom.xml -l output.log
@ECHO OFF
)
echo Checkout and deploy finished

This file is executing well , Log file also creating but each time for loop building a project the build result overrides in to log file. I want build result of all project. Please help me friends

Body:
I want build result of all project. Please help me friends

You cannot depend on mavens logger implementation. Use the OS stdout/stderr redirection:

at the beginning of your batch file delete the old log content:

echo > output.log

then change the maven call:

mvn clean install -Dskiptests  -f %WORKSPACE%\%%G\%REPO%\pom.xml >> output.log 2>&1


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
You basically have two choices: switch to using IEnumerable instead of IList<T>, as every IList<> is also an IEnumerable. You can then use as and is to determine which code path to take, casting as necessary to call the appropriate method.

Your other option is to use dynamic method invocation, which lets you call a method based upon the runtime type referenced by the object variable, e.g.

```<code>object o = ...;
SomeMethod((dynamic) o);

private void SomeMethod<T>(IList<T> list) { ... }
private void SomeMethod(string str) { ... }
</code>```

Though, of the top of my head, I cannot remember if you can do a dynamic invocation to a method with a type parameter. If not, you'd have to replace SomeMethod<T>(IList<T> list) with SomeMethod(IEnumerable e).

Personally I'd take the first path. Whilst cruder it's easier to read and debug.

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
You basically have two choices: switch to using IEnumerable instead of IList<T>, as every IList<> is also an IEnumerable. You can then use as and is to determine which code path to take, casting as necessary to call the appropriate method.

Your other option is to use dynamic method invocation, which lets you call a method based upon the runtime type referenced by the object variable, e.g.

object o = ...;
SomeMethod((dynamic) o);

private void SomeMethod<T>(IList<T> list) { ... }
private void SomeMethod(string str) { ... }

Though, of the top of my head, I cannot remember if you can do a dynamic invocation to a method with a type parameter. If not, you'd have to replace SomeMethod<T>(IList<T> list) with SomeMethod(IEnumerable e).

Personally I'd take the first path. Whilst cruder it's easier to read and debug.


问:
Hibernate Inheritance mapping
Basically I am trying to implement an Observer pattern, Data is getting stored into the database but the while retrieving it is showing an error.
What I am trying to create is a set of categories and all the leaf nodes will contain questions.I am learning hibernate, so any kind of help will be appreciated.
Error is given below.

ERROR:  could not resolve property: parent_child_id of: hierarchy.Component
    at
org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83) ...

This is a Component class

```<code>@Entity
@Table(name = "Component")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType =    DiscriminatorType.STRING)
public abstract class Component {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int component_id;
private String name;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_child_id")
private Component parent;

public Component() {

}

public Component(String name, Component parent) {
    super();
    this.name = name;
    this.parent = parent;
}

public int getComponent_id() {
    return component_id;
}

public void setComponent_id(int component_id) {
    this.component_id = component_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

/*public abstract Iterator<Component> getChildren();

public abstract Component getParent();*/

public List<Component> getChildren() {
    throw new UnsupportedOperationException();
}

public void setParent(Component parent) {
    this.parent = parent;
}

public Component getParent() {
    return this.parent;
}

public void setSize(int size) {
    throw new UnsupportedOperationException();
}

public int getSize() {
    throw new UnsupportedOperationException();
}
}
</code>```

This is a Category class

```<code>@Entity
public class Category extends Component {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
private List<Component> children = new ArrayList<Component>(0);

public Category() {

}

public Category(String name, Component parent) {
    super(name, parent);
}

@Override
public List<Component> getChildren() {
    return children;
}
}
</code>```

This is a Question class

```<code>@Entity
public class Question extends Component {

private int size;

public Question() {

}

public Question(String name, Component parent) {
    super(name, parent);
}

@Override
public void setSize(int size) {
    this.size = size;
}

@Override
public int getSize() {
    return this.size;
}
}
</code>```

And this is the Main class

```<code>public class Main {

private SessionFactory factory;

public Main() {
    factory = HibieUtil.getSessionFactory();
}

public void insertData(Component root) {
    Session sessie = factory.openSession();
    Transaction transaction = null;
    try {
        transaction = sessie.beginTransaction();
        sessie.save(root);
        transaction.commit();
    } catch(HibernateException e) {
        if(transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        sessie.close();
    }
}

public void showData(Component node) {
    if(node == null) return;
    System.out.println(node.getName());
    Iterator<Component> children = node.getChildren().iterator();
    while(children.hasNext())
        showData(children.next());
}

public void display() {
    Session sessie = factory.openSession();
    Transaction transaction = null;
    try {
        transaction = sessie.beginTransaction();
        Criteria criteria = sessie.createCriteria(Component.class);
        criteria.add(Restrictions.eq("parent_child_id", null));

        @SuppressWarnings("unchecked")
        List<Component> result = criteria.list();
        if(result != null)
            showData(result.get(0));
        transaction.commit();
    } catch(HibernateException e) {
        if(transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        sessie.close();
    }
}

public static void main(String[] args) {
    Main main = new Main();
    Component root = new Category("Root", null);
    Component childA = new Category("ChildA", root);
    Component childB = new Category("ChildB", root);
    root.getChildren().add(childA);
    root.getChildren().add(childB);
    Component questionA = new Question("Question A", childA);
    questionA.setSize(10);
    Component quesitonB = new Question("Question B", childA);
    quesitonB.setSize(5);
    childA.getChildren().add(questionA);
    childA.getChildren().add(quesitonB);
    main.insertData(root);
    main.display();
}

}
</code>```

答:
In your display method you must specify propertyname of component not the column name in database change  :

```<code> criteria.add(Restrictions.eq("parent_child_id", null));
</code>```

by:

```<code> criteria.add(Restrictions.eq("parent", null));
</code>```

Title: Hibernate Inheritance mapping

Body:
Basically I am trying to implement an Observer pattern, Data is getting stored into the database but the while retrieving it is showing an error.
What I am trying to create is a set of categories and all the leaf nodes will contain questions.I am learning hibernate, so any kind of help will be appreciated.
Error is given below.

ERROR:  could not resolve property: parent_child_id of: hierarchy.Component
    at
org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83) ...

This is a Component class

@Entity
@Table(name = "Component")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType =    DiscriminatorType.STRING)
public abstract class Component {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int component_id;
private String name;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_child_id")
private Component parent;

public Component() {

}

public Component(String name, Component parent) {
    super();
    this.name = name;
    this.parent = parent;
}

public int getComponent_id() {
    return component_id;
}

public void setComponent_id(int component_id) {
    this.component_id = component_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

/*public abstract Iterator<Component> getChildren();

public abstract Component getParent();*/

public List<Component> getChildren() {
    throw new UnsupportedOperationException();
}

public void setParent(Component parent) {
    this.parent = parent;
}

public Component getParent() {
    return this.parent;
}

public void setSize(int size) {
    throw new UnsupportedOperationException();
}

public int getSize() {
    throw new UnsupportedOperationException();
}
}

This is a Category class

@Entity
public class Category extends Component {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
private List<Component> children = new ArrayList<Component>(0);

public Category() {

}

public Category(String name, Component parent) {
    super(name, parent);
}

@Override
public List<Component> getChildren() {
    return children;
}
}

This is a Question class

@Entity
public class Question extends Component {

private int size;

public Question() {

}

public Question(String name, Component parent) {
    super(name, parent);
}

@Override
public void setSize(int size) {
    this.size = size;
}

@Override
public int getSize() {
    return this.size;
}
}

And this is the Main class

public class Main {

private SessionFactory factory;

public Main() {
    factory = HibieUtil.getSessionFactory();
}

public void insertData(Component root) {
    Session sessie = factory.openSession();
    Transaction transaction = null;
    try {
        transaction = sessie.beginTransaction();
        sessie.save(root);
        transaction.commit();
    } catch(HibernateException e) {
        if(transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        sessie.close();
    }
}

public void showData(Component node) {
    if(node == null) return;
    System.out.println(node.getName());
    Iterator<Component> children = node.getChildren().iterator();
    while(children.hasNext())
        showData(children.next());
}

public void display() {
    Session sessie = factory.openSession();
    Transaction transaction = null;
    try {
        transaction = sessie.beginTransaction();
        Criteria criteria = sessie.createCriteria(Component.class);
        criteria.add(Restrictions.eq("parent_child_id", null));

        @SuppressWarnings("unchecked")
        List<Component> result = criteria.list();
        if(result != null)
            showData(result.get(0));
        transaction.commit();
    } catch(HibernateException e) {
        if(transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        sessie.close();
    }
}

public static void main(String[] args) {
    Main main = new Main();
    Component root = new Category("Root", null);
    Component childA = new Category("ChildA", root);
    Component childB = new Category("ChildB", root);
    root.getChildren().add(childA);
    root.getChildren().add(childB);
    Component questionA = new Question("Question A", childA);
    questionA.setSize(10);
    Component quesitonB = new Question("Question B", childA);
    quesitonB.setSize(5);
    childA.getChildren().add(questionA);
    childA.getChildren().add(quesitonB);
    main.insertData(root);
    main.display();
}

}

Body:
In your display method you must specify propertyname of component not the column name in database change  :

 criteria.add(Restrictions.eq("parent_child_id", null));

by:

 criteria.add(Restrictions.eq("parent", null));


问:
HTML Javascript font size change
```<code><html>
<head>
  <meta charset="utf-8">
  <script>
    function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;
      document.write("name="+name+"");
      document.write("&snumber="+snumber+"<br />");
    }
  </script>
</head>

<body>
   <h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">
</body>
</html>
</code>```

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

```<code> <h2></h2>
</code>```

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

答:
Simply add h2 tag

Single line output:

function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;

 document.write("
name="+name+"");
 document.write("&snumber="+snumber+"

");
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();"></code>```

For multiline output: Just close
 tag and start new heading tag like:

```<code>document.write("<h2>name="+name+"</h2>");
document.write("<h2>snumber="+snumber+"</h2><br />");
</code>```

Title: HTML Javascript font size change

Body:
  <meta charset="utf-8">

Example of sending data using POST

     Name :
   <input type="text" id="name">

     Student number:
   <input type="text" id="snumber">

   <input type="button" value="submit" onclick="test();">

I want to change the font size of 6th and 7th lines' result to h2 size
I can change in body section by putting

however, it's not working in a script section. If I input data in name and snumber section, It connects to a new page that shows inputs like "name=David&snum=21467564" I want this font size to be h2 size!

Body:
Simply add h2 tag

Single line output:

function test(){
      var name = document.getElementById('name').value;
      var snumber = document.getElementById('snumber').value;

 document.write("<h2>name="+name+"");
 document.write("&snumber="+snumber+"</h2> <br/>");
 }

<h2>Example of sending data using POST</h2>
     Name :
   <input type="text" id="name"><br/>
     Student number:
   <input type="text" id="snumber"><br/><br/>
   <input type="button" value="submit" onclick="test();">

For multiline output: Just close <h2> tag and start new heading tag like:

document.write("<h2>name="+name+"</h2>");
document.write("<h2>snumber="+snumber+"</h2><br />");


问:
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>```

答:
Usman Rana’s answer is correct and well explained. What I want to contribite is the modern answer since the replacements for SimpleDateFormat and Date have been out for years now.

```<code>    String dateTimeString = "2017-07-04 12:00:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
    String formattedDate
            = dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
    System.out.println(formattedDate);
    String formattedTime
            = dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
    System.out.println(formattedTime);
</code>```

On my computer this prints

```<code>04-07-2017
12:00:00
</code>```

And the idea is exactly what you asked for, these are the date format and the time format set up on my computer, so each device will print the date and the time in its own preferred way.

Beware that there’s a potential time zone issue here. If you want to display the server’s time on the user’s phone no matter where in the world the user is taking her/his phone, you should be fine. If you wanted to use the phone’s time zone, you need to convert the date-time first, and for that you need to know the server time zone. Or probably better, the server would need to send the date and time in UTC.

The modern Java date and time API that I am using will come natively to Android Java. Until that happens, you will need the ThreeTenABP, the backport to Android Java 7. See How to use ThreeTenABP in Android Project.

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:
Usman Rana’s answer is correct and well explained. What I want to contribite is the modern answer since the replacements for SimpleDateFormat and Date have been out for years now.

    String dateTimeString = "2017-07-04 12:00:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
    String formattedDate
            = dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
    System.out.println(formattedDate);
    String formattedTime
            = dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
    System.out.println(formattedTime);

On my computer this prints

04-07-2017
12:00:00

And the idea is exactly what you asked for, these are the date format and the time format set up on my computer, so each device will print the date and the time in its own preferred way.

Beware that there’s a potential time zone issue here. If you want to display the server’s time on the user’s phone no matter where in the world the user is taking her/his phone, you should be fine. If you wanted to use the phone’s time zone, you need to convert the date-time first, and for that you need to know the server time zone. Or probably better, the server would need to send the date and time in UTC.

The modern Java date and time API that I am using will come natively to Android Java. Until that happens, you will need the ThreeTenABP, the backport to Android Java 7. See How to use ThreeTenABP in Android Project.


问:
mysql IF ELSE statement syntax error
I have the following query:

```<code>    SELECT
     *
FROM
    `hssData`
WHERE
    `group` = 'LGA_737_CA'
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    )
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    )
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    )
    AND `days` >= 1
    AND `days` <= 2
ORDER BY
    `depTime` ASC
LIMIT
    0, 100
</code>```

...except that when arrTimeInt <= 45 I want :

```<code>`days` >= 1 AND `days` <= 1
</code>```

And not

```<code>`days` >= 1 AND `days` <= 2
</code>```

I have tried:

```<code>       SELECT
    *
FROM
    `hssData`
WHERE
    `group` = 'LGA_737_CA'
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    )
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    )
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    )
    AND (
        IF (`arrTimeInt` < 45) THEN (
            `days` <= 1 AND `days` <= 3
        ) ELSE (
            `days` <= 1 AND `days` <= 2
        )
    )
ORDER BY
    `depTime` ASC
LIMIT
    0, 100
</code>```

but this throws a syntax error.

I am unable to get the correct syntax. what am I doing wrong?  The syntax error is:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ') THEN (
              days <= 1
              AND days <= 2
          ) ELSE (
              days <= 1
              A' at line 20

答:
You are trying to a procedural construct in a non-procedural context.

Within a SELECT (or UPDATE or DELETE) statement you need to use the IF function (or CASE). Hence:

```<code> SELECT
   *
 FROM
    `hssData`
 WHERE
  `group` = 'LGA_737_CA'
  AND (
    `pos` = 'CA'
    OR `pos` = 'RC'
  )
  AND (   // brackets in this clause are redundant
    `depTimeInt` >= 0
    AND `depTimeInt` <= 1440
  )
  AND (
    `arrTimeInt` >= 1050
    OR `arrTimeInt` <= 45
  )
  AND `days` >= 1
  AND `days` <= IF(`arrTimeInt` <= 45, 1, 2)
ORDER BY
  `depTime` ASC
LIMIT
  0, 100
</code>```

Title: mysql IF ELSE statement syntax error

Body:
I have the following query:

    SELECT
     *
FROM
    `hssData`
WHERE
    `group` = 'LGA_737_CA'
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    )
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    )
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    )
    AND `days` >= 1
    AND `days` <= 2
ORDER BY
    `depTime` ASC
LIMIT
    0, 100

...except that when arrTimeInt <= 45 I want :

`days` >= 1 AND `days` <= 1

And not

`days` >= 1 AND `days` <= 2

I have tried:

       SELECT
    *
FROM
    `hssData`
WHERE
    `group` = 'LGA_737_CA'
    AND (
        `pos` = 'CA' OR `pos` = 'RC'
    )
    AND (
        `depTimeInt` >= 0 AND `depTimeInt` <= 1440
    )
    AND (
        `arrTimeInt` >= 1050 OR `arrTimeInt` <= 45
    )
    AND (
        IF (`arrTimeInt` < 45) THEN (
            `days` <= 1 AND `days` <= 3
        ) ELSE (
            `days` <= 1 AND `days` <= 2
        )
    )
ORDER BY
    `depTime` ASC
LIMIT
    0, 100

but this throws a syntax error.

I am unable to get the correct syntax. what am I doing wrong?  The syntax error is:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ') THEN (
              days <= 1
              AND days <= 2
          ) ELSE (
              days <= 1
              A' at line 20

Body:
You are trying to a procedural construct in a non-procedural context.

Within a SELECT (or UPDATE or DELETE) statement you need to use the IF function (or CASE). Hence:

 SELECT
   *
 FROM
    `hssData`
 WHERE
  `group` = 'LGA_737_CA'
  AND (
    `pos` = 'CA'
    OR `pos` = 'RC'
  )
  AND (   // brackets in this clause are redundant
    `depTimeInt` >= 0
    AND `depTimeInt` <= 1440
  )
  AND (
    `arrTimeInt` >= 1050
    OR `arrTimeInt` <= 45
  )
  AND `days` >= 1
  AND `days` <= IF(`arrTimeInt` <= 45, 1, 2)
ORDER BY
  `depTime` ASC
LIMIT
  0, 100


问:
MySQL: How to get result from 2 different tables with 1 WHERE IN CLAUSE
I have 2 tables with different content and there is no way to join tables because there is no common identifier, but every table as 1 column with same content. I need to extract the content from these both colums and want to get ID's from each record that is the same. The following query extracts what I already know/have, but I don't get the ID's from the WHERE IN table.

Query

```<code>SELECT pd.products_id, pd.products_short_description
FROM products_description pd
WHERE pd.products_short_description IN (SELECT m.manufacturers_ean FROM manufacturers m)
</code>```

Result

```<code>ID | products_short_description
-------------------------------
2  | BMW
</code>```

This is what I need:

```<code>ID | products_short_description | ID | manufacturers_ean
--------------------------------------------------------
2  | BMW                        | 285| BMW
</code>```

答: Answer to all: Perfect! It works! Where an I mark it as solved?</p>

Body:
I have 2 tables with different content and there is no way to join tables because there is no common identifier, but every table as 1 column with same content. I need to extract the content from these both colums and want to get ID's from each record that is the same. The following query extracts what I already know/have, but I don't get the ID's from the WHERE IN table.

Query

SELECT pd.products_id, pd.products_short_description
FROM products_description pd
WHERE pd.products_short_description IN (SELECT m.manufacturers_ean FROM manufacturers m)

Result

ID | products_short_description
-------------------------------
2  | BMW

This is what I need:

ID | products_short_description | ID | manufacturers_ean
--------------------------------------------------------
2  | BMW                        | 285| BMW


问:
Do I need to add thread locking to simple variables?
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

```<code>enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}
</code>```

答: “need locking” needs to be quallified with what you expect to be safe from.  If you need to update more than one value in a coordinated manner, you certainly need to lock.  If you do a read/modify/write on more than one thread, you needto lock or use special speculative code that can note the interruption of another thread.  For simple use of single values, you can use special atomic operations.  Sometimes just setting a value doesn’t need locking, but that depends on the situation.</p>

Body:
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}


问:
Simple vs cryptic usernames
When creating users (for instance in a linux system), are there any security recommendations for the syntax of the username?

Let´s say:
Is "FTP_User1" less "secure" than something like "Xg_32_FTP_User1_043"?

I have already seen this attempt of trying to bloat usernames several times but never came to a conclusion whether it is actually helpful. It might prevent attackers from guessing account names, but that won´t help them a lot when a strong password is used.

Any thoughts?

答:
No, there aren't such recommendations and there really shouldn't be.

Usernames aren't a secret, and the word "secret" has a rather specific meaning in information security - it is something that you must keep hidden at all costs (i.e. passwords, encryption keys, etc).

It is common sense to make life harder for potential attackers, but attempting to make usernames unguessable may only stop the teenage hacker wannabes, who wouldn't be able to go past the next step (e.g. password protection) anyway.

Any skilled attacker wouldn't even try to guess, but would find a direct way to get a full list of your usernames, or have a go at one they already know exists.

It is leaking usernames via other means that you must prevent. Making the login names unguessable is just a waste of time, and really annoying to users.

Title: Simple vs cryptic usernames


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答:
It doesn't make a great deal of difference if the names of the elements in the list are always the same, because if you're processing it using XPath or Linq-to-XML or whatever then the query will just have one more selector if there's a wrapper node, but otherwise will be identical.

On the other hand if the element names in the list may differ, then it can make processing the list easier if there is a wrapper element, because you can just use '*' as the selector below the list element rather than having to filter all elements to those with a specified set of names.

So it probably doesn't matter hugely, but I tend to prefer having a wrapper element just because it visually delineates the items in the collection from items that are not.

OwnerDisplayName: Mat

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

OwnerDisplayName: Greg Beech


问:
Draft.js 's RichUtils.toggleInlineStyle doesn't work
Draft.js 's RichUtils.toggleInlineStyle doesn't work properly. please help!
My code is on JSfiddle.

Is there any misunderstood?

```<code>var TextArea = React.createClass({
  ...
  toggleBlockStyle: function(blockType) {
    this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); // don't work!
  },

  toggleInlineStyle: function(inlineStyle) {
    this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); // don't work!
  },

  handleClear: function() {
    this.onChange(EditorState.push(this.state.editorState,
        ContentState.createFromText(''), 'remove-range')); // don't work!
  },
  ...
  render: function() {
    return (
      <div onClick={this.onFocus}>
        {this.renderButtons()}
        <Editor editorState={this.state.editorState}
          className={this.props.className}
          name={this.props.name} ref="editor"
          placeholder={this.props.placeholder}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.onChange}
          spellCheck={true}
          stripPastedStyles={true}
          customStyleMap={myStyleMap}/>
      </div>);
   }
}
</code>```

答:
The reason why its not coming is you need to include the css file available. Include the css file and it will fine. (Draft.css)

https://draftjs.org/docs/advanced-topics-issues-and-pitfalls/#missing-draftcss

see the last line of the page.

Body:
Draft.js 's RichUtils.toggleInlineStyle doesn't work properly. please help!
My code is on JSfiddle.

Is there any misunderstood?

var TextArea = React.createClass({
  ...
  toggleBlockStyle: function(blockType) {
    this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); // don't work!
  },

  toggleInlineStyle: function(inlineStyle) {
    this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); // don't work!
  },

  handleClear: function() {
    this.onChange(EditorState.push(this.state.editorState,
        ContentState.createFromText(''), 'remove-range')); // don't work!
  },
  ...
  render: function() {
    return (

        {this.renderButtons()}
        <Editor editorState={this.state.editorState}
          className={this.props.className}
          name={this.props.name} ref="editor"
          placeholder={this.props.placeholder}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.onChange}
          spellCheck={true}
          stripPastedStyles={true}
          customStyleMap={myStyleMap}/>

);
   }
}

ContentLicense: CC BY-SA 4.0


问:
Neo4j with Spring - Best Repository Design
Currently I am working on project based on Spring data Neo4j. Here in most nodes, there can be multiple type of different relationships like given in below example.

Node definition

```<code>    @NodeEntity(label = CollectionNames.User)
    public class User{

        @GraphId
        private Long id;

        //Different Parameters, removed because these are irrelevant
        @Relationship(type = RelationshipNames.HAS_CONTACT, direction = Relationship.OUTGOING)
        private Set<HasContact> contactList;

        @Relationship(type = RelationshipNames.HAS_INVITED, direction = Relationship.OUTGOING)
        private Set<HasInvited> invitedContacts;

        @Relationship(type = RelationshipNames.HAS_FAVORITE, direction = Relationship.OUTGOING)
        private Set<HasFavorite> favoriteMerchants;

    //And so many others such relationships

    //Constructor and Getters() & Setters()
}
</code>```

Repository Definition

```<code>@Repository
public interface UserRepository extends GraphRepository<User>{

    List<User> findByUsernameIn(Set<String> username, @Depth int depth);//Here for exp, I just want to load user with his/her 'contactList' entries only
    User findByUsername(String username, @Depth int depth);
}
</code>```

Although this repository is working fine while loading given user with given depth, but main issue is that this query will load all existing relationships with up to given depth. As here I am just interested in some/ or just one particular type of relationship, so how can that be possible using Spring Named Query methods? Can I specify depth for each relationship while loading using Named Query methods? Or I have to write custom query for each such relationship using @Query annotation? We want to minimize usage of Custom queries!

So what is the best Repository Design in Spring Data Neo4j for such cases?
Suggestion will be highly appreciated!

答:
As of SDN version 4.2.x custom cypher query in @Query or by using session.query is you best option if you want to avoid loading all related entities.

Work on more fine grained loading is being done in the upcoming release. See this github issue.

Body:
Currently I am working on project based on Spring data Neo4j. Here in most nodes, there can be multiple type of different relationships like given in below example.

Node definition

    @NodeEntity(label = CollectionNames.User)
    public class User{

        @GraphId
        private Long id;

        //Different Parameters, removed because these are irrelevant
        @Relationship(type = RelationshipNames.HAS_CONTACT, direction = Relationship.OUTGOING)
        private Set<HasContact> contactList;

        @Relationship(type = RelationshipNames.HAS_INVITED, direction = Relationship.OUTGOING)
        private Set<HasInvited> invitedContacts;

        @Relationship(type = RelationshipNames.HAS_FAVORITE, direction = Relationship.OUTGOING)
        private Set<HasFavorite> favoriteMerchants;

    //And so many others such relationships

    //Constructor and Getters() & Setters()
}

Repository Definition

@Repository
public interface UserRepository extends GraphRepository<User>{

    List<User> findByUsernameIn(Set<String> username, @Depth int depth);//Here for exp, I just want to load user with his/her 'contactList' entries only
    User findByUsername(String username, @Depth int depth);
}

Although this repository is working fine while loading given user with given depth, but main issue is that this query will load all existing relationships with up to given depth. As here I am just interested in some/ or just one particular type of relationship, so how can that be possible using Spring Named Query methods? Can I specify depth for each relationship while loading using Named Query methods? Or I have to write custom query for each such relationship using @Query annotation? We want to minimize usage of Custom queries!

So what is the best Repository Design in Spring Data Neo4j for such cases?
Suggestion will be highly appreciated!


问:
LINQ to XML how compare children with repeater items
I've got a print button that gives XML data to filling an adobe lifecycle template. I'm trying to compare ROWID in XML with a repeater rowid to make it print the information about the row the button was clicked on.

```<code>Int32 rownum = Convert.ToInt32(e.CommandArgument.ToString());
string xmlROWID = Xmld.Descendants("ROWID").First().Value;
</code>```

Here are 2 of the children in the XML:

```<code><VKRSADL>
    <CUSTOMER_SADLS>
      <TABLEVALUE>
        <ROW>
          <ROWID>0</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>1</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>777</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL0>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL0>
          </XML>
          <XMLCHECK />
        </ROW>
        <ROW>
          <ROWID>1</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>2</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>123123</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL1>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL1>
          </XML>
          <XMLCHECK />
        </ROW>
      </TABLEVALUE>
    </CUSTOMER_SADLS>
  </VKRSADL>
</code>```

Comparing it to the First() gives me only the first ROWID, and there can be multiple. How can I compare the repeater rowid it to each of the ROWID's I've got saved?

I've tried this:

```<code>foreach (var child in Xmld.Root.Element("REQUEST").Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements("ROW").Elements()) {
    //DO SOMETHING
}
</code>```

but I get an error:
An exception of type 'System.NullReferenceException' occurred in App_Web_f2rvuyke.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

答:
Try following :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("ROW").Select(x => new {
                rowID = (int)x.Element("ROWID"),
                id = (string)x.Element("ID"),
                type = (int)x.Element("TYPE"),
                typeID = (int)x.Element("TYPEID"),
                typeCode = (int)x.Element("TYPECODE"),
                crsCode = (int)x.Element("CRSCODE"),
            }).ToList();
        }
    }
}
</code>```

Body:
I've got a print button that gives XML data to filling an adobe lifecycle template. I'm trying to compare ROWID in XML with a repeater rowid to make it print the information about the row the button was clicked on.

Int32 rownum = Convert.ToInt32(e.CommandArgument.ToString());
string xmlROWID = Xmld.Descendants("ROWID").First().Value;

Here are 2 of the children in the XML:

<VKRSADL>
    <CUSTOMER_SADLS>
      <TABLEVALUE>
        <ROW>
          <ROWID>0</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>1</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>777</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL0>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL0>
          </XML>
          <XMLCHECK />
        </ROW>
        <ROW>
          <ROWID>1</ROWID>
          <ID>Съкредитополучател</ID>
          <TYPE>48</TYPE>
          <TYPEID>2</TYPEID>
          <TYPECODE>1</TYPECODE>
          <CRSCODE>123123</CRSCODE>
          <EGN />
          <NAME />
          <XML>
            <SADL1>
              <OwnerCrsCode />
              <TABLEVALUE />
            </SADL1>
          </XML>
          <XMLCHECK />
        </ROW>
      </TABLEVALUE>
    </CUSTOMER_SADLS>
  </VKRSADL>

Comparing it to the First() gives me only the first ROWID, and there can be multiple. How can I compare the repeater rowid it to each of the ROWID's I've got saved?

I've tried this:

foreach (var child in Xmld.Root.Element("REQUEST").Element("VKRSADL").Element("CUSTOMER_SADLS").Element("TABLEVALUE").Elements("ROW").Elements()) {
    //DO SOMETHING
}

but I get an error:
An exception of type 'System.NullReferenceException' occurred in App_Web_f2rvuyke.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("ROW").Select(x => new {
                rowID = (int)x.Element("ROWID"),
                id = (string)x.Element("ID"),
                type = (int)x.Element("TYPE"),
                typeID = (int)x.Element("TYPEID"),
                typeCode = (int)x.Element("TYPECODE"),
                crsCode = (int)x.Element("CRSCODE"),
            }).ToList();
        }
    }
}


问:
javafx2.0 - force refresh the scene
In my app, one scene having the popup dialog which consists of some fields and buttons. If you click on the button then I want to dismiss the popup dialog as well as update the some fields in the scene. Indirectly I want to refresh scene. is it possible?

I used the following code.Here what I did is, I get the controller of that scene and then update the field using id. but it doesn't work.

```<code> URL location = AdmincontrolController.class.getResource("admincontrol.fxml");

 FXMLLoader fxmlLoader = new FXMLLoader();
 fxmlLoader.setLocation(location);
 fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
 try {
     Parent root = (Parent) fxmlLoader.load(location.openStream());
     AdmincontrolController controller = fxmlLoader.getController();
     System.out.println("AdmincontrolController: "+controller);
     controller.setEmail(item.getEmail());
 } catch (IOException ex) {
     Logger.getLogger(Add_loginController.class.getName()).log(Level.SEVERE, null, ex);
 }
</code>```

Scenario:

scene

Popup - If we clicks on the add then we need to dismiss that dialog and change the email text on the previous scene.

答:
Everytime you have the Feeling that you manually want to update a Scene you should probably use a backgroundWorker Thread to do the work.
This way your UI Thread can use the time to update Labels etc.</p>

Title: javafx2.0 - force refresh the scene

Body:
In my app, one scene having the popup dialog which consists of some fields and buttons. If you click on the button then I want to dismiss the popup dialog as well as update the some fields in the scene. Indirectly I want to refresh scene. is it possible?

I used the following code.Here what I did is, I get the controller of that scene and then update the field using id. but it doesn't work.

 URL location = AdmincontrolController.class.getResource("admincontrol.fxml");

 FXMLLoader fxmlLoader = new FXMLLoader();
 fxmlLoader.setLocation(location);
 fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
 try {
     Parent root = (Parent) fxmlLoader.load(location.openStream());
     AdmincontrolController controller = fxmlLoader.getController();
     System.out.println("AdmincontrolController: "+controller);
     controller.setEmail(item.getEmail());
 } catch (IOException ex) {
     Logger.getLogger(Add_loginController.class.getName()).log(Level.SEVERE, null, ex);
 }

Scenario:

scene

Popup - If we clicks on the add then we need to dismiss that dialog and change the email text on the previous scene.


问:
Does C have a standard ABI?
From a discussion somewhere else:

C++ has no standard ABI (Application Binary Interface)

But neither does C, right?

On any given platform it pretty much does. It wouldn't be useful as the lingua franca for inter-language communication if it lacked one.

What's your take on this?

答:
An ABI, even for C, has parts which are quite platform independent, parts which depend on the processor (which registers should be saved, which are used for passing parameters,...) and parts which depend on the OS (more or less the same factors as for the processor as some choices are not imposed by the architecture but are the result of trade-offs, plus some OS's have a language independent notion of exception and so a compiler for any language has to generate the right thing to handle those, handling of threads may also impose things on the ABI -- if a register points to TLS, you can't use it for what you want).

In theory, every compiler may have its own ABI.  But usually, for a couple processor/OS, the ABI is fixed by the OS vendor which often also provide a C compiler and common libraries which use that ABI and competitors prefer to be compatible.  (I'd not be surprised if there are exceptions for some OS for which C isn't a major programming language).

But the OS vendor may switch ABI for one reason or the  other (new versions of processors may have features that you want to use in the ABI for one - for instance some have asked for a 32bit ABI for x86_64 allowing to use all the registers).  During the migration phase - which may be for a very long time - you may have to handle two ABI.

Title: Does C have a standard ABI?


问:
YQL new htmlstring table not working like the old html table
I've been using YQL for HTML scraping but now Yahoo have stopped supporting the html table so I replaced it with the htmlstring table (community table) and the additional parameters as suggested here.

However, I used to search for all divs and get them returned as an array so I could iterate through the elements, now when using htmlstring I get the result as plain HTML and I can't do anything with it.

Here's an example of how it looks now: http://i.imgur.com/vWJ65wo.jpg

I used to be able to loop through all divs in the array query.results.div.

答: Solved it by cleaning up the html and using html2json.</p>


问:
Install Node in ubuntu
I want to install node to run Angular2 program, but while installing I am getting this error:

```<code>npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN using --force I sure hope you know what you are doing.

/usr/local/lib/node_modules/npm/lib/cache.js:3
const BB = require('bluebird')
^^^^^
npm ERR! Use of const in strict mode.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-04T10_51_42_147Z-debug.log
</code>```

I've already tried this solution:

```<code>sudo npm cache clean -f
sudo npm install -g n
sudo n stable
</code>```

but even for first command "sudo npm cache clean -f" I am getting same issue. Please let me know if anyone aware about same.

答:
I, personally, am a huge fan of nvm.
It makes node installation and versions manipulations so easy.

All install instructions can be found here.

I'll just give an example command of installing new nodejs version and start using it, so you understand how clear and easy it is:

```<code>nvm install 8.0
nvm use 8.0
</code>```

Title: Install Node in ubuntu

Body:
I want to install node to run Angular2 program, but while installing I am getting this error:

npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN using --force I sure hope you know what you are doing.

/usr/local/lib/node_modules/npm/lib/cache.js:3
const BB = require('bluebird')
^^^^^
npm ERR! Use of const in strict mode.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-04T10_51_42_147Z-debug.log

I've already tried this solution:

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

but even for first command "sudo npm cache clean -f" I am getting same issue. Please let me know if anyone aware about same.

Body:
I, personally, am a huge fan of nvm.
It makes node installation and versions manipulations so easy.

All install instructions can be found here.

I'll just give an example command of installing new nodejs version and start using it, so you understand how clear and easy it is:

nvm install 8.0
nvm use 8.0


问:
How to display data from database When Selecting Multiple option from Dropdown using PHP Mysqli
Script Page is working nicely. When I select the multiple options in next dashboard page, no records display. Please fix this problem. I think the selected value cannot recognize in dashboard page

Script.php

```<code><?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    <strong>Choose Script Name : </strong><select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>
</code>```

Dashboard.php

```<code><table border="1">
    <tr align="center">
        <th>Number </th>      <th>Script Name</th>    <th> Date</th>
    </tr>
    <?php
    include("connection.php");
    $select = $_POST['script'];
    $selects = "SELECT * FROM script_details where script_name='$select'";
    $result = $conn->query($selects);
    echo "<table>";
    while ($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"] . "</td><td>" . $row["script_name"] . "</td></tr>" . "</td><td>" . $row["date"] . "</td></tr>";
    }
    echo "</table>";
[This is script page Image. Selecting option from script_details database. Field name : script_name.][1]?>
</code>```

This is Dashboard page. when selecting script2, script3 option. Doesnot show record for selected items.

答:
Firstof all your code is sql vulnerable

In Scrip you didn't define values of options in <select> tag. define value first and for this you need to fetch is from database

Script.php

```<code><?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    <strong>Choose Script Name : </strong>
    <select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select id, script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            $id = $row['id'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>
</code>```

In dashboard do proper markup

Dashboard.php

```<code><table border="1">
    <tr align="center">
        <th>Number </th>      <th>Script Name</th>    <th> Date</th>
    </tr>
    <?php
    include("connection.php");
    $select = $_POST['script'];
    $ids = "'" . implode("','", $select) . "'";
    $selects = "SELECT * FROM script_details WHERE id IN ($ids)";
    $result = $conn->query($selects);
    while ($row = $result->fetch_assoc()) {
        echo "<tr>"
                . "<td>" . $row["id"] . "</td>"
                . "<td>" . $row["script_name"] . "</td>"
                . "<td>" . $row["date"] . "</td>"
            . "</tr>";
    }
    ?>
</table>
</code>```

Body:
Script Page is working nicely. When I select the multiple options in next dashboard page, no records display. Please fix this problem. I think the selected value cannot recognize in dashboard page

Script.php

<?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    Choose Script Name : <select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>

Dashboard.php

        Number 	      Script Name	     Date

    <?php
    include("connection.php");
    $select = $_POST['script'];
    $selects = "SELECT * FROM script_details where script_name='$select'";
    $result = $conn->query($selects);
    echo "
";
    while ($row = $result->fetch_assoc()) {
        echo "
" . $row["id"] . "	" . $row["script_name"] . "
" . "	" . $row["date"] . "
";
    }
    echo "
";
[This is script page Image. Selecting option from script_details database. Field name : script_name.][1]?>

This is Dashboard page. when selecting script2, script3 option. Doesnot show record for selected items.

Body:
Firstof all your code is sql vulnerable

In Scrip you didn't define values of options in <select> tag. define value first and for this you need to fetch is from database

Script.php

<?php include("connection.php") ?>
<form id="script" name="script" action="dashboard.php" method="post">
    <strong>Choose Script Name : </strong>
    <select name="script[]" id="select3" multiple=multiple style="margin: 20px;width:300px;">
        <?php
        $result = $conn->query("select id, script_name from script_details ORDER BY script_name");
        while ($row = $result->fetch_assoc()) {
            unset($script_name);
            $script_name = $row['script_name'];
            $id = $row['id'];
            echo '<option value="' . $id . '">' . $script_name . '</option>'; // Generated From database
        }
        ?>
    </select>
    <input type="submit" name="submit" id="button" value="View Dashboard" />
</form>

In dashboard do proper markup

Dashboard.php

<table border="1">
    <tr align="center">
        <th>Number </th>      <th>Script Name</th>    <th> Date</th>
    </tr>
    <?php
    include("connection.php");
    $select = $_POST['script'];
    $ids = "'" . implode("','", $select) . "'";
    $selects = "SELECT * FROM script_details WHERE id IN ($ids)";
    $result = $conn->query($selects);
    while ($row = $result->fetch_assoc()) {
        echo "<tr>"
                . "<td>" . $row["id"] . "</td>"
                . "<td>" . $row["script_name"] . "</td>"
                . "<td>" . $row["date"] . "</td>"
            . "</tr>";
    }
    ?>
</table>


问:
lua program shows current time
This is a piece of lua script that displays the time. I cannot separate the numbers ie: time.hour, ":",
to basically show hh:mm:ss

```<code>time = os.date("*t")
print(time.hour .. time.min .. time.sec)
</code>```

答:
For simply printing the time - extract what you want (the time) from the full date stamp string:

```<code>  > os.date():sub(9)
    12:30:39
</code>```

This works on my PC ;). There may be a different date stamp string in your OS.

G

Title: lua program shows current time

Body:
This is a piece of lua script that displays the time. I cannot separate the numbers ie: time.hour, ":",
to basically show hh:mm:ss

time = os.date("*t")
print(time.hour .. time.min .. time.sec)

Body:
For simply printing the time - extract what you want (the time) from the full date stamp string:

  > os.date():sub(9)
    12:30:39

This works on my PC ;). There may be a different date stamp string in your OS.

G


问:
WPF EventTriggers - Cannot convert string 'DragOver' in attribute 'RoutedEvent' to object of type 'System.Windows.RoutedEvent' in Visual Studio 2008
I have implemented some triggers for a WPF button as below:

```<code>   <ControlTemplate.Triggers>
        <EventTrigger RoutedEvent="DragOver">
            <BeginStoryboard Storyboard="{StaticResource swap}"/>
            <BeginStoryboard Storyboard="{StaticResource fadein}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="DragLeave">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Drop">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>
    </ControlTemplate.Triggers>
</code>```

This is working perfectly in Visual Studio 2015, but in Visual Studio 2008 it is thrown below error:

```<code>Cannot convert string 'DragOver' in attribute 'RoutedEvent' to object of type 'System.Windows.RoutedEvent'
</code>```

I have changed above routed events within event triggers to:

RoutedEvent="DragOver"  -> RoutedEvent="Mouse.DragOver"

RoutedEvent="DragLeave" -> RoutedEvent="Mouse.DragLeave"

RoutedEvent="Drop"      -> RoutedEvent="Mouse.Drop"

Mouse.DragOver, Mouse.DragLeave, Mouse.Drop are not recognized by xaml parser, it is highlighted.
Any ideas?

答:
I have found the solution. I need to preceed the routed events with Button and a period like below. Now is working:</p>

```<code>   <ControlTemplate.Triggers>
        <EventTrigger RoutedEvent="Button.DragOver">
            <BeginStoryboard Storyboard="{StaticResource swap}"/>
            <BeginStoryboard Storyboard="{StaticResource fadein}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Button.DragLeave">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Button.Drop">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>
    </ControlTemplate.Triggers>
</code>```

Body:
I have implemented some triggers for a WPF button as below:

   <ControlTemplate.Triggers>
        <EventTrigger RoutedEvent="DragOver">
            <BeginStoryboard Storyboard="{StaticResource swap}"/>
            <BeginStoryboard Storyboard="{StaticResource fadein}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="DragLeave">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Drop">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>
    </ControlTemplate.Triggers>

This is working perfectly in Visual Studio 2015, but in Visual Studio 2008 it is thrown below error:

Cannot convert string 'DragOver' in attribute 'RoutedEvent' to object of type 'System.Windows.RoutedEvent'

I have changed above routed events within event triggers to:

RoutedEvent="DragOver"  -> RoutedEvent="Mouse.DragOver"

RoutedEvent="DragLeave" -> RoutedEvent="Mouse.DragLeave"

RoutedEvent="Drop"      -> RoutedEvent="Mouse.Drop"

Mouse.DragOver, Mouse.DragLeave, Mouse.Drop are not recognized by xaml parser, it is highlighted.
Any ideas?

Body:
I have found the solution. I need to preceed the routed events with Button and a period like below. Now is working:

   <ControlTemplate.Triggers>
        <EventTrigger RoutedEvent="Button.DragOver">
            <BeginStoryboard Storyboard="{StaticResource swap}"/>
            <BeginStoryboard Storyboard="{StaticResource fadein}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Button.DragLeave">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>

        <EventTrigger RoutedEvent="Button.Drop">
            <BeginStoryboard Storyboard="{StaticResource reset}"/>
            <BeginStoryboard Storyboard="{StaticResource fadeout}"/>
        </EventTrigger>
    </ControlTemplate.Triggers>