text:
Q: Error: java.sql.SQLDataException,Invalid character string format for type int. I really don't understand? I have a problem with my project. When i browse http://localhost:8080/user/form to fill information user

Then submit form to save user and automaticlly direct http://localhost:8080/user/list to display list User, but occur following error:

Hibernate: insert into userdat (age, birthday, gender, password,
  username) value s (?, ?, ?, ?, ?) Mar 27, 2016 8:30:17 AM
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper$Standar
  dWarningHandler logWarning WARN: SQL Warning Code: 10000, SQLState:
  01J01 Mar 27, 2016 8:30:17 AM
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper$Standar
  dWarningHandler logWarning WARN: Database 'D:\PROJECTSPRING\userdb'
  not created, connection made to existin g database instead. Mar 27,
  2016 8:30:17 AM
  org.hibernate.hql.internal.QueryTranslatorFactoryInitiat or
  initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory
  Hibernate: select user0_.username as username1_0_, user0_.age as
  age2_0_, user0_ .birthday as birthday3_0_, user0_.gender as
  gender4_0_, user0_.password as passw ord5_0_ from userdat user0_ Mar
  27, 2016 8:30:17 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper
  logExce ptions WARN: SQL Error: 20000, SQLState: 22018 Mar 27, 2016
  8:30:17 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExce
  ptions ERROR: Invalid character string format for type int. [WARNING]
  org.springframework.web.util.NestedServletException: Request
  processing failed; nested exception is
  org.hibernate.exception.DataException: could not execute que ry
Caused by: org.hibernate.exception.DataException: could not execute
  query
          at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQL
  ExceptionTypeDelegate.java:52)
          at org.hibernate.exception.internal.StandardSQLExceptionConverter.conver
  t(StandardSQLExceptionConverter.java:42)
          at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlException
  Helper.java:111)
Caused by: java.sql.SQLDataException: Invalid character string format
  for type i nt.
          at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknow
  n Source)
          at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source
  )
          at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException
  (Unknown Source)

Here file UserDaoImpl.java
@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    public LocalSessionFactoryBean sessionFactory;

    @Override
    public void save(User user) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getObject().openSession();
        session.save(user);
        session.flush();
        session.close();

    }

    @Override
    public void update(User user) {
        // TODO Auto-generated method stub

    }

    @Override
    public List<User> listUsers() {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getObject().openSession();
        Query query = session.createQuery("from User");
        return (List<User>)query.list();
    }

Here file User.java
@Entity
@Table(name = "userdat",uniqueConstraints={@UniqueConstraint(columnNames="username")})
public class User {
    @Column(name = "gender", nullable = false)

    public Gender getGender() {
        return gender;
    }
    public void setGender(Gender gender) {
        this.gender = gender;
    }
    @Id
    @Column(name = "username", unique = true, nullable = false)
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    @Column(name = "password", nullable = false)
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    @Column(name = "birthday", nullable = false)
    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }
    @Column(name="age", nullable = false)
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    private String userName;
    private String passWord;
    private Date birthDay;
    private Integer age;
    private Gender gender;

}

Here file Gender.java
public enum Gender {
    MALE("Male"),
    FEMALE("Female"),
    OTHER("Other");
    private String name;

    private Gender(String name) {
        this.name = name;
    }

    public String getGender(){
        return this.name;
    }
        }

Here Create Table in DB
public void createTable() throws SQLException{
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            Connection connection = DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/dbuser;create=true");
            createTableNotExist(connection,"userdat", "create table userdat"
                    + "(username varchar(1000) primary key,"
                    + "password varchar(1000),birthday date,"
                    + "age integer,gender varchar(100))");
//          createTableNotExist(connection,"subject","create table subject"
//                  + "(id bigint primary key generated always as identity(start with 1,increment by 1),"
//                  + "title varchar(1000),student integer,score integer)" );
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

A: Enums persist by ordinal number if they do not annotated with @Enumerated. In this case  hibernate expects int but gets varchar(100). Code below solves the problem.
@Column(name = "gender", nullable = false)
@Enumerated(EnumType.STRING)

A: I think it is saying that it wants to store Gender as in Integer since it is an enum type. Change the database creation to:
gender integer

A: I'm publishing this answer because this error can be also caused by using column names in the CSV file.
Here is the thing: I extracted some data from a DB in CSV format using an automation tool. Then I tried to import data to Apache Derby without any success.
After a couple of hours finally I figured out that column names should have been removed from the file.
It's a very simple solution but sometimes we just want run into the process ASAP and forget the details about process configuration.
I hope this post help others.
Cheers!


text:
Q: Как восстановить загрузку windows 10 после неудачного запуска sysprep Для переноса папки с данными профилей пользователей была выполнена команда
%windir%\system32\sysprep\sysprep.exe /oobe /reboot /unattend:c:\relocate.xml

Содержимое файла relocate.xml
<?xml version="1.0" encoding="utf-8"?>

<unattend xmlns="urn:schemas-microsoft-com:unattend">

<settings pass="oobeSystem">

<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<FolderLocations>

<ProfilesDirectory>E:\Users</ProfilesDirectory>

</FolderLocations>

</component>

</settings>

</unattend>

После этих действий загрузка windows останавливается на сообщении об ошибке, после нажатия кнопки OK, компьютер перезагружается и сообщение выводится снова.
Не удалось завершить процесс установки. Чтобы установить Windows, перезапустите программу установки.

Подскажите, пожалуйста, как можно решить эту проблему?

redpajama_set_name: RedPajamaStackExchange


text:
Q: prove this equality
First, I try to use the Taylor series but it doesn't work well.
And someone said I can use fundamental theorem of calculus but I don't see it.
can anyone give me a good hit?
thanks

A: Here is a start:
Let
$f_n( x)
=D_n(x^{n-1}e^{1/x})
$,
where $D_n$
is the $n^{th}$
derivative.
By Leibnitz's formula
$D_n(a(x)b(x))
=\sum_{k=0}^n \binom{n}{ k} D_k(a(x))D_{n-k}(b(x))
$.
(This is readily proved by induction
using the regular product rule
for derivatives.)
Then get the appropriate derivatives.
Note that many of the derivatives
may be zero,
which might simplify things.


text:
Q: Alterações no log de erro Por padrão quando tem algum erro no meu PHP, meu servidor cria um arquivo de log, com as seguintes informações:

[19-Apr-2017 16:20:12 America/Fortaleza] PHP Notice:  Trying to get property of non-object in /var/www/Produto.php on line 131

Ele me informa qual o arquivo contém o erro, e qual a linha.
Porém queria saber se existe alguma formar de salvar a linha no log, ou seja, salvar a linha inteira que contém o erro.

A: Pata atingires esse objectivo podes fazer uso da função set_error_handler em junção com a função debug_backtrace
Fiz uma pesquisa e encontrei uma solução no stackoverflow vizinho, segue o código:
<?php
function process_error_backtrace($errno, $errstr, $errfile, $errline, $errcontext) {
    if(!(error_reporting() & $errno))
        return;
    switch($errno) {
    case E_WARNING      :
    case E_USER_WARNING :
    case E_STRICT       :
    case E_NOTICE       :
    case E_USER_NOTICE  :
        $type = 'warning';
        $fatal = false;
        break;
    default             :
        $type = 'fatal error';
        $fatal = true;
        break;
    }
    $trace = array_reverse(debug_backtrace());
    array_pop($trace);
    if(php_sapi_name() == 'cli') {
        echo 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n";
        foreach($trace as $item)
            echo '  ' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()' . "\n";
    } else {
        echo '
' . "\n";
        echo '  Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n";
        echo '
' . "\n";
        foreach($trace as $item)
            echo '
' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()
' . "\n";
        echo '
' . "\n";
        echo '
' . "\n";
    }
    if(ini_get('log_errors')) {
        $items = array();
        foreach($trace as $item)
            $items[] = (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()';
        $message = 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ': ' . join(' | ', $items);
        error_log($message);
    }
    if($fatal)
        exit(1);
}

set_error_handler('process_error_backtrace');
?>


text:
Q: Background process sending SMS Folks,
I am working on a project where the requirement is the app launch will not display any screen but will launch a background process that will send out SMS. I have just started on android so I need some pointer on
a) How to launch an app without screen but only with a background process?
b) From that background process how to spawn a thread (I am assuming we need to spawn a thread here) that will send out SMS automatically?
Thanks in advance!

A: use this code in onCreate() of your Activity and write logic of sms in Service
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent=new Intent(this,YourService.class);
    startService(intent);
    finish();
}

Send SMS in Background

A: You can call finish() immediately right after spawning a background process. You can use IntentService as it automatically spawns its own worker thread to handle every intent. For example:
public class MyIntentService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("phoneNumber", null, "your message here", null, null);
    }
}

so in the onCreate() of your Activity, you can just simply do something like this:
Intent intent = new Intent(this, MyIntentService.class);
startService(intent);

Don't forget to add the android.permission.SEND_SMS permission in your manifest.

A: You can schedule message sending from the IntentService through AlarmManager class.


text:
Q: Issue with using JSON.stringify after using jQuery.map I am writing a bookmarklet (that will eventually be a plugin) to scrape web pages for list items in jQuery under a specified div. I'm having an issue with using JSON.stringify
The following code allows me to convert each individual item to JSON, but has issues when using join to concatenate each string.
var dMap = $("div").filter($("#<div-id>")).find("li").map(function() {
    var iObject = {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
    return JSON.stringify(iObject);
});
console.log(dMap);

This second snippet of code creates each object in the array correctly, but the resulting array doesn't log the resulting JSON.
var dMap = $("div").filter($("#,div-id.")).find("li").map(function() {
    return {
        id: $(this).data('id'),
        text: $(this).text(),
        list_name: $(this).closest('div').attr('id')
    };
});
console.log(dMap);
var json = JSON.stringify(dMap);
console.log(json);

Any ideas?

A: According to the documentation for .map:

As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.

Have you tried:
var json = JSON.stringify(dMap.get());


text:
Q: How to keep BSD sockets connected in ios 5.0+ after iphone gets locked My webserver's sockets get disconnected on iphone lock. I am using system calls to handle socket functionality in my app. Is there a way in which I can enable voip flags using system calls so that stay active after iphone gets locked or can I implement a voip socket flag setting functionality as it is done in Objective C.
This problem I understand is seen in ios 5.0+ versions. There is not much help around for this in web. Please let me know if some one has successfully got around this problem.


text:
Q: How to set Android DataBinding in nested layouts I was just reading about data binding feature in android. I was trying to bind a view from a nested layout. My activity is android's default template of DrawerMenuActivity and it has content_my_activity layout nested inside activity_my_activity layout.
I have 3 auto generated binding classes. MyActivityBinding, AppBarMyActivityBinding and ContentMyActivityBinding.
I tried initialising all 3 class as below:
MyActivity.java
MyActivityBinding activityBinding;
AppBarMyActivityBinding appBarBinding;
ContentMyActivityBinding contentBinding;

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    activityBinding = DataBindingUtils.setContentView(this,
                               R.layout.activity_my_activity);
    appBarBinding = DataBindingUtils.setContentView(this,
                               R.layout.app_bar_my_activity);
    contentBinding = DataBindingUtils.setContentView(this,
                               R.layout.content_my_activity);

    setName();
}

private void setName(){
    contentBinding.setFirstName("Omkar");
}

But it throws RuntimeException as below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 18305
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.userInterface.activity.MyActivity}: android.view.InflateException: Binary XML file line #35: Binary XML file line #27: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
 Caused by: android.view.InflateException: Binary XML file line #35: Binary XML file line #27: Error inflating class fragment
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at android.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:276)
    at com.example.userInterface.activity.MyActivity.onCreate(MyActivity.java:88)
    at android.app.Activity.performCreate(Activity.java:6259)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
 Caused by: android.view.InflateException: Binary XML file line #27: Error inflating class fragment
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at android.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:276)
    at com.example.userInterface.activity.MyActivity.onCreate(MyActivity.java:88)
    at android.app.Activity.performCreate(Activity.java:6259)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
 Caused by: java.lang.IllegalArgumentException: Binary XML file line #27: Duplicate id 0x7f0e0081, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
    at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2416)
    at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
    at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
    at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:971)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:831)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at android.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:276)
    at com.example.userInterface.activity.MyActivity.onCreate(MyActivity.java:88)
    at android.app.Activity.performCreate(Activity.java:6259)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

How do I bind view from content_my_activity in MyActivity.java class, any help is appreciated.
Thanks.

A: DataBindingUtils.setContentView() does exactly how it is named: It sets the current view to the given parameter. I don't think you want your AppBar as the whole view, or do you?
Nevertheless, I assume that you include your layouts in your layout_activity_main.xml. George Mount has written a whole blog post about this feature. The code examples are from this post.
The first example would be your layout_activity_main.xml (Or however you have named it), where you include your AppBar, your Content and so on.
hello_world.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        <TextView
                android:id="@+id/hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        <include
                android:id="@+id/world1"
                layout="@layout/included_layout"/>
        <include
                android:id="@+id/world2"
                layout="@layout/included_layout"/>
    </LinearLayout>
</layout>

included_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/world"/>
</layout>

Now that the used layouts are clear, you'll need to jump into your ActivityMain, initialize the DataBinding and access your fields:
//This works if you have used a variable in your <data> tag and you have built your project afterwards, if you don't have an activity
HelloWorldBinding binding = HelloWorldBinding.inflate(getLayoutInflater());

 //if you have an activity, you can use setContentView from the DataBindingUtils. Don't forget to delete the generic setContentView
HelloWorldBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_my_activity);

//Once you have accomplished the above, you can access your data-bound fields like this:
binding.hello.setText("Hello");
binding.world1.world.setText("First World");
binding.world2.world.setText("Second World");

It is important to set Ids to your <include> tags to access them correctly i your Activity.

A: One can pass the objects in XML ... the xmlns:bind namespace is required (similar to xmlns:app).
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto">

   <data>
       <variable name="user" type="com.example.User"/>
   </data>

   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <include
           layout="@layout/name"
           bind:user="@{user}"/>

       <include
           layout="@layout/contact"
           bind:user="@{user}"/>

   </LinearLayout>

</layout>

source of the example: Layouts and binding expressions.


text:
Q: How to make Google Mobile Vision to continuously trying to auto focus? I'm using ML Kit. I'm trying to achieve the behavior where my barcode scanner Android app keeps trying to focus the camera while I move when trying to find a barcode. You know, the typical "clear-blur" behavior that we get when trying to use our phone camera to take a photo.
What are the settings I should turn on?


text:
Q: Report viewer does not load, showing blank space - running local RDLC files I got a problem with reporting services, running local rdlc files on the 2005 version.
I have in the HTML a report viewer set to run locally as follows :
 <rsweb:ReportViewer ID="ReportingServicesReportViewer" runat="server" Height="100%"
            ProcessingMode="Local" ShowParameterPrompts="False" Width="100%">
        </rsweb:ReportViewer>

In the code
// create SqlConnection
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        myCommand.Connection = myConnection;
        SqlDataAdapter da = new SqlDataAdapter(myCommand);

        //get the data
        DataSet data = new DataSet();
        da.Fill(data);

        if (data != null && data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
        {
            ReportingServicesReportViewer.Visible = true;
            ltrStatus.Text = string.Empty;

            //provide local report information to viewer
            ReportingServicesReportViewer.LocalReport.ReportPath = Server.MapPath(Report.RDLCPath);

            //bind the report attributes and data to the reportviewer
            ReportDataSource rds = new ReportDataSource("DataSet1", data.Tables[0]);
            ReportingServicesReportViewer.LocalReport.DataSources.Clear();
            ReportingServicesReportViewer.LocalReport.DataSources.Add(rds);
            ReportingServicesReportViewer.LocalReport.Refresh();
        }
        else
        {
            ReportingServicesReportViewer.Visible = false;
            ltrStatus.Text = "No data to display.";
        }

When the method to populate the report viewer with the results of the report is executed, nothing comes up as if the report viewer is not even there.
What I did to trouble shoot till now:

*

*Checked the event viewer for errors and this is the only thing related
which I get,   [Domain]\sp_dbadmin    Reason:
Failed to open the explicitly specified database. . However,
my user which I am connecting is a sysadmin. I have checked that and
am sure because I checked the sys.server_role_members

*I tried impersonating the logged in user, to no avail

*I created a specific user with sysadmin rights, and gave all access rights both from IIS and also on the sql server 2008.

Has anyone encountered a problem similar to this, any ideas?

A: I had same problem with VS2012, report shows loading image and then after loading is complete, report is blank. Data exists but not rendered.
Solution : Simply change Report AsyncRendering to False and report works fine again.

A: Try using a simple report , sometimes reportviewer throws exception caused by invalid RDLC and shows an empty report.
Try also to debug the project and look at the output window in Visual Studio: you will see the warning raised bu the RDL engine, it could be useful to investigate the reason of the error.

A: I was getting the same problem when I add parameter in rdlc but not assigning it.
I solved by adding this code.
Dim p_Date As Microsoft.Reporting.WebForms.ReportParameter
p_Date = New Microsoft.Reporting.WebForms.ReportParameter("DATE", txtDate.Text)
    Me.ReportViewer1.LocalReport.SetParameters(New Microsoft.Reporting.WebForms.ReportParameter() {p_Date})
    ReportViewer1.LocalReport.Refresh()

A: In my case, ReportViewer control does not provide error messages (EventViewer nor ReportViewer control body), just blank page. I think this make hard find and fix the issue. Yoel Halb's answer was my key!
A property called IsReadyForRendering was False. In the BOL refers to parameters topic.
I could inspect every value of the whole parameters with the code (you can execute it from immediate window)
   var parameters = ReportViewer1.LocalReport.GetParameters()

You will find the problematic parameter when you look the property State with the value "MissingValidValue"
Hope this helps !

A: I had the same problem and in my case it turned out that I have supplied the a dataset that was not the actually the object type that the report expected.
In my situation the report expected a business object, but I have supplied a SQL Data source.
I also encountered this same problem when there was parameters on the report which were not allowed to be null or blank but the parameter values was not supplied.
Also note that in order to set a data source in code it has to be done in the onload event and not in the page_load event.

A: This one took some time to figure out, so hopefully these checks will save you some time:
1) Verify the web.config
<system.web>
  <httpHandlers>
    <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" />
  </httpHandlers>

  <buildProviders>
    <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 </buildProviders>
</system.web>

<system.webServer>
  <handlers>
    <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
  </handlers>
<system.webServer>

2) try the report viewer control directly in design view before moving any configuration into code
Hard-Coded Report Viewer Control
3) Verify that the script manager is on the page before the report viewer
4) Ensure that the report runs outside of design viewer, either locally or on the SSRS server
5) BE SURE THAT REPORT HAS DEFAULT VALUES FOR ALL PARAMETERS!  Reports that require parameters and don't have default values show up blank.

A: In my case the culprit was having parameters with the Allow null value = false (unchecked)... Don't asked me why.

A: after changing size for paper or reportviewer won't work you can try my solution by adding more delay for

WaitControlDisplayAfter

sometimes your data too large to process for async

A: Had the same problem. Took a while to figure out for me but it turns out I accidentally new'ed the reportViewer control myself so I lost what the Visual Studio Designer had created for me when I designed the form and that is why the reportviewer control kept coming up blank - I never set any properties on the Visual Studio Designer's ReportViewer object.
Silly mistake but took quite some time to figure out.

A: I've spent many days to figure out similar issue. Maybe this could help someone. I've read almost all threads on stackoverflow, but reading comments here made me try this out. In my case first two rows (parameters row and row with option to hide parameters) were  shown, but rows that contain management buttons and the report itself were empty. Clicking View report resulted in no action.

What I've done was loading the report that had parameters without providing them - I wanted user to fill them - on Page_Load.
protected void Page_Load( object sender, EventArgs e )
{
    this.LoadReport();
}

private void LoadReport()
{
        // retrieve path param from "Reports/{path}" URL
        string reportPath = Request.QueryString[ "path" ] as string;
        string reportServerUrl = System.Configuration.ConfigurationManager.AppSettings[ "ReportServerUrl" ];

        this.MainReport.ProcessingMode = ProcessingMode.Remote;
        this.MainReport.ServerReport.ReportServerUrl = new Uri( reportServerUrl );
        this.MainReport.ServerReport.ReportPath = reportPath;
        this.MainReport.ServerReport.Refresh();
}

After changing Page_Load code to the given below everything works fine.
protected void Page_Load( object sender, EventArgs e )
{
    if ( !this.IsPostBack )
        this.LoadReport();
}


text:
Q: a Unhandled exception :Access violation reading location 0x00000004 I get this error in the debugging mode when i first encounter the marked line in the code below
#include<fstream>
#include<iostream>
#include<math.h>
#include<string>

using namespace std;

int main()
{int t,i,j,k,n,g[100],w[100],opp[100];
float rpi[100],wp[100],owp[100],oowp[100];
char s[100][100];
ifstream ip; ip.open("A-small-practice.in"); ofstream op; op.open("A_out.in");
ip>>t;
for(i=0;i<t;i++)
  { ip>>n;
    memset(g,0,sizeof(g));
    memset(w,0,sizeof(w));
    memset(op,0,sizeof(op));
    memset(rpi,0,sizeof(rpi));
    memset(wp,0,sizeof(wp));
    memset(owp,0,sizeof(owp));
    memset(oowp,0,sizeof(oowp));
    memset(s,'.',sizeof(s));

    for(j=0;j<n;j++)
      {for(k=0;k<n;k++)
        {ip>>s[j][k]; //<--------------------the error occurs here
        if(s[j][k]=='0')
          g[j]++;
    if(s[j][k]=='1')
      {g[j]++;w[j]++;}
        }
      wp[j]=w[j]/g[j];
     }

    for(j=0;j<n;j++)
      {for(k=0;k<n;k++)
       if(j!=k && s[k][j]!='.')
           {owp[j]+=(wp[k]*g[k]-s[k][j])/(g[k]-1);
           opp[j]++;
           }
       owp[j]/=opp[j];
      }

    for(j=0;j<n;j++)
      {for(k=0;k<n;k++)
        {if(j!=k && s[k][j]!='.')
         oowp[j]+=owp[k];
        }
       oowp[j]/=opp[j];
      }

   op<<"Case #"<<i+1<<": \n";
    for(j=0;j<n;j++)
    {rpi[j]=(0.25*wp[j]) + (0.5*owp[j]) +(0.25*oowp[j]);
    op<<rpi[j]<<"\n";
     }
 }
return 0;
}

the debugger breaks at this code segment when stepped in. The loops and logic the value size is all correct i don't know where the overflow is ocurring..is there any other cause for this?
    class _Sentry_base
    {   // stores thread lock and reference to input stream
public:
    __CLR_OR_THIS_CALL _Sentry_base(_Myt& _Istr)
        : _Myistr(_Istr)
        {   // lock the stream buffer, if there
        if (_Myistr.rdbuf() != 0)//<-------------break points here
            _Myistr.rdbuf()->_Lock();
        }

A: You don't need to use memset for the 1D arrays.  For example
 int g[100] = {0};

will work.
For the 2D array, loop through using a for loop and set each element to '.', or stick with the memset for that step.
In terms of your actual problem, you may need to use ip.get() to read character by character instead.


text:
Q: Bessel Function to Exponential Function Solving this equation : $ y'' + (1/x)y' - (k^2 - (m^2/x^2) )y=0$
gives $y(x) = J_m (-ikx) + Y_m (-ikx)$ which is further written as
$y(x) = \frac{1}{\sqrt{x}}\left(\exp(-kx) + \exp(kx) \right)$
Here $J_m, Y_m$ are Bessel functions of first and second kind respectively & $i = \sqrt{-1}$.
Please explain how Bessel functions are converted to exponential form.
Thanks in advance.

A: Some notes:

The differential equation
\begin{align}
\left[ x^{2} D_{x}^{2} + x D_{x} - ((kx)^{2} - m^{2}) \right] y =0
\end{align}
has the solution
\begin{align}
y(x) = A J_{im}(-ikx) + B Y_{im}(-i kx)
\end{align}
where $J_{n}(x)$ and $Y_{n}(x)$ are Bessel functions. Notice that these functions are of order $i m$ which are complex in value.
For the case of $m$ being of fractional order the differential equation
\begin{align}
\left[ x^{2} D_{x}^{2} + 2 x D_{x} + (x^{2} - n(n+1)) \right] y = 0
\end{align}
has the solution
\begin{align}
y(x) = A j_{n}(x) + B \mathcal{y}_{n}(x).
\end{align}
Further information on the Bessel functions can be obtained, often the starting point these days, from Bessel Functions (Wiki).

As given by the question the solution is
\begin{align}
y(x) = \frac{2 \, \cosh(kx)}{\sqrt{x}}.
\end{align}
This leads to the differential equation
\begin{align}
x^{2} y'' + x y' - ((kx)^{2} + \frac{1}{4})y = o
\end{align}
which is a modified Bessel function of fractional order and has the form
\begin{align}
y(x) = A I_{-1/2}(kx) + B I_{1/2}(kx) = A \sqrt{\frac{2}{k\pi x}} \cosh(kx) + B \sqrt{\frac{2}{k\pi x}} \sinh(kx).
\end{align}
From this it is seen that $B=0$ and $A = \sqrt{2 k \pi}$.

Another example of similarity:
Consider the solution
\begin{align}
y(x) = \frac{2}{x^{5}} \, \cosh(kx)
\end{align}
satisfies the differential equation
\begin{align}
x^{2} y'' + 10 x y' -((kx)^{2} - 20)y = 0.
\end{align}
Making the substitution
\begin{align}
y(x) = \frac{1}{x^{4}} \, g(x)
\end{align}
it is seen that $g(x)$ satisfies $x^{2} g'' + 2 x g' -(kx)^{2} g = 0$ which has the solution
\begin{align}
g(x) = A j_{0}(-ikx) + B \mathcal{y}_{0}(-ikx) = \frac{1}{x} (A_{1} \sinh(kx) + B_{1} \cosh(kx) ).
\end{align}
This leads to
\begin{align}
y(x) = \frac{1}{x^{5}} \left[ A_{1} \sinh(kx) + B_{1} \cosh(kx) \right].
\end{align}
Now, letting $A_{1} = 0$ and $B_{1} = 2$ it is then seen that
\begin{align}
y(x) = \frac{C}{x^{4}} \, \mathcal{y}_{0}(-ikx).
\end{align}


text:
Q: Bind SIGTERM to a member function I would like to create a simple class to signals handling (just for study) with std::bind. However, I could not compile this code:
#include <iostream>
#include <functional>
#include <csignal>
using namespace std;

class SignalHandler
{
public:

    void handler(int value)
    {
        cout << value << endl;
    }

    SignalHandler()
    {
        auto callback = std::bind(&SignalHandler::handler, this, std::placeholders::_1);

        sighandler_t ret = std::signal(SIGTERM, callback);
        if (SIG_ERR == ret) {
            throw;
        }
    }

};

int main() {

    SignalHandler handler;

    raise(SIGTERM);

    return 0;
}

(GCC) Compiler exit:
prog.cpp: In constructor 'SignalHandler::SignalHandler()':
prog.cpp:21:51: error: cannot convert 'std::_Bind(SignalHandler*, std::_Placeholder<1>)>' to '__sighandler_t {aka void ()(int)}' for argument '2' to 'void ( signal(int, __sighandler_t))(int)'
   sighandler_t ret = std::signal(SIGTERM, callback);

A: You can use static methods to handle SIGTERM, et al.  I've done that before.  static was the key to get signatures to match.


text:
Q: Make animation slower (jQuery) I'm trying to make animation of the block by changing its position.
Like, move the block from the left to the middle by animation of the css left.
The problem is, animation process happens with the same speed from the beginning to the end.
I want to make animation slower at the end, it should slow down when it comes to the finish point.
How can I do this? I've read about easing plugin, but don't know which effect should I use, which is the wanted one.

A: You want an ease-out effect. Here are some demos:
http://jquery-ui.googlecode.com/svn/tags/1.6rc6/demos/effects_easings/default.html
EDIT:
Here's a more "official" demo page:
http://jqueryui.com/demos/effect/easing.html

A: This is an awesome reference for have the easing effects behave: http://hosted.zeh.com.br/tweener/docs/en-us/misc/transitions.html. Yes I know this is for the actionscript library Tweener but all of the easing names are the same(For the most part).
You're looking for easeOut or easeOutQuad or easeOutCubic. (They are in order of how quickly they will start slowing down)

A: Try somthing like this:
$('#yourBlock').animate({
    left: newValue
}, 500, 'easeOut')

A: $(document).ready(function () {
    $("#imgAnimate").click(function () {
        $("#imgAnimate").animate({ "opacity": 0.0, left: '800px' }, 2500);
    });
});


text:
Q: GAN LOSS of Generator and Discriminator Lowest at First Epoch - Is that normal? I am trying to train a simple GAN and I noticed that the loss for the generator and discriminator is the lowest in the first epoch? How can that be? Did I miss something?
Below you find the plot of the Loss over the iterations:
Here is the code I was using:
I adapted the code according to your suggest @emrejik. It doesn't seem to have changed much though. I couldn't work with torch.ones() at the suggested lines as I was receiving this error message: "argument size (position 1) must be tuple of ints, not Tensor". Any idea how come?
I ran through 10 epochs and this came out now:
from glob import glob
import sys
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import torchvision.utils as vutils
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchinfo import summary
from mpl_toolkits.axes_grid1 import ImageGrid
from skimage import io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from tqdm import trange

manual_seed = 999

path = 'Punks'
image_paths = glob(path + '/*.png')
img_size = 28
batch_size = 32

device = 'cuda' if torch.cuda.is_available() else 'cpu'

transform = transforms.Compose(
    [
        transforms.ToPILImage(),
        transforms.Resize(img_size),
        transforms.CenterCrop(img_size),
        transforms.ToTensor(),
        transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
    ]
)

class ImageDataset(Dataset):
    def __init__(self, paths, transform):
        self.paths = paths
        self.transform = transform

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, index):
        image_path = self.paths[index]
        image = io.imread(image_path)

        if self.transform:
            image_tensor = self.transform(image)

        return image_tensor

if __name__ == '__main__':

    dataset = ImageDataset(image_paths, transform)

    train_loader = DataLoader(
        dataset, batch_size=batch_size, num_workers=2, shuffle=True)

    class Discriminator(nn.Module):
        def __init__(self):
            super().__init__()
            self.model = nn.Sequential(
                nn.Linear(784*3, 2048),
                nn.ReLU(),
                nn.Dropout(0.3),
                nn.Linear(2048, 1024),
                nn.ReLU(),
                nn.Dropout(0.3),
                nn.Linear(1024, 512),
                nn.ReLU(),
                nn.Dropout(0.3),
                nn.Linear(512, 256),
                nn.ReLU(),
                nn.Dropout(0.3),
                nn.Linear(256, 1),
                nn.Sigmoid(),
            )

        def forward(self, x):
            x = x.view(x.size(0), 784*3)
            output = self.model(x)
            return output

    discriminator = Discriminator().to(device=device)

    class Generator(nn.Module):
        def __init__(self):
            super().__init__()
            self.model = nn.Sequential(
                nn.Linear(100, 256),
                nn.ReLU(),
                nn.Linear(256, 512),
                nn.ReLU(),
                nn.Linear(512, 1024),
                nn.ReLU(),
                nn.Linear(1024, 2048),
                nn.ReLU(),
                nn.Linear(2048, 784*3),
                nn.Tanh(),
            )

        def forward(self, x):
            output = self.model(x)
            output = output.view(x.size(0), 3, 28, 28)
            return output

    generator = Generator().to(device=device)

    lr = 0.0001
    num_epochs = 10
    loss_function = nn.BCELoss()
    #noise = torch.randn(batch_size, 100, device=device)

    optimizer_discriminator = torch.optim.Adam(
        discriminator.parameters(), lr=lr)
    optimizer_generator = torch.optim.Adam(generator.parameters(), lr=lr)

    model = Discriminator().to(device=device)
    summary(model, input_size=(batch_size, 3, 28, 28))

    model = Generator().to(device=device)
    summary(model, input_size=(batch_size, 100))

    image_list = []
    Dis_losses = []
    Gen_losses = []
    iters = 0
    epochs = 0

    for epoch in trange((num_epochs), bar_format='{desc:<5.5}{percentage:3.0f}%|{bar:120}{r_bar}\n'):
        for n, real_samples in enumerate(train_loader):

            batch_size = len(real_samples)
            real_samples = real_samples.to(device=device)
            real_samples_labels = torch.ones((batch_size, 1)).to(device=device)

            latent_space_samples = torch.randn(
                (batch_size, 100)).to(device=device)

            fake_samples = generator(latent_space_samples)
            fake_samples_labels = torch.zeros(
                (batch_size, 1)).to(device=device)

            discriminator.zero_grad()

            output_discriminator_real = discriminator(real_samples)
            loss_discriminator_real = loss_function(
                output_discriminator_real, real_samples_labels)

            output_discriminator_fake = discriminator(fake_samples)
            loss_discriminator_fake = loss_function(
                output_discriminator_fake, fake_samples_labels)

            loss_discriminator = (
                loss_discriminator_real + loss_discriminator_fake)/2

            loss_discriminator.backward()
            optimizer_discriminator.step()

            latent_space_samples = torch.randn(
                (batch_size, 100)).to(device=device)

            generator.zero_grad()

            fake_samples = generator(latent_space_samples)
            output_discriminator_fake = discriminator(fake_samples)
            loss_generator = loss_function(
                output_discriminator_fake, real_samples_labels)

            loss_generator.backward()
            optimizer_generator.step()

            image_list.append(vutils.make_grid(
                fake_samples_labels, padding=2, normalize=True))
            Dis_losses.append(loss_discriminator.item())
            Gen_losses.append(loss_generator.item())
            iters += 1
            epochs += 1

            if n == batch_size - 1:
                print(f"Epoch: {epoch} Loss D.: {loss_discriminator}")
                print(f"Epoch: {epoch} Loss G.: {loss_generator}")

    latent_space_samples = torch.randn((batch_size, 100)).to(device=device)

    plt.figure(figsize=(10, 5))
    plt.title("Generator and Discriminator Loss During Training")
    plt.plot(Dis_losses, label="D")
    plt.plot(Gen_losses, label="G")
    plt.xlabel("iterations")
    plt.ylabel("Loss")
    plt.legend()
    plt.show()

A: I didn't see the proper use of loss function for the discriminator. You should give real samples and generated samples separately to the discriminator. I think  you should change your code to a form like this:
fake = generator(noise)
disc_real = disc(real)
loss_disc_real = loss_func(disc_real, torch.ones_like(disc_real))
disc_fake = disc(fake)
loss_disc_fake = loss_func(disc_fake,torch.zeros_like(disc_fake))
loss_disc = (loss_disc_real+loss_disc_fake)/2
....

loss_generator = loss_func(disc_fake,torch.ones_like(disc_fake))
...

plot loss_disc and loss_generator, this should be work


text:
Q: Insert custom div between posts I'm using twenty twelve and I need to insert a div between the posts. I'm not sure how to stop the loop, insert the div, and then restart the loop.
Can anyone shed some light on this? Thanks.

A: You can check your position within the loop using the current_post var of the $wp_query object, and insert markup at a specific spot or at some interval. A simple example:
while( have_posts() ):
    the_post();

    the_title();
    the_excerpt();

    // if current_post is 1, insert the div
    // note that current_post starts at 0,
    // so this will be after the second post's content

    if( 1 == $wp_query->current_post ):
        echo '
My div!
';
    endif;

endwhile;

A: You can add the
 right after the post is output by modifying index.php of the theme. Take a look at lines 22-25 (http://themes.trac.wordpress.org/browser/twenty-twelve/0.9/index.php), you'd place it right after line 24, which is responsible for pulling the right content type template in and displaying it.
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

If you wanted to get picky about which types of posts (regular posts, image posts, etc.) it comes after, then you could edit the content-*.php files themselves, and place it at the end of those templates.


text:
Q: Is there an equivalent to super.super()? I know that you can use super.super.methodName() to invoke the grandparent's version of a method, but is there any way to directly invoke the grandparent class's constructor in a chained constructor call?
(Simplified) Example:
 class A {
    public A(){}
    public A(int i, boolean b) {
        /*...*/
    }
}

class B extends A {
    public B(){}
    public B(int i) {
        super(i, true);
    }

}

class C extends B {
    public C(int i)
        {
        super.super(i,false);  //This is not allowed, but you
            //can see what I'm trying to do (call A(i,false).)
            //this=new A(i,false); also doesn't work b/c this can't be LHS
            //of assignment
        }
}

..or is this disallowed, and did I just demonstrate the reasoning for doing so in attempting to make a super.superclass(grandparent) constructor call not possible in the (parent)superclass?

A: No, and this is by design. The intermediate class intentionally hides some of the functionality of its superclass, and the constructor is one area where it does so.
Think about it like this. Suppose you have three classes: Animal, Dog, Terrier.
Dog extends Animal

Terrier extends Dog

In your Terrier constructor, it's quite appropriate for it to call the Dog constructor. What you're doing is to say that when a Terrier is created it should do its doggy-related thing, and then afterwards do anything terrier-specific.
But what you're wanting to do is to get the Terrier constructor to invoke the Animal constructor. This is essentially to say that the Terrier should set itself up without regard for the fact that it's a dog. Anything might now happen: the code to initialize the fields needed for the .woof() method won't get dealt with, for instance. Now your Terrier is in a terrible mess when it tries to woof later.
If you're wanting your Terrier to do some Animal setup but avoid the Dog setup, that suggests that your class hierarchy is all wrong: your Terrier probably isn't a Dog at all.

A: No. But you can get around it.
You can call super.foo(), then in your parent foo method, you call super.foo()
For instance
class A {

  public void foo() {
    System.out.println("I want this");
  }
}

class B extends A {
  public void foo() {
    super.foo();
  }
}

class C extends B {
   @Test
   public void callFooTest() {
       C c = new C();
       c.foo();
       //call foo() and you will get the one from Class A
   }
}

The same works for constructors


text:
Q: How do I combine date from one timestamp and time from another timestamp? I using AngularJS to get date and time separately as user input through via HTML. But timestamp is a single column in my database.
Date and Time field are coming as two different timestamps in my Java server.
Date --> 2015-11-11 00:00:00.0
Time --> 1970-01-01 23:11:00.0

I want to combine date part from Date and time part from Time and insert as timestamp into my database
DateTime --> 2015-11-11 23:11:00.0

A: Assuming you're able to create these as java.util.Date objects, you can rely on their milleseconds-from-epoch to get this information:
long dateMills = date.getTime();
long timeMills = time.getTime();

long dateTimeMills = dateMills + timeMills();

long dateTime = new Date(dateTimeMills);

Alternatively, you could set the fields individually.
GregorianCalendar dateCal = new GregorianCalendar();
GregorianCalendar timeCal = new GregorianCalendar();

dateCal.setTime(date.getTime());
timeCal.setTime(time.getTime());

int year = dateCal.get(Calendar.YEAR);
int month = dateCal.get(Calendar.MONTH);
int day = dateCal.get(Calendar.DAY_OF_MONTH);

int hour = timeCal.get(Calendar.HOUR_OF_DAY);
int minute = timeCal.get(Calendar.MINUTE);
int second = timeCal.get(Calendar.SECOND);

GregorianCalendar dateTimeCal = new GregorianCaledar(year, month, day, hour, minute, second);
Date dateTime = dateTimeCal.getTime();

A: No need to use the date and time as String, just use Calendar and get the fields separately:
public static Date combineDateTime(Date date, Date time) {
    Calendar dateCalendar = Calendar.getInstance();
    dateCalendar.setTime(date);

    Calendar timeCalendar = Calendar.getInstance();
    timeCalendar.setTime(time);

    dateCalendar.set(Calendar.HOUR, timeCalendar.get(Calendar.HOUR));
    dateCalendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
    dateCalendar.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));

    return dateCalendar.getTime();
}

A: You can simply use String.split and create your required String date and use it as required.
 SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a");
 SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String dateInString = "12:30 AM";
 String dateInString2 = "2017-10-16 10:00:00";
 try {
  Date date1 = formatter.parse(dateInString);
  Date date2 = formatter2.parse(dateInString2);
  String[] d1 = formatter2.format(date1).split(" ");
  String[] d2 = formatter2.format(date2).split(" ");
  String neededDate = d2[0] + " " + d1[1];
  System.out.println(date1);
  System.out.println(formatter2.format(date1));
  System.out.println(formatter2.format(date2));
  System.out.println(neededDate);
 } catch (ParseException e) {
  e.printStackTrace();
 }

Output
Thu Jan 01 00:30:00 IST 1970
1970-01-01 00:30:00
2017-10-16 10:00:00
2017-10-16 00:30:00


text:
Q: Deploying spring application in wildfly 11 result in " Only one AsyncAnnotationBeanPostProcessor may exist within the context." error We have a Java Spring 3.2 project, we are trying to migrate the project from jBoss 7 to wildFly 11
However, during the deployment the following error occurs:

Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host./faultmanager" =>
      "java.lang.RuntimeException: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
      Only one AsyncAnnotationBeanPostProcessor may exist within the context. Offending resource:
      \"/D:/wildfly-11.0.0.Final/wildfly-11.0.0.Final/bin/content/xxxx.war/WEB-INF/classes/META-INF/spring/applicationContext.xml\"
      Caused by: java.lang.RuntimeException: org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
      Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context. Offending resource:
      \"/D:/wildfly-11.0.0.Final/wildfly-11.0.0.Final/bin/content/xxxxxx.war/WEB-INF/classes/META-INF/spring/applicationContext.xml\"
      Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
      Only one AsyncAnnotationBeanPostProcessor may exist within the context. Offending resource:
      \"/D:/wildfly-11.0.0.Final/wildfly-11.0.0.Final/bin/content/xxxxxx.war/WEB-INF/classes/META-INF/spring/applicationContext.xml\""}}

With our attempts and our searches, we got that the exception could be throwed by some causes:

*

*Some bean in applicationContext.xml is defined twice

*The applicationContext.xml is imported twice

*Some bean defined in applcationContext.xml is defined again in a different file

*This may be caused by a  tag defined in applicationElement.xml, but trying to remove it will cause a illegalArgumentException during the deploy (don't know why), interestingly this doesn't appear to be used anywhere

*This may be caused by another contextl (we have an applicationContext-security) but even removing it the same error above will persist

Others fun facts:

*

*The error is never throwned during the build, only during the deploy throught wildFly

*The same project have worked for year in jboss without this kind of problem

What could be the cause?

A: this will happens only ,
1)may be you are import both applicationContext-root.xml and applicationContext-where-annotation-driven-is-specififed.xml in your WEB.xml in  section.
2)make applicationContext-root.xml in WEB.xml.
2)This is happenning because you are initializ The application context twice but org.springframework.scheduling.config.AnnotationDrivenBeanDefinitionParser fails registering bean ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME second time.
3)and spring parses the <task:annotation-driven/> text twice in a config XML.
may be one of the resons is that  @ContextConfiguration("/path/to/applicationContext.xml") are both the parent test class and child test class


text:
Q: How to add ANN in python smote_variants model_selection? I am working with the library smote-variants for python (https://pypi.org/project/smote-variants/) and I want to use the method model_selection to select the best classifier and the best resampling method. I do it just like this:
lista_oversamplers = sv.get_all_oversamplers()

samp_obj, cl_obj = sv.model_selection(dataset = dataset,
                                    samplers = lista_oversamplers,
                                    classifiers = list_classifiers,
                                    cache_path = cache_path,
                                    n_jobs = 5,
                                    max_samp_par_comb = 10)

CLassifiers such as KNN or RandomForestClassifier can be included as a list of classifiers in sv.model_selection(), but what if I would like to include an ANN implementation? How can I do it? Is there a way?


text:
Q: Software to use webcam as camera Is there software that allows the webcam to be used as a camera?
I'm using Ubuntu 12.04 desktop.
Thanks!

A: Another nice alternative to cheese: GTK UCV Video Viewer
Install it using sudo apt-get install guvcview

A: As your goal is to take pictures of your desk, I'd suggest to install cheese
Open a terminal (Ctrl+Alt+t) and type:
sudo apt-get install cheese

Then start it with just cheese from the same terminal or from the Dash:

A: May I assume you wish to be able to take a still photo with your webcam? If so, I recommend cheese. It is available in the Ubuntu repositories:
sudo apt-get install cheese

After you start it, there is an option to take a photo, photos in a burst or videos.


text:
Q: WPF: How to get cell value from DataGridRow I have DataGridRow of a DataGrid, how can I get the individual column values from it? See the code below.
var itemsSource = MESearchDatagrid.ItemsSource as IEnumerable;
if (itemsSource != null)
{
    foreach (var item in itemsSource)
    {
        var row = MESearchDatagrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (row != null)
        {
        //How to get the Cell value?
        }

    }
}

A: You can cast your row.item to your initial class type.
        var itemsSource = MESearchDatagrid.ItemsSource;
        if (itemsSource != null)
        {
            foreach (var item in itemsSource)
            {
                var row = MESearchDatagrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (row != null)
                {
                    var data = row.Item as UserClass;
                    MessageBox.Show(data.Name);
                }

            }
        }

A: There is no reason to call the ContainerFromItem method here. The ItemsSource contains the actual data objects. You only need to cast them to your type (called YourClass in the following sample code):
var itemsSource = MESearchDatagrid.ItemsSource as IEnumerable;
if (itemsSource != null)
{
    foreach (var item in itemsSource.OfType<YourClass>())
    {
        var prop = item.Property1;
        //...
    }
}

Property1 is a property of YourClass.


text:
Q: Redirecionar para uma pagina através de um post Pessoal precisava fazer o seguinte tenho uma pagina feita em html puro e nela tenho uma área onde o usuário pode colocar seu e-mail e pedir pra cadastra-lo. Ai queria pegar este e-mail do inoput text e no post direcionar para outra página onde pego a string recebida e a trato no controller. porém não estou tendo sucesso ao incluir o valor do input na minha url.

<form>

Quer receber as melhores ofertas dos nossos parceiros? Cadastre-se abaixo!

                    <form>

                                <input type="email" id="email" name="email" class="form-control form-control-lg" placeholder="Digite seu melhor email...">

                                <button type="submit" id="enviar" formmethod="post" formaction="../Home/GetEmail/?email=document.getElementById('email').value" class="btn btn-block btn-lg btn-primary">Cadastrar!</button>

                    </form>

</form>

porem ao redirecionar fica assim:
http://localhost:64073/Home/GetEmail/?email=document.getElementById(%27email%27).value
talvez minha forma de concatenar esteja errada.
Algum id~eia como resolver isso?

A: Na verdade era apenas um forma de concatenar a string no formaction :\
formaction="../Home/GetEmail/?email=document.getElementById('email').value"
ele passa na minha url:
/Home/GetEmail/?email=document.getElementById(%27email%27).value
Mas o no controller consegue recuperar o e-mail e ai deu certo!

        public ActionResult GetEmail(string email)
        {
            EmailRegister emailregister = new EmailRegister();

            if (email != "" && email != null)
            {
                try
                {
                    emailregister.Email = email;
                    emailregister.RegisterDate = DateTime.Now;

                    _emailregisterRepository.InsertEmailRegister(emailregister);
                    _emailregisterRepository.Save();

                    TempData["Message"] = "E-mail cadastrado com sucesso!";

                }
                catch (DataException ex)
                {
                    TempData["Error"] = "Não foi possível salvar as alterações. Tente de novo, e se o problema persistir consulte o administrador do sistema. Erro: " + ex.Message;
                }

            }

            return View("GetEmail");
        }


text:
Q: Decrease the sensitivity of rotation of arrow (React native + PanResponder) Does anyone know how can I decrease the rotating velocity of arrow which is below.
I'm using panResponder and have some simple maths to rotate the arrow image.
The rotation is too sensitive, its is working fine for me but some how I'm not able to decrease the velocity
Code Link:
https://snack.expo.dev/bLVo169CM
Video:

Thanks in advance ✨

A: Not sure but changing the divisor maybe ?
Like so :
          let x0 = x.current + 100 / 4;
          let y0 = y.current + 100 / 4;


text:
Q: Structure of inputs to scipy minimize function I have inherited some code that is trying to minimize a function using scipy.optimize.minimize.  I am having trouble understanding some of the inputs to the fun and jac arguments
The call to minimize looks something like this:
result = minimize(func, jac=jac_func, args=(D_neg, D, C), method = 'TNC' ...other arguments)

func looks like the following:
def func(G, D_neg, D, C):
#do stuff

jac_func has the following structure:
def jac_func(G, D_neg, D, C):
#do stuff

What I don't understand is where the G input to func and jac_func is coming from.  Is that somehow specified in the minimize function, or by the fact that the method is specified as TNC?  I've tried to do some research into the structure of this optimization function but I'm having trouble finding the answer I need.  Any help is greatly appreciated

A: The short answer is that G is maintained by the optimizer as part of the minimization process, while the (D_neg, D, and C) arguments are passed in as-is from the args tuple.
By default, scipy.optimize.minimize takes a function fun(x) that accepts one argument x (which might be an array or the like) and returns a scalar. scipy.optimize.minimize then finds an argument value xp such that fun(xp) is less than fun(x) for other values of x. The optimizer is responsible for creating values of x and passing them to fun for evaluation.
But what if you happen to have a function fun(x, y) that has some additional parameter y that needs to be passed in separately (but is considered a constant for the purposes of the optimization)? This is what the args tuple is for. The documentation tries to explain how the args tuple is used, but it can be a little hard to parse:

args: tuple, optional
Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian).

Effectively, scipy.optimize.minimize will pass whatever is in args as the remainder of the arguments to fun, using the asterisk arguments notation: the function is then called as fun(x, *args) during optimization. The x portion is passed in by the optimizer, and the args tuple is given as the remaining arguments.
So, in your code, the value of the G element is maintained by the optimizer while evaluating possible values of G, and the (D_neg, D, C) tuple is passed in as-is.


text:
Q: Trouble finding out why string is being copied twice I'm copying a string but for some reason the string is being copied twice.
bool check(const char* word) {
    // copy the word
    char *copy = malloc(sizeof(word));
    strcpy(copy, word);

    printf("word %s\n", word);
    printf("copy %s\n", copy);

    return false;
}

The output of this function is
word myWord
copy myWord
myWord

If i remove the '\n' character in the printf for copy, the output changes to
word myWord
copy myWordmyWord

I've tried walking through this code with a debugger but the debugger is showing the value of copy to be "myWord"
Does anyone have an idea what may be happening here?

A: you need to allocate strlen(word) + 1 bytes.  sizeof(word) returns the number of bytes for storing a pointer.


text:
Q: How to have sub ordered lists correctly I'm not sure I understand the logistics of this.  Basically I wanted to make a simple listing on a web blog that looks like:
1.  item1
    a.  item2
2.  item3
    a.  item4
    b.  item5
3.  item6

And so on, basically a master list ordered numerically, with child lists under each master item that are lower-alpha ordered.
I achieved this effect by using this HTML markup:

item1

item2

item3

item4

item5

item6

With this small CSS rule:
ol ol { list-style-type: lower-alpha; } /* sub ordered lists */

This issue I had was that according to the w3c validator:

Element ol not allowed as child of element ol in this context.

I think this problem ought have a very simple solution, I wasn't able to find one, and I'm not sure I follow why ol cannot be a child of ol.

A: There are several ways to control your sub-ordered list, either with CSS, or HTML. You almost were achieving the effect you want, to get something like this:
1.  item1
    a.  item2
2.  item3
    a.  item4
    b.  item5
3.  item6

Your HTML should look like this:

item1

item2

item3

item4

item5

item6

And your CSS should look like this:
ol li{ list-style-type:decimal; } /* sub ordered lists level 1 */
ol li ol li { list-style-type: lower-alpha; } /* sub ordered lists level 2 */

You can also read more about a similar question here

A: You do it like this:

item1

item2

You need to put the sublist inside the list item for the top level.

A: I think that your ol needs to be in an li:

item1

item2


text:
Q: Spring Cloud Config failed to get the configuration from private git repository I was using the classpath of my spring cloud config server to put all the config files and now I decide to move it to a git server, so I created a empty repository and then commited my config files.
The config looks like this:
server:
  port: 8888

spring:
  application:
    name: server-config
  cloud:
    config:
      server:
        git:
          uri: ssh://development@xxx.xx.my.ip:/home/development/repository
          password: password

When I start the config server, everything works fine, but when I wont to access the configuration of a microservice through the url (example: http://localhost:8888/get-ticket/env) I get an following message:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
  this as a fallback. Tue Sep 22 14:30:31 GMT-03:00 2015 There was an
  unexpected error (type=Internal Server Error, status=500). Cannot load
  environment

And in my stacktrace I can see:

2015-09-22 14:30:31.024  INFO 9160 --- [nio-8888-exec-1]
  o.s.web.servlet.DispatcherServlet        : FrameworkServlet
  'dispatcherServlet': initialization completed in 18 ms 2015-09-22
  14:30:31.233 ERROR 9160 --- [nio-8888-exec-1]
  o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for
  servlet [dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
  java.lang.IllegalStateException: Cannot load environment] with root
  cause
org.eclipse.jgit.errors.NotSupportedException: URI not supported:
  ssh:///development@xxx.xx.my.ip:/home/development/repository  at
  org.eclipse.jgit.transport.Transport.open(Transport.java:563)     at
  org.eclipse.jgit.transport.Transport.open(Transport.java:437)     at
  org.eclipse.jgit.transport.Transport.open(Transport.java:318)     at
  org.eclipse.jgit.transport.Transport.open(Transport.java:287)     at
  org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:120)     at
  org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:178)    at
  org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:125)     at
  org.springframework.cloud.config.server.JGitEnvironmentRepository.cloneToBasedir(JGitEnvironmentRepository.java:207)
    at
  org.springframework.cloud.config.server.JGitEnvironmentRepository.copyRepository(JGitEnvironmentRepository.java:180)
    at
  org.springframework.cloud.config.server.JGitEnvironmentRepository.createGitClient(JGitEnvironmentRepository.java:169)
    at
  org.springframework.cloud.config.server.JGitEnvironmentRepository.findOne(JGitEnvironmentRepository.java:79)
    at
  org.springframework.cloud.config.server.MultipleJGitEnvironmentRepository.findOne(MultipleJGitEnvironmentRepository.java:84)
    at
  org.springframework.cloud.config.server.EnvironmentController.labelled(EnvironmentController.java:83)
    at
  org.springframework.cloud.config.server.EnvironmentController.defaultLabel(EnvironmentController.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)     at
  org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at
  org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at
  org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at
  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at
  org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:291)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
    at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at
  org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at
  org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

A: Spring config have an issue on ssh connection, use http instread

A: Spring cloud config gives you a 500 error when it tries to load a yml/properties file that has a synctatic error (e.g., duplicate key).
The error message gives you no useful information about the cause of the problem. There's an open issue to improve the error message.


text:
Q: Building highly scalable web services My team and I are in the middle of developing an application which needs to be able to handle pretty heavy traffic. Not facebook level but in the future I would like to be able to scale to that without massive code re-writes.
My thought was to modularise out everything into seperate services with their own interfaces. So for example messaging would have a messaging interface that might have send and getMessages() as methods and then the PHP web app would simply query this interface through soap or curl or something like that. The messaging application could then be any kind of application so a Java application or Python or whatever was suitable for that particular functionality with its own seperate database shard.
Is this a good approach?

A: That sounds reasonable as a first step, just keep in mind the traffic between the PHP layer and the messaging layer will add a bit of latency. You might also consider:

*

*Caching data on the PHP layer, using (for example) memcached. You might also consider using a Web Proxy Cache such as squid

*Scaling your web server to more than one machine by, for example, storing session data in the database. Once you can support having 2 web servers, adding a third (fourth, fifth, etc) should be simple. Keep in mind that you may eventually need to scale the messaging layer to multiple machines as well.

*Using tools such as PHP e-Accelerator to cache compiled scripts; should help increase performance on the web layer
There are some great articles on High Scalability as well, that you might find helpful.
Finally, keep in mind it is easy to over-engineer a solution. Your best bet is to continuously measure load, performance, resource utilization, etc along the way - then use this data to make adjustments as necessary.

A: Modularise

My thought was to modularise out
  everything into seperate services with
  their own interfaces. So for example
  messaging would have a messaging
  interface that might have send and
  getMessages() as methods and then the
  PHP web app would simply query this
  interface through soap or curl or
  something like that

I like the idea of separating every in service modules(good coding principle).  I don't like the part about SOAP :(. I think it is way to complex. I would go for something like JSON-RPC or something.
Some quick tips:

My team and I are in the middle of
  developing an application which needs
  to be able to handle pretty heavy
  traffic. Not facebook level but in the
  future I would like to be able to
  scale to that without massive code
  re-writes.

*

*Like the others also hinted I would advice you to look at High Scalability blog.

*First focus on the front-end using YSlow / google page speed. This optimization are easy to implement and can give you significantly boosts. A quote from the Yslow webpage:

80% of the end-user response time is
  spent on the front-end. Most of this
  time is tied up in downloading all the
  components in the page: images,
  stylesheets, scripts, Flash, etc.
  Reducing the number of components in
  turn reduces the number of HTTP
  requests required to render the page.
  This is the key to faster pages.

*

*I would also advice you to have a look at HipHop for php which converts your php code to C code which was a huge boost for facebook. A quote from the article:

With HipHop we've reduced the CPU
  usage on our Web servers on average by
  about fifty percent, depending on the
  page. Less CPU means fewer servers,
  which means less overhead

*

*I guess another big/easy improvement if not already setup is to use APC(opcode cache) to cache your compiled code. This will give you a huge boost(not necessary for the parts converted to HipHop).

*If you want your websites to scale you have to go by the mantra:

RAM is the new Disk

!Cache, cache, cache! with for example APC, memcached, redis.

*First profile your PHP code then optimize low hanging fruit. I found this audio file from Rasmus Lerdorf really useful. When reading the blog post you will find a lot of good tips to improve performance.

*Also I would consider moving away from the relation database in favor of for example Cassandra. This is a move which I see a lot of big players do recently(for example twitter, digg, facebook, reddit). You will have to go in a complete different mindset this way, but my bet is this will totally be worth the effort.

*Queue everything and delight every one with for example beanstalkd, gearman or google app engine's taskqueue.

A: Cache, cache, and more cache.  SQL query caching, opcode caching, avoid querying multiple times for the same thing. Then use a profiler as you run to keep track of where your slow points are.

A: Basing the high level design around a set of modules is a good way to manage complexity and structure development (even more so that at the micro level) however

the PHP web app would simply query this interface through soap or curl

This introduces a lot of latency into the application. I'd suggest defining APIs but for any synchronously handled request, run as much of the code within a single thread as possible.
Sure, if you have to deal with multiple development languages, using an interface running over HTTP is a very pragmatic solution - but if you're developing the front end in PHP then by programming to an abstract PHP API (which may call Soap, Corba, or other stuff), you still have the option of reimplementing the backend in a different way later.
I'm not sure what you mean by messaging. If you're talking about asynchronous request processing, then you need to think about how to implement a subscriber in PHP. This is a complete can of worms - I've not seen a good message handling system written in PHP - but I've not seen a good scalable solution written in Java either - and that includes the products pimped by some major players in high end systems. Maybe one day I'll write one ;) in the meantime, you really want to keep your complex (and potentially less reliable) business logic running in a seperate thread from any sort of subscriber daemon - so an obvious way to do that is to expose the target as a web page and have the subscriber running as a daemon which simply picks up messages and calls web-based APIs.
You really don't want to base a synchronous system around messaging if your at all concerned about performance / reliability / scalability.
HTH
C.


text:
Q: Resizing floated elements, that are resizable with JQuery UI Resizable, on window resize to fit their parent container I'm having trouble to solve an issue with floated elements and  JQuery UI Resizable and window resize event.
Here is the jsFiddle with the problem.
Basically, I have a parent container - .tab - and 3 child divs. .content1, .content2 and .content3. Both .content2 and content3 are inversely proportional resized when .content1 is resized with the "alsoInverResize" function.

$(".container1").resizable({
    containment: "parent",
    handles: "s",
    alsoInverResize: ".container2, .container3",
    maxHeight: $(".tab").height()
});

Althought all 3 child divs start with percentage widths and height to fit their parent, when they're resized they get flat sizes, and when you resize the window to less than the original size, they overflow from the parent container, making the .container3 floating left under .container2, or having less width that their parent if the window gets a bigger size than the original.
I've tried to set percentage sizes again on the window resize event, but that prevents the resizeable plugin from even working, obviously not being the desired effect (http://jsfiddle.net/fh77N/2/) :
$(".container1").css({"height" : "50%", "width" : "100%"});
$(".container3").css({"height" : "50%", "width" : "70%"});
$(".container2").css({"height" : "50%", "width" : "30%"});

I want to make the three child containers be either equality resized to the ratio of the window or parent on window.resize or having them revert to their original percentage sizes but maintaining the resizeable functionality.


text:
Q: Counting in Wonderland The text of Alice in Wonderland contains the word 'Wonderland' 8 times. (Let's be case-insensitive for this question).
However it contains the word many more times if you count non-contiguous subsequences as well as substrings, eg.

Either the well was very deep, or she fell very slowly, for she had
  plenty of time as she went down to look about her and to WONDER what was
  going to happen next. First, she tried to Look down AND make out what
  she was coming to, but it was too dark to see anything;

(A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. —Wikipedia)
How many times does the book contain the word Wonderland as a subsequence? I expect this will be a big number—it's a long book with many w's and o's and n's and d's.
I tried brute force counting (recursion to make a loop 10 deep) but it was too slow, even for that example paragraph.

A: The string "wonderland" occurs as a subsequence in Alice in Wonderland1 24100772180603281661684131458232 times.
The main idea is to scan the main text character by character, keeping a running count of how often each prefix of the target string (i.e.: in this case, "w", "wo", "won", ..., "wonderlan", and "wonderland") has occurred up to the current letter. These running counts are easy to compute and update. If the current letter does not occur in "wonderland", then the counts are left untouched. If the current letter is "a" then we increment the count of "wonderla"s seen by the number of "wonderl"s seen up to this point. If the current letter is "n" then we increment the count of "won"s by the count of "wo"s and the count of "wonderlan"s by the count of "wonderla"s. And so forth. When we reach end of the text, we will have the count of all prefixes of "wonderland" including the string "wonderland" itself, as desired.
The advantage of this approach is that it requires a single pass through the text and does not require O(n) recursive calls (which will likely exceed the maximum recursion depth unless you do something clever).
Code
import fileinput
import string

target = 'wonderland'

prefixes = dict()
count = dict()

for i in range(len(target)) :
    letter = target[i]
    prefix = target[:i+1]
    if letter not in prefixes :
        prefixes[letter] = [prefix]
    else :
        prefixes[letter].append(prefix)
    count[prefix] = 0L

for line in fileinput.input() :
    for letter in line.lower() :
        if letter in prefixes :
            for prefix in prefixes[letter] :
                if len(prefix) > 1 :
                    count[prefix] = count[prefix] + count[prefix[:len(prefix)-1]]
                else:
                    count[prefix] = count[prefix] + 1

print count[target]

*

*Using this text from Project Gutenberg, starting with "CHAPTER I. Down the Rabbit-Hole" and ending with "THE END"

A: Let's say you didn't want to search for wonderland, but just for w. Then you'd simply count how many times w occurred in the story.
Now let's say you want wo. For each first character of the current pattern you find, you add to your count:

*

*How many times the current pattern without its first character occurs in the rest of the story, after this character you're at: so you have reduced the problem (story[1..n], pattern[1..n]) to (story[2..n], pattern[2..n])

*How many times the entire current pattern occurs in the rest of the story. So you have reduced the problem to (story[2..n], pattern[1..n])
Now you can just add the two. There is no overcounting if we talk in terms of subproblems. Consider the example wawo. Obviously, wo occurs 2 times. You might think the counting will go like:

*

*For the first w, add 1 because o occurs once after it and another 1 because wo occurs once after it.

*For the second w, add 1 because o occurs once after it.

*Answer is 3, which is wrong.
But this is what actually happens:
(wawo, wo) -> (awo, o) -> (wo, o) -> (o, o) -> (-, -) -> 1
                                            -> (-, o) -> 0
           -> (awo, wo) -> (wo, wo) -> (o, wo) -> (-, wo) -> 0
                                    -> (o, o) -> (-, -) -> 1
                                              -> (-, o) -> 0

So you can see that the answer is 2.
If you don't find a w, then the count for this position is just how many times wo occurs after this current character.
This allows for dynamic programming with memoization:
count(story_index, pattern_index, dp):
  if dp[story_index, pattern_index] not computed:
    if pattern_index == len(pattern):
      return 1
    if story_index == len(story):
      return 0

    if story[story_index] == pattern[pattern_index]:
      dp[story_index, pattern_index] = count(story_index + 1, pattern_index + 1, dp) +
                                       count(story_index + 1, pattern_index, dp)
    else:
      dp[story_index, pattern_index] = count(story_index + 1, pattern_index, dp)

  return dp[story_index, pattern_index]

Call with count(0, 0, dp). Note that you can make the code cleaner (remove the duplicate function call).
Python code, with no memoization:
def count(story, pattern):
  if len(pattern) == 0:
    return 1
  if len(story) == 0:
    return 0

  s = count(story[1:], pattern)
  if story[0] == pattern[0]:
    s += count(story[1:], pattern[1:])

  return s

print(count('wonderlandwonderland', 'wonderland'))

Output:
17

This makes sense: for each i first characters in the first wonderland of the story, you can group it with remaining final characters in the second wonderland, giving you 10 solutions. Another 2 are the words themselves. The other five are:
wonderlandwonderland
*********    *
********    **
********    *      *
**      **    ******
***      *    ******

You're right that this will be a huge number. I suggest that you either use large integers or take the result modulo something.
The same program returns 9624 for your example paragraph.

A: Following up on previous comments, if you are looking for an algorithm that would return 2 for the input wonderlandwonderland and 1 for wonderwonderland, then I think you could adapt the algorithm from this question:
How to find smallest substring which contains all characters from a given string?
Effectively, the change in your case would be that, once an instance of the word is found, you increment a counter and repeat all the procedure with the remaining part of the text.
Such algorithm would be O(n) in time when n is the lenght of the text and O(m) in space where m is the length of the searched string.


text:
Q: Phillips hue Local network I want to send signals to a Phillips Hue Bulb from an Arduino Ethernet, but using only a local network. This means I plan to have a router with an Ethernet connection to both the Arduino and the Hue's bridge, but the router has no connection to the Internet. I read their API's page: http://developers.meethue.com/howhueworks.html and from that I think this could work, but I would like to be sure before buying a Hue kit. Anyone who owns one could assert this will indeed work?
Thanks!

A: Yes this will work :)
You only need internet to update the firmware of the bridge or if you want to control your lights from outside your own network.
You do need a way to find the ip address of your bridge though. So it's probably easiest to give your bridge a static ip or configure your router to always give the same ip to your bridge.


text:
Q: Why org.hibernate.TransactionException in Hibernate and avoid I'm newbie in Hibernate.
I have tried to code a small program to insert data into mysql database server.
This is source code of my program:
private int insertRelateNew(int newId, List<DocSimilar> relateNews) {
    Session session = HibernateUtils.currentSession();
    Transaction tx = session.beginTransaction();
    RelatedArticles relatedArticles = null;
    try {
        relatedArticles = new RelatedArticles();
        for (DocSimilar doc : relateNews) {
            ApplicationPK appPK = new ApplicationPK(newId,
                    (int) doc.getDocid());
            relatedArticles.setApplicationPK(appPK);
            relatedArticles.setRelated_score(doc.getPercent());
            session.save(relatedArticles);
            tx.commit();
            session.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    }
    return newId;
}

When running, It insert successful but sometime It throw a TransactionException.
This is Exception console:
org.hibernate.TransactionException: Transaction not successfully started
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:131)
    at com.ant.crawler.dao.hibernate.SqlNewsPersistencer.insertRelateNew(SqlNewsPersistencer.java:56)
    at com.ant.crawler.dao.hibernate.SqlNewsPersistencer.insertNews(SqlNewsPersistencer.java:40)
    at com.ant.crawler.dao.hibernate.SqlPersistencer.store(SqlPersistencer.java:44)
    at com.ant.crawler.core.AbstractCrawler.crawl(AbstractCrawler.java:186)
    at com.ant.crawler.core.Worker.run(Worker.java:14)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

I searched the problem, somebody advised catch the Exception and rollback().
But this way can lose the record that I want insert into DB.
I want find why the Exception is happen to avoid It.
I searched the Exception in Hibernate Java Doc: http://www.dil.univ-mrs.fr/~massat/docs/hibernate-3.1/api/org/hibernate/TransactionException.html
It said: "Indicates that a transaction could not be begun, committed or rolled back."
It doesn't explain why the Exception happen.
Please explain for me why the exception happen and how avoid It.
Thanks very much.

A: The explanation is simple: you start a transaction only once, but commit it several times:
Transaction tx = session.beginTransaction();
...
for (DocSimilar doc : relateNews) {
    ...
    tx.commit();
}

Either you want a seperate transaction for each doc, and the transaction must begin inside the for loop, or you want a single transaction for all the docs, and the commit must be outside the for loop.

A: I had the same error message as yours, I found that even the rollback could give you a problem here.
In my case, when I call "tx.rollback()", it throws me above error "org.hibernate.TransactionException: Transaction not successfully started".
So when I realized that, I added following ...
if (tx!=null && tx.isActive()) {
 tx.rollback();
}

then it reveals me another exception, which is better now, caused now I can see where's the real problem is, it's some criteria in my insert I've not fulfilling ...
Hope this helps, cheers.


text:
Q: Whats the batch request limit for Facebooks Graph API? Does anyone know whats the limit for batch requests when using FBs graph API?
From their documentation:

Limit
We currently limit the number of batch requests to 20.

Source
That's not clear. Is that 20 per 600 seconds? Per day? Total for one app ever?

A: It is 50 now. 50 request/batch

A: It means that 20 individual requests are allowed to be batched together into a single batched request, which saves you from sending 20 individual http requests over at the same time.

A: If you have more than twenty (20) you can build an array and then break them into groups of 20 or less and loop them thru your PHP in one "session".   We have one app that will run 600 - 700 OG requests but it is sloooooooow, up to 300 seconds, some times, depending on FB.


text:
Q: How to set session expiry time for mod_auth_openidc We are using OpenID Connect on one of our applications, and implementing with Apache's mod_auth_openidc. Is there a way to set the expiry time of the session? Our current configuration looks like this:
    OIDCProviderMetadataURL https://accounts.google.com/.well-known/openid-configuration
    OIDCClientID XXXXXXXXXXXXXXXXX
    OIDCClientSecret ZZZZZZZZZZZZZZZ
    OIDCRedirectURI https://jZZZZZZZZ.com
    OIDCCryptoPassphrase <password>
    OIDCScope "openid email"
    <Location />
            AuthType openid-connect
            require valid-user
            Require claim hd:xxxxxx
   </Location>

A: You can set OIDCSessionMaxDuration as documented in the template .conf file https://github.com/zmartzone/mod_auth_openidc/blob/master/auth_openidc.conf#L529:
# Maximum duration of the application session
# When not defined the default is 8 hours (3600 * 8 seconds).
# When set to 0, the session duration will be set equal to the expiry time of the ID token.
# NB: this can be overridden on a per-OP basis in the .conf file using the key:
# "session_max_duration"
#OIDCSessionMaxDuration <seconds>