问:
Tensorflow:How to save the model in the step that I want in training
Here is a problem that I want my code can save the model by each 100 step , my TRAIN_STEPS is 3000 , so there should almost 30 models be saves, but it only last 5 models be saved .The details in checkpoint is :

```<code>model_checkpoint_path: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2900"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2500"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2600"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2700"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2800"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2900"
</code>```

only save those 5 models.I don't know why.can somebody tell me? Here is my code

```<code># coding=utf-8
from  color_1 import read_and_decode, get_batch, get_test_batch
import color_inference
import cv2
import os
import time
import numpy as np
import tensorflow as tf

batch_size=128
TRAIN_STEPS=3000
crop_size=56
MOVING_AVERAGE_DECAY=0.99
num_examples=50000
LEARNING_RATE_BASE=0.8
LEARNING_RATE_DECAY=0.99
MODEL_SAVE_PATH="/home/vrview/tensorflow/example/char/tfrecords/color/"
MODEL_NAME="model.ckpt"

def train(batch_x,batch_y):
    image_holder = tf.placeholder(tf.float32, [batch_size, 56, 56, 3], name='x-input')
    label_holder = tf.placeholder(tf.int32, [batch_size], name='y-input')
    image_input = tf.reshape(image_holder, [-1, 56, 56, 3])

    y=color_inference.inference(image_holder)
    global_step=tf.Variable(0,trainable=False)

    def loss(logits, labels):
        labels = tf.cast(labels, tf.int64)
        cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
            logits=logits, labels=labels, name='cross_entropy_per_example')

        cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
        tf.add_to_collection('losses', cross_entropy_mean)
        return tf.add_n(tf.get_collection('losses'), name='total_loss')

    loss = loss(y, label_holder)
    train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)

    saver=tf.train.Saver()
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for i in range(TRAIN_STEPS):
            image_batch, label_batch = sess.run([batch_x, batch_y])
            _, loss_value,step = sess.run([train_op, loss,global_step], feed_dict={image_holder: image_batch,
                                                                                label_holder:label_batch})
            if i % 100 == 0:
                format_str=('After %d step,loss on training batch is: %.2f')
                print (format_str%(i,loss_value))
                saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=i)
        coord.request_stop()
        coord.join(threads)
def main(argv=None):
    image, label = read_and_decode('train.tfrecords')
    batch_image, batch_label = get_batch(image, label, batch_size, crop_size)  # batch 生成测试
    train(batch_image,batch_label)
if __name__=='__main__':
    tf.app.run()
</code>```

答: add max_to_keep=30 to your constructor of your saver, by default its value is 5, that's why you only save 5 times

Body:
Here is a problem that I want my code can save the model by each 100 step , my TRAIN_STEPS is 3000 , so there should almost 30 models be saves, but it only last 5 models be saved .The details in checkpoint is :

model_checkpoint_path: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2900"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2500"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2600"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2700"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2800"
all_model_checkpoint_paths: "/home/vrview/tensorflow/example/char/tfrecords/color/model.ckpt-2900"

only save those 5 models.I don't know why.can somebody tell me? Here is my code

# coding=utf-8
from  color_1 import read_and_decode, get_batch, get_test_batch
import color_inference
import cv2
import os
import time
import numpy as np
import tensorflow as tf

batch_size=128
TRAIN_STEPS=3000
crop_size=56
MOVING_AVERAGE_DECAY=0.99
num_examples=50000
LEARNING_RATE_BASE=0.8
LEARNING_RATE_DECAY=0.99
MODEL_SAVE_PATH="/home/vrview/tensorflow/example/char/tfrecords/color/"
MODEL_NAME="model.ckpt"

def train(batch_x,batch_y):
    image_holder = tf.placeholder(tf.float32, [batch_size, 56, 56, 3], name='x-input')
    label_holder = tf.placeholder(tf.int32, [batch_size], name='y-input')
    image_input = tf.reshape(image_holder, [-1, 56, 56, 3])

    y=color_inference.inference(image_holder)
    global_step=tf.Variable(0,trainable=False)

    def loss(logits, labels):
        labels = tf.cast(labels, tf.int64)
        cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
            logits=logits, labels=labels, name='cross_entropy_per_example')

        cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
        tf.add_to_collection('losses', cross_entropy_mean)
        return tf.add_n(tf.get_collection('losses'), name='total_loss')

    loss = loss(y, label_holder)
    train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)

    saver=tf.train.Saver()
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for i in range(TRAIN_STEPS):
            image_batch, label_batch = sess.run([batch_x, batch_y])
            _, loss_value,step = sess.run([train_op, loss,global_step], feed_dict={image_holder: image_batch,
                                                                                label_holder:label_batch})
            if i % 100 == 0:
                format_str=('After %d step,loss on training batch is: %.2f')
                print (format_str%(i,loss_value))
                saver.save(sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=i)
        coord.request_stop()
        coord.join(threads)
def main(argv=None):
    image, label = read_and_decode('train.tfrecords')
    batch_image, batch_label = get_batch(image, label, batch_size, crop_size)  # batch 生成测试
    train(batch_image,batch_label)
if __name__=='__main__':
    tf.app.run()


来源: stackexchange

问:
Returning two variables in SML
I have a function below that uses variable X and variable A.

How can I return both of these variables to be able to use these values further down the program.

```<code>val a = 1000;
val x = 5;

fun test (x,a) =
    if (a<1) then(
    x)

    else(
    test(x+1,a-1)
    )
</code>```

答:
You just return a pair:

```<code>fun test (x, a) = if a < 1 then (x, a) else test (x+1, a-1)
</code>```

You receive it by pattern matching:

```<code>val (y, z) = test (10, 11)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Returning two variables in SML

Body:
I have a function below that uses variable X and variable A.

How can I return both of these variables to be able to use these values further down the program.

val a = 1000;
val x = 5;

fun test (x,a) =
    if (a<1) then(
    x)

    else(
    test(x+1,a-1)
    )

Body:
You just return a pair:

fun test (x, a) = if a < 1 then (x, a) else test (x+1, a-1)

You receive it by pattern matching:

val (y, z) = test (10, 11)


问:
Data not inserted using hibernate, but gives no error?
I'm trying to get started with Hibernate, but can't insert data, for some reason. It seems to be working properly as no error is given, but when I check the database the table is empty. I don't think it the connection to the database itself that fail, because when I change the table name to a non-excisting one in the mapping xml, Hibernate creates this on the fly (But as I said, no data is inserted). Does anyone know what the problem could be?

Here's my code:

hibernate.cfg.xml:

```<code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
          <property     name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/intex</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password"></property>
          <property name="hibernate.connection.pool_size">10</property>
          <property name="show_sql">true</property>
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
          <property name="hibernate.hbm2ddl.auto">update</property>
          <!-- Mapping files -->
          <mapping resource="intex.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
</code>```

My mapping xml:

```<code><hibernate-mapping>
  <class name="com.intex.uni.courses.Course" table="course">
   <id name="id" column="id" >
   <generator class="increment"/>
  </id>

  <property name="name" column="name" />
  <property name="description" column="description" />
  <property name="url" column="url" />
  <property name="code" column="code" />
 </class>
</hibernate-mapping>
</code>```

And my test client:

```<code>public class HibernateTest {

    public static void main(String[] args) {

        Session session = null;

        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Course course = new Course();
            course.setDescription("Description");
            course.setName("NAME");
            course.setUrl("http://www.url.com");
            session.save(course);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }
}
</code>```

I really hope someone will be able to help me! Thanks in advance :)

答:
use this code and test in main class.     </p>

```<code>Session session = null;
Transaction txn = null;
try {
    SessionFactory sessionFactory =
        new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();
    txn = session.beginTransaction();
    Course course = new Course();
    course.setDescription("Description");
    course.setName("NAME");
    course.setUrl("http://www.url.com");
    session.save(course);
    txn.commit();

} catch (Exception e) {
    System.out.println(e.getMessage());
} finally {
    if (!txn.wasCommitted()) {
        txn.rollback();
    }

    session.flush();
    session.close();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get started with Hibernate, but can't insert data, for some reason. It seems to be working properly as no error is given, but when I check the database the table is empty. I don't think it the connection to the database itself that fail, because when I change the table name to a non-excisting one in the mapping xml, Hibernate creates this on the fly (But as I said, no data is inserted). Does anyone know what the problem could be?

Here's my code:

hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
          <property     name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/intex</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password"></property>
          <property name="hibernate.connection.pool_size">10</property>
          <property name="show_sql">true</property>
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
          <property name="hibernate.hbm2ddl.auto">update</property>

          <mapping resource="intex.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

My mapping xml:

<hibernate-mapping>
  <class name="com.intex.uni.courses.Course" table="course">
   <id name="id" column="id" >
   <generator class="increment"/>
  </id>

  <property name="name" column="name" />
  <property name="description" column="description" />
  <property name="url" column="url" />
  <property name="code" column="code" />
 </class>
</hibernate-mapping>

And my test client:

public class HibernateTest {

    public static void main(String[] args) {

        Session session = null;

        try {
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Course course = new Course();
            course.setDescription("Description");
            course.setName("NAME");
            course.setUrl("http://www.url.com");
            session.save(course);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            session.flush();
            session.close();
        }
    }
}

I really hope someone will be able to help me! Thanks in advance :)

Body:
use this code and test in main class.

Session session = null;
Transaction txn = null;
try {
    SessionFactory sessionFactory =
        new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();
    txn = session.beginTransaction();
    Course course = new Course();
    course.setDescription("Description");
    course.setName("NAME");
    course.setUrl("http://www.url.com");
    session.save(course);
    txn.commit();

} catch (Exception e) {
    System.out.println(e.getMessage());
} finally {
    if (!txn.wasCommitted()) {
        txn.rollback();
    }

    session.flush();
    session.close();
}


问:
C Struct to Swift
in c file : have a struct

```<code>struct CPerson {
  const char* name;
  int age;
};
</code>```

in swift file:

```<code>extension UnsafePointer where Pointee == Int8 {
  var string : String? {
     return String.init(cString: self)
  }
}
</code>```

I try use c struct:

```<code>print(CPerson(name: "baby", age: 1).name.string)
//Optional("baby")
</code>```

but :

```<code>let p = CPerson(name: "angela", age: 1)
print(p.name.string , p.age)
//Optional("") 1
</code>```

why p.name.string == "" ?

I hope that p.name.string == "angela"

thanks.

答:
It is a memory management problem. In

```<code> let p = CPerson(name: "angela", age: 1)
</code>```

you pass a Swift String to a function taking an UnsafePointer<Int8>
argument (the Swift equivalent of const char *). The compiler inserts
code to create a temporary   C string representation and
passes that to the CPerson initializer. The name field then points
to that temporary C string.

The problem is that this pointer is no longer valid when the
initializer returns. It may point to something else or may be an
invalid pointer.

A const char * in C is just a pointer, it does not imply any
ownership or memory management. You would have exactly the same
problem in C if you assign

```<code>person.name = someString;
</code>```

and leave the scope where someString is defined.

So you have to decide who is responsible
to allocate (and free) the C string storage.

One option would be to duplicate the string in Swift and release
the memory when it is no longer needed:

```<code>let name = strdup("angela")

let p = CPerson.init(name: name, age: 1)
print(p.name.string , p.age) // Optional("angela") 1

free(name)
</code>```

Another option might be to create C functions CreatePerson()
and ReleasePerson() which allocate and release the storage.

Title: C Struct to Swift

Body:
in c file : have a struct

struct CPerson {
  const char* name;
  int age;
};

in swift file:

extension UnsafePointer where Pointee == Int8 {
  var string : String? {
     return String.init(cString: self)
  }
}

I try use c struct:

print(CPerson(name: "baby", age: 1).name.string)
//Optional("baby")

but :

let p = CPerson(name: "angela", age: 1)
print(p.name.string , p.age)
//Optional("") 1

why p.name.string == "" ?

I hope that p.name.string == "angela"

thanks.

Body:
It is a memory management problem. In

 let p = CPerson(name: "angela", age: 1)

you pass a Swift String to a function taking an UnsafePointer<Int8>
argument (the Swift equivalent of const char *). The compiler inserts
code to create a temporary   C string representation and
passes that to the CPerson initializer. The name field then points
to that temporary C string.

The problem is that this pointer is no longer valid when the
initializer returns. It may point to something else or may be an
invalid pointer.

A const char * in C is just a pointer, it does not imply any
ownership or memory management. You would have exactly the same
problem in C if you assign

person.name = someString;

and leave the scope where someString is defined.

So you have to decide who is responsible
to allocate (and free) the C string storage.

One option would be to duplicate the string in Swift and release
the memory when it is no longer needed:

let name = strdup("angela")

let p = CPerson.init(name: name, age: 1)
print(p.name.string , p.age) // Optional("angela") 1

free(name)

Another option might be to create C functions CreatePerson()
and ReleasePerson() which allocate and release the storage.


问:
Quarzt: store JobDataMap before/without scheduling a job
Is there any way to persist JobDataMap without triggering/scheduling any jobs? Can I afterwards (on callback) start a Job with the stored JobDataMap?

I have many jobs scheduled with Quartz an I pass JobDataMap to those jobs:

```<code>scheduler.triggerJob(new JobKey("job-name", "job-group"), myJobDataMap);
</code>```

Now I need to implement job queue since there are jobs which can't be launched in parallel. The problem is that state (JobDataMap) for some jobs is passed from client, and should be persisted for queueing purposes. In other hand I can't schedule job on user request since I don't know when it should be executed! (It should be executed right after previous job)

答:
Yes.

You can use the method addJob(JobDetail, boolean) to add a new job to the Scheduler without actually scheduling it. Quoting the docs:

The Job will be 'dormant' until it is scheduled with a Trigger, or Scheduler.triggerJob() is called for it.

Your data map would be part of the JobDetail parameter.

Body:
Is there any way to persist JobDataMap without triggering/scheduling any jobs? Can I afterwards (on callback) start a Job with the stored JobDataMap?

I have many jobs scheduled with Quartz an I pass JobDataMap to those jobs:

scheduler.triggerJob(new JobKey("job-name", "job-group"), myJobDataMap);

Now I need to implement job queue since there are jobs which can't be launched in parallel. The problem is that state (JobDataMap) for some jobs is passed from client, and should be persisted for queueing purposes. In other hand I can't schedule job on user request since I don't know when it should be executed! (It should be executed right after previous job)


问:
Calling R Script from within C-Code
Is there a way to call an R-Script within C-Code?

I did find the R Api for C (chaper 6. of the 'Writing R Extensions' manual), but as far as I understood this does "only" allow to call the C-Implementation of R. Of cause I could call the R-Script via shell, but that's no solution for me, since this does not allow proper passing of data (at least no if I don't what to write the data into a Csv-File or something like this).

Is there a easy way of using the R to C parser beforehand?

答:
I found this works to run Rscript in C++ for Mac systems:

```<code>string r_command = "/usr/local/bin/RScript --vanilla /Users/<enter file path here>/your_script.R \"" + argument_1 + "\" " + "\"" + argument_2 + "\"";

system(r_command.c_str());
</code>```

You can also pass variables into the arguments. Watch out on the escapes. Things can get tricky.

Title: Calling R Script from within C-Code

Body:
I found this works to run Rscript in C++ for Mac systems:

string r_command = "/usr/local/bin/RScript --vanilla /Users/<enter file path here>/your_script.R \"" + argument_1 + "\" " + "\"" + argument_2 + "\"";

system(r_command.c_str());

You can also pass variables into the arguments. Watch out on the escapes. Things can get tricky.


问:
Issue in drupal the directory sites/default/files is not writable
To solve these issues display in process of installing Drupal as:

Go to your "drupal" folder and make permission 777

Then open "sites" folder and make it 777

Choose "default" folder and make it 777

Open "files" and choose "setting.php" to change permission to 777

答:
Some normal permissions would be 0644 for files and 0755 for directories. Then i.e. settings.php since there is no need for it to be writable you should fully forbid writing.

If only 0777 "solves" your issue, maybe problem are not permission values but file owner. It happens that you upload files with one (FTP) account Apache is running website with some other, which is not allowed to write over first one. So changing file owner could solve the issue.


问:
Assure Delivery Of UILocalNotification on correct time ios
I'm having a problem with my local notification that is: if the device is in off state or when changing the date of phone, the notification is kept in queue and firing along with next notification. Why?

Since need to have very concern about the date of notification..
How to assure correct delivery of notification?

Where should we put code for removing expired notification?

答:
So you mean you had a notification named ABC to be triggered in 30 minutes...but then you turned your iPhone off for 3 hours...then turned it on and saw that notification ABC notification even though its time was passed? AFAIK ....the notification will still be there unless you remove it using removeDeliveredNotifications(withIdentifiers:).

Basically call:

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).
</code>```

For more information see this moment of this WWDC video.

Also see this tutorial look for the section "4. Managing Notifications"

As to address your edit:

To be honest I'm not sure...but here's what I think you should do:

I suggest to make the class that creates the notifications:

Step1: Conform to UNUserNotificationCenterDelegate

Step2: Implement:

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
 withCompletionHandler completionHandler: @escaping () -> Void) {
}
</code>```

<s>Now that you turned your device on...This function would get called only if app is in background. There you have a chance to kill your obsolete notifications.</s>

This function is called in both foreground and background, if it's background then you can kill obsolete notifications following step3, if it's foreground well then you don't need to do anything, it send off the queue itself, because it was shown!

Step3:

Inside the function you implemented do:

```<code>UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {deliveredNotifications -> () in
            print("\(deliveredNotifications.count) Delivered notifications-------")
            for notification in deliveredNotifications{
               if (someCondition){
             UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).

              }
            }
        })
</code>```

As for the iPhone time change issue... you should come up with a reasonable  condition and find the notification and remove it...or simply change your notification trigger from a UNCalendarNotificationTrigger to UNTimeIntervalNotificationTrigger. (though again I'm not sure if your timer resets itself or not. I think it shouldn't and you're good).

Body:
So you mean you had a notification named ABC to be triggered in 30 minutes...but then you turned your iPhone off for 3 hours...then turned it on and saw that notification ABC notification even though its time was passed? AFAIK ....the notification will still be there unless you remove it using removeDeliveredNotifications(withIdentifiers:).

Basically call:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).

For more information see this moment of this WWDC video.

Also see this tutorial look for the section "4. Managing Notifications"

As to address your edit:

To be honest I'm not sure...but here's what I think you should do:

I suggest to make the class that creates the notifications:

Step1: Conform to UNUserNotificationCenterDelegate

Step2: Implement:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
 withCompletionHandler completionHandler: @escaping () -> Void) {
}

<s>Now that you turned your device on...This function would get called only if app is in background. There you have a chance to kill your obsolete notifications.</s>

This function is called in both foreground and background, if it's background then you can kill obsolete notifications following step3, if it's foreground well then you don't need to do anything, it send off the queue itself, because it was shown!

Step3:

Inside the function you implemented do:

UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {deliveredNotifications -> () in
            print("\(deliveredNotifications.count) Delivered notifications-------")
            for notification in deliveredNotifications{
               if (someCondition){
             UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).

              }
            }
        })

As for the iPhone time change issue... you should come up with a reasonable  condition and find the notification and remove it...or simply change your notification trigger from a UNCalendarNotificationTrigger to UNTimeIntervalNotificationTrigger. (though again I'm not sure if your timer resets itself or not. I think it shouldn't and you're good).


问:
Move ImageView from one layout to another layout within same activity using animation
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

```<code><LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>
</code>```

答:
Try this:</p>

```<code>public void moveImage(){

    //layout is your Relativelayout
    TransitionManager.beginDelayedTransition(layout);

    RelativeLayout.LayoutParams imageparam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    //add Rule where you want to align it
    imageparam.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);

    imageView.setLayoutParams(imageparam);
}
</code>```

Body:
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

<LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>

Body:
Try this:

public void moveImage(){

    //layout is your Relativelayout
    TransitionManager.beginDelayedTransition(layout);

    RelativeLayout.LayoutParams imageparam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    //add Rule where you want to align it
    imageparam.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);

    imageView.setLayoutParams(imageparam);
}


问:
On clicking the back button Activity is restarting itself
I am starting an activity using intent like this:

```<code>Bundle bundle = new Bundle();
bundle.putParcelableArrayList("datacover",arrayList);
Intent intent = new Intent(TroubleShootActivity.this,SearchResultsActivity.class);
intent.putExtra("bundle",bundle);
startActivity(intent);
</code>```

Im not finishing the activity, but still when i click on back button in the next activity it does not return to the previous activity instead restarts itself.

Code for the other activity:

```<code>public class SearchResultsActivity extends AppCompatActivity implements InnerDetailsFragment.OntroubleshootinneritemsListener,InnerDetailsFragment.OnHandleBack,CompleteDetailsFragment.OnHandleBack {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);
    if(!getResources().getBoolean(R.bool.twoPaneMode)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }else{
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    Bundle bundle=getIntent().getBundleExtra("bundle");

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Inner = new InnerDetailsFragment();
    bundle.putString("val", "search");
    Inner.setArguments(bundle);
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Inner);

    fragmentTransaction.commit();

}

@Override
public void onBackClick(String inner) {
    super.onBackPressed();
}

@Override
public void ontroubleinneritemelected(int position, String heading, CoverageData coverageData) {
    Bundle bundle = new Bundle();
    bundle.putParcelable("coverage",coverageData);

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Detailsf= new CompleteDetailsFragment();
    Detailsf.setArguments(bundle);
    FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Detailsf);
    ft.addToBackStack("completedetails");
    ft.commit();

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
}
</code>```

答:
Use below code...</p>

```<code>  @Override
public void onBackPressed() {
    super.onBackPressed();

    Intent i=new Intent(CurrentActivity.this, PreviousActivity.class);
    startActivity(i);
}
</code>```

Body:
I am starting an activity using intent like this:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("datacover",arrayList);
Intent intent = new Intent(TroubleShootActivity.this,SearchResultsActivity.class);
intent.putExtra("bundle",bundle);
startActivity(intent);

Im not finishing the activity, but still when i click on back button in the next activity it does not return to the previous activity instead restarts itself.

Code for the other activity:

public class SearchResultsActivity extends AppCompatActivity implements InnerDetailsFragment.OntroubleshootinneritemsListener,InnerDetailsFragment.OnHandleBack,CompleteDetailsFragment.OnHandleBack {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_results);
    if(!getResources().getBoolean(R.bool.twoPaneMode)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }else{
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    Bundle bundle=getIntent().getBundleExtra("bundle");

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Inner = new InnerDetailsFragment();
    bundle.putString("val", "search");
    Inner.setArguments(bundle);
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Inner);

    fragmentTransaction.commit();

}

@Override
public void onBackClick(String inner) {
    super.onBackPressed();
}

@Override
public void ontroubleinneritemelected(int position, String heading, CoverageData coverageData) {
    Bundle bundle = new Bundle();
    bundle.putParcelable("coverage",coverageData);

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment Detailsf= new CompleteDetailsFragment();
    Detailsf.setArguments(bundle);
    FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.activity_search_results,Detailsf);
    ft.addToBackStack("completedetails");
    ft.commit();

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}
}

Body:
Use below code...

  @Override
public void onBackPressed() {
    super.onBackPressed();

    Intent i=new Intent(CurrentActivity.this, PreviousActivity.class);
    startActivity(i);
}


问:
Confirm User to Change Route without saving details while editing Angular 2
If the user is editing something and try to change the route without saving details.

in this condition I want to alter the user that 'your changes are not saved do you want to go away'. according to the user can we prevent component to destroy the component.

I try a guard but guard run before ngOnDestroy method run.
So what should I do?

答:
You can use angular CanDeactivate for this purpose .

Link of canDeactivate Angular

https://angular.io/docs/js/latest/api/router/index/CanDeactivate-interface.html
https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

Also a working example @
https://rahulrsingh09.github.io/AngularConcepts/

AdvancedConcepts - > guards


问:
Getting error in passing date value in ajax request
I am trying to pass a Datein ajax request here is my ajax call
I am getting value of Date06/13/2017

```<code>$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + Date,
                cache: false
            }).done(function (response) {

            });
</code>```

and here is my controller

```<code>[HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {
            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }
</code>```

but i am getting this error

```<code>**http://localhost:54850/api/ServiceProvider/GetUpdatedPrice/06/13/2017 404 (Not Found)**
</code>```

does I have to pass date in JSON format or any other thing i am missing ?
please help.

答:
The / symbol in your date value is interpreted as a URL path segments delimiter. Use data field to send any value to your action. For example use

```<code>$.ajax({
  type: 'POST',
  contentType: false,
  async: false,
  url: '/api/ServiceProvider/GetUpdatedPrice/',
  data: {Date: DateValue}
});
</code>```

See jQuery.ajax() documentation and w3schools for details.

Body:
I am trying to pass a Datein ajax request here is my ajax call
I am getting value of Date06/13/2017

$("#txtpdate").on("changeDate", function (e) {
            var Date = $('#txtpdate').val();

            $.ajax({
                type: 'POST',
                contentType: false,
                async: false,
                url: '/api/ServiceProvider/GetUpdatedPrice/' + Date,
                cache: false
            }).done(function (response) {

            });

and here is my controller

[HttpPost]
        [Route("GetUpdatedPrice/{Date}")]
        public async Task<ServiceProviderDocuments> GetUpdatedPrice(DateTime Date)
        {
            return await ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);

        }

but i am getting this error

**http://localhost:54850/api/ServiceProvider/GetUpdatedPrice/06/13/2017 404 (Not Found)**

does I have to pass date in JSON format or any other thing i am missing ?
please help.

Body:
The / symbol in your date value is interpreted as a URL path segments delimiter. Use data field to send any value to your action. For example use

$.ajax({
  type: 'POST',
  contentType: false,
  async: false,
  url: '/api/ServiceProvider/GetUpdatedPrice/',
  data: {Date: DateValue}
});

See jQuery.ajax() documentation and w3schools for details.


问:
how to use wcf and svc in php?
I want to connect to a webservice
Url:

```<code>https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl
</code>```

in c# it's working and I recieve data

```<code>ServiceReference1.BillStateServiceClient bdclinet = new ServiceReference1.BillStateServiceClient();
s=  bdclinet.VerifyBillPaymentWithAddData("4546330305913", "54360101", "10400061", "9768914");
</code>```

but in in php response is null

```<code>$client = new  oapClient("https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl");
$res=  $client->VerifyTransaction("0911229170","1411727361","6010","10780538");
</code>```

What could be the problem?

答:
Have you turned on error exposure on the php side? By default php supresses most exceptions and error messages, wich is a acceptable strategy at runtime.

But during Development you have to explicitly override that behavior or you never get any debugging data.

Unless you manage to extract an actuall error message from SoapClient or VerifyTransaction, we are both just trying to navigate a very Dark space.

Title: how to use wcf and svc in php?

Body:
I want to connect to a webservice
Url:

https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl

in c# it's working and I recieve data

ServiceReference1.BillStateServiceClient bdclinet = new ServiceReference1.BillStateServiceClient();
s=  bdclinet.VerifyBillPaymentWithAddData("4546330305913", "54360101", "10400061", "9768914");

but in in php response is null

$client = new  oapClient("https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl");
$res=  $client->VerifyTransaction("0911229170","1411727361","6010","10780538");

What could be the problem?


问:
How to? PHP & MySQL sortdata in a function
I am stuck in writing a PHP function. What I need to do is pass on about 10 - 12 ID into an array and then sort them by name in mysql database and then print some statements. I got this far where I manually add an ID number and it prints the information I need but at this point I have to sort the data before using those ID numbers.

Here is what I have done so far.

```<code><?php
function print_software_info($id) {
  $appinfo = "SELECT * FROM `appinfo` WHERE `id` = ".intval($id);
  $rt = mysql_query($appinfo) or die(mysql_error("Could not retrieve database information"));
  echo $rt['name'];
  echo $rt['image'];
}
?>
<?php
print_software_info(217);
print_software_info(179);
print_software_info(8);
?>
</code>```

答:
with

```<code>$ids = array(13, 14, 250, ... );
</code>```

First (optional for now, but keep in mine) make sure they're all integer (sanitize)

```<code>$ids = array_map('intval',$ids);
</code>```

You need to build a query like this

```<code>$q = "SELECT * FROM `appinfo` WHERE `id` IN (". implode(',',$ids) ." ) ORDER BY name";

$result = mysql_query($q);
</code>```

Then go through each rows..

```<code>while ($row = mysql_fetch_object($result)) {
    echo $row->name;
    echo $row->image;
}
</code>```

Body:
I am stuck in writing a PHP function. What I need to do is pass on about 10 - 12 ID into an array and then sort them by name in mysql database and then print some statements. I got this far where I manually add an ID number and it prints the information I need but at this point I have to sort the data before using those ID numbers.

Here is what I have done so far.

<?php
function print_software_info($id) {
  $appinfo = "SELECT * FROM `appinfo` WHERE `id` = ".intval($id);
  $rt = mysql_query($appinfo) or die(mysql_error("Could not retrieve database information"));
  echo $rt['name'];
  echo $rt['image'];
}
?>
<?php
print_software_info(217);
print_software_info(179);
print_software_info(8);
?>

Body:
with

$ids = array(13, 14, 250, ... );

First (optional for now, but keep in mine) make sure they're all integer (sanitize)

$ids = array_map('intval',$ids);

You need to build a query like this

$q = "SELECT * FROM `appinfo` WHERE `id` IN (". implode(',',$ids) ." ) ORDER BY name";

$result = mysql_query($q);

Then go through each rows..

while ($row = mysql_fetch_object($result)) {
    echo $row->name;
    echo $row->image;
}


问:
How to test private field is set to supplied value using public method in JUnit?
I have a class:

```<code>public class MyEncryptor {

    private StringEncryptor stringEncryptor; // this is an interface ref

    public void setStringEncryptor(StringEncryptor stringEncryptorImpl) {

        if(condition){
            this.stringEncryptor = stringEncryptorImpl;
        }

    }
}
</code>```

When Testing in JUnit for method setStringEncryptor, i want to test if instance value stringEncryptor is set to what i've supplied in parameter as implementation? or i'm going the wrong way for testing this method?

Below is my failed attempt in a junit test method:

```<code>MyEncryptor decryptor = new MyEncryptor ();

        StringEncryptor spbe = new StandardPBEStringEncryptor();
        decryptor.setStringEncryptor(spbe);

        Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
        f.setAccessible(true);

        Assert.assertSame(f, spbe);
</code>```

I want to test that stringEnctyptor is set to spbe in junit

答:
The unit test you have given, fails because you attempt to compare a Field instance and a StandardPBEStringEncryptor instance using assertSame. What you should do is: assertSame(f.get(decryptor), StandardPBEStringEncryptor)

Notice that we use the Field::get method to retrieve the field's value and the argument we give is the instance whose field value we want to retrieve.

However, regardless of that, unit testing a setter type method is redundant and simply adds extra testing code and testing time for no reason.

Body:
I have a class:

public class MyEncryptor {

    private StringEncryptor stringEncryptor; // this is an interface ref

    public void setStringEncryptor(StringEncryptor stringEncryptorImpl) {

        if(condition){
            this.stringEncryptor = stringEncryptorImpl;
        }

    }
}

When Testing in JUnit for method setStringEncryptor, i want to test if instance value stringEncryptor is set to what i've supplied in parameter as implementation? or i'm going the wrong way for testing this method?

Below is my failed attempt in a junit test method:

MyEncryptor decryptor = new MyEncryptor ();

        StringEncryptor spbe = new StandardPBEStringEncryptor();
        decryptor.setStringEncryptor(spbe);

        Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
        f.setAccessible(true);

        Assert.assertSame(f, spbe);

I want to test that stringEnctyptor is set to spbe in junit


答:
Here  you assert that the java.lang.reflect.Field stringEncryptor is the same object than the StringEncryptor object you create for your test :

```<code>StringEncryptor spbe = new StandardPBEStringEncryptor();
...
Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
f.setAccessible(true);
Assert.assertSame(f, spbe);
</code>```

These are two distinct objects of two distinct and no related classes.

You should first retrieve the value associated to the field :

```<code> Object value = f.get(spbe);
</code>```

and then compare the objects :

```<code>Assert.assertSame(value, spbe);
</code>```

But anyway I don't think it is the good way.

To test a code, the implementation should be testable.

Doing reflection to test the code should be done only if we have really not the choice.

A natural way to test your code is providing a method to get the actual StringEncryptor field.

```<code>public StringEncryptor getStringEncryptor(){
     return stringEncryptor;
}
</code>```

In this way you could assert the field value in a straight way.

Title: How to test private field is set to supplied value using public method in JUnit?

Body:
Here  you assert that the java.lang.reflect.Field stringEncryptor is the same object than the StringEncryptor object you create for your test :

StringEncryptor spbe = new StandardPBEStringEncryptor();
...
Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
f.setAccessible(true);
Assert.assertSame(f, spbe);

These are two distinct objects of two distinct and no related classes.

You should first retrieve the value associated to the field :

 Object value = f.get(spbe);

and then compare the objects :

Assert.assertSame(value, spbe);

But anyway I don't think it is the good way.

To test a code, the implementation should be testable.

Doing reflection to test the code should be done only if we have really not the choice.

A natural way to test your code is providing a method to get the actual StringEncryptor field.

public StringEncryptor getStringEncryptor(){
     return stringEncryptor;
}

In this way you could assert the field value in a straight way.


问:
Camera feed goes black once entering VR Mode in A-Frame
Here's my code below, I'm fairly new to using a-frame and it's pretty interesting, and I can't seem to work out why I'm having the issue, can someone more experienced help me out?

var errorCallback = function(e) {
  console.log('Not working!', e);
};

navigator.getUserMedia({
  video: true,
  audio: true
}, function(localMediaStream) {
  var video = document.querySelector('video');
  video.src = window.URL.createObjectURL(localMediaStream);

  video.onloadedmetadata = function(e) {
    // Ready to go. Do some stuff.
  };
}, errorCallback);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>video {
  width: 100% !important;
  max-width: 100% !important;
  height: auto !important;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1000;
}</code>```

<video autoplay></video>

```

The camera works when you aren't in VR mode, but when you do enter VR mode in a-frame, the background becomes black instead of showing the camera feed. Does anyone know why? I've asked for help on other websites before, but nothings helped.

答:
from what i see You create a <video> element OVER the aframe canvas. When entering vr mode, You see only the aframe canvas, which is why your 100%/100% video probably dissapears.

I think You should make a  element, and set the "src" as Your localMediaStream. Moreover You'd need a object to texture with your video.
 Not sure if it will take it though, never tried before. You should check out https://github.com/jeromeetienne/AR.js/

Btw it seems Your method is quite deprecated:
https://developer.mozilla.org/pl/docs/Web/API/Navigator/getUserMedia

it seems you should use navigator.mediaDevices.getUserMedia() now:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

UPDATE: I made a small pen which manages to texture a plane with my camera feed, tried on firefox, works great, my chrome seems to disable userMedia when called within plunker or codepen. Seems to work when in VRMODE both on my pc, and  firefox for android. The plane on my phone is crooked 4 some reason, i guess it has a shitty camera and no memory :p

Feel free to modify my pen:
https://codepen.io/gftruj/pen/jwEyQN

The css part is a leftover, better make sure that video feed has the power of two dimensions. As i see on the aframe website, i should put the video inside the  element: https://aframe.io/docs/0.5.0/primitives/a-video.html , though putting it as a  src seems to work fine.

Body:
Here's my code below, I'm fairly new to using a-frame and it's pretty interesting, and I can't seem to work out why I'm having the issue, can someone more experienced help me out?

var errorCallback = function(e) {
  console.log('Not working!', e);
};

navigator.getUserMedia({
  video: true,
  audio: true
}, function(localMediaStream) {
  var video = document.querySelector('video');
  video.src = window.URL.createObjectURL(localMediaStream);

  video.onloadedmetadata = function(e) {
    // Ready to go. Do some stuff.
  };
}, errorCallback);

video {
  width: 100% !important;
  max-width: 100% !important;
  height: auto !important;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1000;
}

<video autoplay></video>

The camera works when you aren't in VR mode, but when you do enter VR mode in a-frame, the background becomes black instead of showing the camera feed. Does anyone know why? I've asked for help on other websites before, but nothings helped.

Body:
from what i see You create a <video> element OVER the aframe canvas. When entering vr mode, You see only the aframe canvas, which is why your 100%/100% video probably dissapears.

I think You should make a <a-video> element, and set the "src" as Your localMediaStream. Moreover You'd need a object to texture with your video.
 Not sure if it will take it though, never tried before. You should check out https://github.com/jeromeetienne/AR.js/

Btw it seems Your method is quite deprecated:
https://developer.mozilla.org/pl/docs/Web/API/Navigator/getUserMedia

it seems you should use navigator.mediaDevices.getUserMedia() now:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

UPDATE: I made a small pen which manages to texture a plane with my camera feed, tried on firefox, works great, my chrome seems to disable userMedia when called within plunker or codepen. Seems to work when in VRMODE both on my pc, and  firefox for android. The plane on my phone is crooked 4 some reason, i guess it has a shitty camera and no memory :p

Feel free to modify my pen:
https://codepen.io/gftruj/pen/jwEyQN

The css part is a leftover, better make sure that video feed has the power of two dimensions. As i see on the aframe website, i should put the video inside the <a-video> element: https://aframe.io/docs/0.5.0/primitives/a-video.html , though putting it as a <a-plane> src seems to work fine.


问:
Folder name with space in SQL*Plus script
I wrote the following script to create a new folder

```<code>column mn new_value _mn;
select '\\common\jds\Daily report\DailyReport2017\\'||tochar(sysdate,'mon')||'\';
host mkdir &_mn;
</code>```

but it throws error

```<code>'The specified path is invalid.
Error occurred while processing \\common\jdfs\Daily',
</code>```

since there is space in the name

How can I create the folder

答:
Unlike in Windows, In Linux the default folder separator is the / and the spaces must be escaped with a backslash (\). Therefore I would try to use this instead:

```<code>select '/common/jds/Daily\ report/DailyReport2017/' || tochar(sysdate,'mon')  || '/';
</code>```

Body:
I wrote the following script to create a new folder

column mn new_value _mn;
select '\\common\jds\Daily report\DailyReport2017\\'||tochar(sysdate,'mon')||'\';
host mkdir &_mn;

but it throws error

'The specified path is invalid.
Error occurred while processing \\common\jdfs\Daily',

since there is space in the name

How can I create the folder

Body:
Unlike in Windows, In Linux the default folder separator is the / and the spaces must be escaped with a backslash (\). Therefore I would try to use this instead:

select '/common/jds/Daily\ report/DailyReport2017/' || tochar(sysdate,'mon')  || '/';


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答:
The problem is that as you remove the items from the list, the other items change positions in it, resulting in skipping some of them as the loop keeps on iterating. Try with more elements and you will see how the skipping follows a pattern.

To avoid this you need to iterate the list differently and in my opinion backwards.

A way to do it could be the following:

```<code>    i = len(test)-1
    while (i>=0):
        del test[i]
        i-=1
    print(test)
</code>```

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

Body:
The problem is that as you remove the items from the list, the other items change positions in it, resulting in skipping some of them as the loop keeps on iterating. Try with more elements and you will see how the skipping follows a pattern.

To avoid this you need to iterate the list differently and in my opinion backwards.

A way to do it could be the following:

    i = len(test)-1
    while (i>=0):
        del test[i]
        i-=1
    print(test)


问:
How to yield the elements in an iterator within a new iterator?
I need an iterator over all leaves in my JSON object. So I wrote this function

```<code>rec = {'a': {'b': [{'c': {'d': [{'e': 'x1','f': 'x2'}],'g': 'x3'}}],'h': 'x4','i': 'x5','j': [{'k': 'x6'}],'l': [{'m': {'n': 'x7'}}]}}

def yield_leaves(rec, lbl = ''):
  if isinstance(rec, dict):
    for key, value in rec.items():
        for to_yield in yield_leaves(value, key):
            yield to_yield
  if isinstance(rec, list):
    for value in rec:
        for to_yield in yield_leaves(value, lbl):
            yield to_yield
  if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl

print(list(yield_leaves(rec)))
>>> [('x5', 'i'), ('x4', 'h'), ('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x6', 'k'), ('x7', 'n')]
</code>```

But I think some code is redundant. The following line

```<code>for to_yield in yield_leaves(value, key):
        yield to_yield
</code>```

It iterates over an iterator and returns the values as part of an iterator.

Do you know a more efficient way to code this?

答:
Try to use yield from instead of for

```<code>yeild from yield_leaves(value, key)
</code>```

P.S. If you are using python >3.3

Body:
I need an iterator over all leaves in my JSON object. So I wrote this function

rec = {'a': {'b': [{'c': {'d': [{'e': 'x1','f': 'x2'}],'g': 'x3'}}],'h': 'x4','i': 'x5','j': [{'k': 'x6'}],'l': [{'m': {'n': 'x7'}}]}}

def yield_leaves(rec, lbl = ''):
  if isinstance(rec, dict):
    for key, value in rec.items():
        for to_yield in yield_leaves(value, key):
            yield to_yield
  if isinstance(rec, list):
    for value in rec:
        for to_yield in yield_leaves(value, lbl):
            yield to_yield
  if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl

print(list(yield_leaves(rec)))
>>> [('x5', 'i'), ('x4', 'h'), ('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x6', 'k'), ('x7', 'n')]

But I think some code is redundant. The following line

for to_yield in yield_leaves(value, key):
        yield to_yield

It iterates over an iterator and returns the values as part of an iterator.

Do you know a more efficient way to code this?

Body:
Try to use yield from instead of for

yeild from yield_leaves(value, key)

P.S. If you are using python >3.3


问:
How to calculate t.test on grouped data based on given list of vectors with two values
I have the following data frame:

library(tidyverse)

dat <- tribble(
 ~sample, ~rep, ~area,
 "S1", "01", 100,
 "S1", "02", 200,
 "S1", "01", 300,
 "S2", "01", 10,
 "S2", "02", 20,
 "S2", "02", 30,
 "S3", "01", 1.2,
 "S3", "02", 2.3,
 "S3", "02", 3.1
)

dat
#> # A tibble: 9 x 3
#>   sample   rep  area
#>    <chr> <chr> <dbl>
#> 1     S1    01 100.0
#> 2     S1    02 200.0
#> 3     S1    01 300.0
#> 4     S2    01  10.0
#> 5     S2    02  20.0
#> 6     S2    02  30.0
#> 7     S3    01   1.2
#> 8     S3    02   2.3
#> 9     S3    02   3.1
```

<p>What I want to do is to create a function that takes a list of vectors with
a paired value and then calculate the P-value derived from t.test of <code>area</code> column.</p>

<p>Fore example given this list:</p>

<pre class="lang-r prettyprint-override"><code>wanted_pairs <- list(c("S1","S2"), c("S2","S3"))
</code>```

We would like to generate this data frame:

  S1 S2  0.0878746
  S2 S3  0.07564237
```

<p>Manually, the above P-values are calculated with:</p>

<pre class="lang-r prettyprint-override"><code>t.test(dat[dat$sample=="S1",]$area, dat[dat$sample=="S2",]$area)$p.value
t.test(dat[dat$sample=="S2",]$area, dat[dat$sample=="S3",]$area)$p.value
</code>```

How can I achieve that?

答:
We can use a loop</p>

```<code>library(dplyr)
lapply(wanted_pairs, function(x)
      dat %>%
         filter(sample %in% x) %>%
         summarise(sample1 = unique(sample)[1], sample2 = unique(sample)[2],
                    pval = t.test(area[sample == sample1],
                              area[sample == sample2])$p.value)) %>%
      bind_rows()
# A tibble: 2 x 3
#  sample1 sample2      pval
#    <chr>   <chr>     <dbl>
#1      S1      S2 0.0878746
#2      S2      S3 0.0897509
</code>```

Body:
I have the following data frame:

library(tidyverse)

dat <- tribble(
 ~sample, ~rep, ~area,
 "S1", "01", 100,
 "S1", "02", 200,
 "S1", "01", 300,
 "S2", "01", 10,
 "S2", "02", 20,
 "S2", "02", 30,
 "S3", "01", 1.2,
 "S3", "02", 2.3,
 "S3", "02", 3.1
)

dat
#> # A tibble: 9 x 3
#>   sample   rep  area
#>    <chr> <chr> <dbl>
#> 1     S1    01 100.0
#> 2     S1    02 200.0
#> 3     S1    01 300.0
#> 4     S2    01  10.0
#> 5     S2    02  20.0
#> 6     S2    02  30.0
#> 7     S3    01   1.2
#> 8     S3    02   2.3
#> 9     S3    02   3.1

What I want to do is to create a function that takes a list of vectors with
a paired value and then calculate the P-value derived from t.test of area column.

Fore example given this list:

wanted_pairs <- list(c("S1","S2"), c("S2","S3"))

We would like to generate this data frame:

  S1 S2  0.0878746
  S2 S3  0.07564237

Manually, the above P-values are calculated with:

t.test(dat[dat$sample=="S1",]$area, dat[dat$sample=="S2",]$area)$p.value
t.test(dat[dat$sample=="S2",]$area, dat[dat$sample=="S3",]$area)$p.value

How can I achieve that?

Body:
We can use a loop

library(dplyr)
lapply(wanted_pairs, function(x)
      dat %>%
         filter(sample %in% x) %>%
         summarise(sample1 = unique(sample)[1], sample2 = unique(sample)[2],
                    pval = t.test(area[sample == sample1],
                              area[sample == sample2])$p.value)) %>%
      bind_rows()
# A tibble: 2 x 3
#  sample1 sample2      pval
#    <chr>   <chr>     <dbl>
#1      S1      S2 0.0878746
#2      S2      S3 0.0897509


问:
GCC optimization issues and behavior
I have an optimisation issue with gcc running on Eclipse.
I have a program which runs well with -O0 optimization level, but I need to turn ON other levels of optimization because my software uses too much flash memory space.
But when I use -O1 optimization level (for instance) my code doesn't work anymore and I need to do strange modifications as described below with the UART peripheral managing functions.

Code running well with -O0

```<code>void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase);
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}
</code>```

Code with modification for -O1

```<code>void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase)
   {
      Dummy = Dummy == 0 ? 1 : 0;
   }
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}
</code>```

I would like to know why gcc is forcing me to do this kind of modifications, do I need to change my "way of think" about the design of my code. Or is there an explanation with this behavior ?

Thanks for your advices.

答:
With optimization turned on, the compiler tries to save as much as it can on redundant code. This line:

while(end_of_transmission_flag == false);

continuously checks a variable which is never modified (from the point of view of the compiler). Moreover, the line does nothing (again from the point of view of the compiler). In reality the line does something: it waits until the flag changes state. But the compiler is not smart enough to understand this. So you have to help it by declaring the flag variable as volatile. Doing this, you warn the compiler that the variable can change state behind the scene (i.e., in interrupt). The compiler now knows that it can not rely on the fact that the variable seems to be never modified - it can not "cache" its value to produce faster code.

Please note that, even so, the whole line still does nothing (there is no code to execute inside the loop); but normally, in this situation, the compiler understands that the loop must be executed anyway.

Your trick "Dummy = Dummy == 0 ? 1 : 0;" seems to have some effect on the compiler, and I can not explain it to myself. But, as you already thought, it seems really strange. The trick addresses the problem of a statement which does nothing, forcing the compiler to generate code inside the loop. But this is only half of the problem and, anyway, a very smart compiler could think "why should I compile code to assign a value to a variable which is never used? When such things happen, the compiler often warns you with something like "Warning: value assigned to xxxxx is never used".

To conclude, declare end_of_transmission_flag as volatile.

Just a thought aside: many programming languages are not born to cope well with hardware (port I/O, interrupts, DMA and so on), and C is no exception: it forces the programmer to strange declarations, pragmas, compilation flags and so on. On the other hand, a line like "while(end_of_transmission_flag == false);" is kind of ambiguous; the real line should read something like "wait_until_true(end_of_transmission_flag);". Things like this could be offered by the language, or by the environment (via macros, libraries, hardware support or whatever).

Title: GCC optimization issues and behavior

Body:
I have an optimisation issue with gcc running on Eclipse.
I have a program which runs well with -O0 optimization level, but I need to turn ON other levels of optimization because my software uses too much flash memory space.
But when I use -O1 optimization level (for instance) my code doesn't work anymore and I need to do strange modifications as described below with the UART peripheral managing functions.

Code running well with -O0

void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase);
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}

Code with modification for -O1

void function(...)
{
   // Send char one by one on UART peripheral
   UART_put_char(...)

   // Wait end of transmission on UART
   while(end_of_transmission_flag == flase)
   {
      Dummy = Dummy == 0 ? 1 : 0;
   }
}

void UART_TxCompleteCallback()
{
   // Change flag state
   end_of_transmission_flag = true;
}

I would like to know why gcc is forcing me to do this kind of modifications, do I need to change my "way of think" about the design of my code. Or is there an explanation with this behavior ?

Thanks for your advices.


问:
Android - Choose Image from Gallery and store it in a File type variable
I am a new to Android Development. I wish to select an image or a video from the Gallery of an Android Device. Store it in a variable of typeFile. I am doing this, since I need to upload the image/video on dropbox using the Android API from my application. The constructor takes in the fourth parameter of the type File. I am not sure, what to pass as a file since all the examples I searched display the image chosen in an ImageView by using the url and making a bitmap.

```<code>imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
</code>```

Here is the code, I have.

```<code>final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//to get image and videos, I used a */"
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
    Uri selectedImageUri = data.getData();
    imagepath = getPath(selectedImageUri);
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(projection[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();
    yourSelectedImage = BitmapFactory.decodeFile(filePath);
    return cursor.getString(column_index);
}
</code>```

答:
Try this

You can try this also

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data)
{

    if (requestCode == 1 && resultCode == RESULT_OK && data != null)
    {
        File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
 //You will get file path of captured camera image
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        iv_profile.setImageBitmap(photo);
    }
}
</code>```

Body:
I am a new to Android Development. I wish to select an image or a video from the Gallery of an Android Device. Store it in a variable of typeFile. I am doing this, since I need to upload the image/video on dropbox using the Android API from my application. The constructor takes in the fourth parameter of the type File. I am not sure, what to pass as a file since all the examples I searched display the image chosen in an ImageView by using the url and making a bitmap.

imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

Here is the code, I have.

final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
//to get image and videos, I used a */"
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
    Uri selectedImageUri = data.getData();
    imagepath = getPath(selectedImageUri);
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(projection[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();
    yourSelectedImage = BitmapFactory.decodeFile(filePath);
    return cursor.getString(column_index);
}

Body:
Try this

You can try this also

public void onActivityResult(int requestCode, int resultCode, Intent data)
{

    if (requestCode == 1 && resultCode == RESULT_OK && data != null)
    {
        File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
 //You will get file path of captured camera image
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        iv_profile.setImageBitmap(photo);
    }
}


问:
Java return type generic
I'm newbie in using generic in java, i have simple method that i would like to return any type from that, this method return other class getters methods, for example i have channels class and that have getChannelId() method, i want to return that from this method:

```<code>@SuppressWarnings("unchecked")
public <T extends Channels> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId();
        break;
        case title:
            return (T) channel.getChannelTitle();
            break;
    }
    return null;
}
</code>```

getId is int and getChannelTitle is string, how can i fix this method to return any type?

in my code channel is instance of Channels class, Thanks in advance

答:
You can create property wrapper which will hold the value in string data format when required it will convert to a specific data type.

```<code>public class MyProperty {
private String stringVal;

public MyProperty(String stringVal) {
    this.stringVal = stringVal;
}

public Integer getInteger() throws IllegalArgumentException {
    return integerValue.getValue();
}

public String getString() {
    return stringValue.getValue();
}

private PropertyValue<String> stringValue = new PropertyValue<String>() {
    protected String parse(String rep) {
        return rep;
    }
};
private PropertyValue<Integer> integerValue = new PropertyValue<Integer>() {
    protected Integer parse(String rep) throws NumberFormatException {
        return Integer.valueOf(rep);
    }
};

private abstract class PropertyValue<T> {
    private T value;

    protected abstract T parse(String rep) throws Exception;

    public T getValue() throws IllegalArgumentException {
        try {
            value = (stringValue == null) ? null : parse(stringVal);
        } catch (Exception e) {
            value = null;
        }
        return value;
    }
}
</code>```

}

you can make specialize class or one class having the access method to get the value with specified data type

```<code>   @SuppressWarnings("unchecked")
    public  MyProperty getChannelColumn(ChannelContentModel.channelColumns column) {
        switch (column) {
            case id:
                return new MyProperty(channel.getId());//
            break;
            case title:
                return new MyProperty(channel.getChannelTitle());
                break;
        }
        return null;
    }
</code>```

Title: Java return type generic

Body:
I'm newbie in using generic in java, i have simple method that i would like to return any type from that, this method return other class getters methods, for example i have channels class and that have getChannelId() method, i want to return that from this method:

@SuppressWarnings("unchecked")
public <T extends Channels> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId();
        break;
        case title:
            return (T) channel.getChannelTitle();
            break;
    }
    return null;
}

getId is int and getChannelTitle is string, how can i fix this method to return any type?

in my code channel is instance of Channels class, Thanks in advance

Body:
You can create property wrapper which will hold the value in string data format when required it will convert to a specific data type.

public class MyProperty {
private String stringVal;

public MyProperty(String stringVal) {
    this.stringVal = stringVal;
}

public Integer getInteger() throws IllegalArgumentException {
    return integerValue.getValue();
}

public String getString() {
    return stringValue.getValue();
}

private PropertyValue<String> stringValue = new PropertyValue<String>() {
    protected String parse(String rep) {
        return rep;
    }
};
private PropertyValue<Integer> integerValue = new PropertyValue<Integer>() {
    protected Integer parse(String rep) throws NumberFormatException {
        return Integer.valueOf(rep);
    }
};

private abstract class PropertyValue<T> {
    private T value;

    protected abstract T parse(String rep) throws Exception;

    public T getValue() throws IllegalArgumentException {
        try {
            value = (stringValue == null) ? null : parse(stringVal);
        } catch (Exception e) {
            value = null;
        }
        return value;
    }
}

}

you can make specialize class or one class having the access method to get the value with specified data type

   @SuppressWarnings("unchecked")
    public  MyProperty getChannelColumn(ChannelContentModel.channelColumns column) {
        switch (column) {
            case id:
                return new MyProperty(channel.getId());//
            break;
            case title:
                return new MyProperty(channel.getChannelTitle());
                break;
        }
        return null;
    }


问:
How to many2many Odoo domain filter
I have supply.conditions and purchase.request models. In purchase.request I have many2many relation field:

```<code>supply_ids  = fields.Many2many(comodel_name='supply.conditions', relation='purchase_supply_rel', column1='purchase_requests_id', column2='supply_conditions_id',string='Supply Conditions')
</code>```

In supply.conditions model I need to add domain filter to check that supply.conditions id is in purchase_supply_rel table. I want to change SQL:

```<code>select * from supply_conditions a
inner join purchase_supply_rel b
on a.id = b.supply_conditions_id
</code>```

to many2many relation domain.

I tied to make domain filter like that:

```<code>[('id', '=', purchase_supply_rel.supply_conditions_id)]
</code>```

But I got an error:

```<code>ValueError: "name 'purchase_supply_rel' is not defined" while evaluating
</code>```

What is wrong? Do I have to have the same many2many relation in my supply.conditions model?

答:
For filtering Many2many field you can use

```<code><field name="m2m_field" domain="[('field', '=', True)]"/>
</code>```

So using domain [('id', 'in', ids)] will filter related objects as usual

Title: How to many2many Odoo domain filter

Body:
I have supply.conditions and purchase.request models. In purchase.request I have many2many relation field:

supply_ids  = fields.Many2many(comodel_name='supply.conditions', relation='purchase_supply_rel', column1='purchase_requests_id', column2='supply_conditions_id',string='Supply Conditions')

In supply.conditions model I need to add domain filter to check that supply.conditions id is in purchase_supply_rel table. I want to change SQL:

select * from supply_conditions a
inner join purchase_supply_rel b
on a.id = b.supply_conditions_id

to many2many relation domain.

I tied to make domain filter like that:

[('id', '=', purchase_supply_rel.supply_conditions_id)]

But I got an error:

ValueError: "name 'purchase_supply_rel' is not defined" while evaluating

What is wrong? Do I have to have the same many2many relation in my supply.conditions model?

Body:
For filtering Many2many field you can use

<field name="m2m_field" domain="[('field', '=', True)]"/>

So using domain [('id', 'in', ids)] will filter related objects as usual


问:
Swift Filter and Map over array of structs
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

```<code>// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map
</code>```

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?

答:
So as I understood you need to filter your array
something like

```<code>let filteredData = myData.filter({$0.tag != sender.tag})
</code>```

then you use reduce to calculate

```<code>let sumAll = filterdData.reduce(0, {$0.value + $1.value})
</code>```

Body:
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?

Body:
So as I understood you need to filter your array
something like

let filteredData = myData.filter({$0.tag != sender.tag})

then you use reduce to calculate

let sumAll = filterdData.reduce(0, {$0.value + $1.value})


问:
Please find below code to count chars in given string. I want to know my approach is right or what is the best way?
```<code>public String getCharCntStr(String inputStr){
        List<Character> alreadyCntChrs=new ArrayList<>();//store already counted chars
        StringBuilder outputStr=new StringBuilder();
        for(int i=0;i<inputStr.length();i++){
            char a=inputStr.charAt(i);
            if(alreadyCntChrs.contains(a)){
                continue;
            }
            int count=0;
            for(int j=i;i<inputStr.length();j++){// to find count of a char in string
                if(a==inputStr.charAt(j))
                    count++;
            }
            outputStr.append(a).append(count);
            alreadyCntChrs.add(a);
        }
        return outputStr.toString();
    }
</code>```

example input: sanaullahshaikh
 ouput: s2a3n1u1l2h3i1k1
Please suggest me the best way to do.

答:
Your code is good but what i have implemented will give you some modifications

```<code> static void characterCount(String inputString) {
        //Creating a HashMap containing char as a key and occurrences as  a value
        HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        //Converting given string to char array
        char[] strArray = inputString.toCharArray();
        //checking each char of strArray
        for (char c : strArray) {
            if (charCountMap.containsKey(c)) {
                //If char is present in charCountMap, incrementing it's count by 1
                charCountMap.put(c, charCountMap.get(c) + 1);
            } else {
                //If char is not present in charCountMap,
                //putting this char to charCountMap with 1 as it's value
                charCountMap.put(c, 1);
            }
        }
        //Printing the charCountMap
        System.out.println(charCountMap);
    }
</code>```

Thanks and Regards.

Body:
public String getCharCntStr(String inputStr){
        List<Character> alreadyCntChrs=new ArrayList<>();//store already counted chars
        StringBuilder outputStr=new StringBuilder();
        for(int i=0;i<inputStr.length();i++){
            char a=inputStr.charAt(i);
            if(alreadyCntChrs.contains(a)){
                continue;
            }
            int count=0;
            for(int j=i;i<inputStr.length();j++){// to find count of a char in string
                if(a==inputStr.charAt(j))
                    count++;
            }
            outputStr.append(a).append(count);
            alreadyCntChrs.add(a);
        }
        return outputStr.toString();
    }

example input: sanaullahshaikh
 ouput: s2a3n1u1l2h3i1k1
Please suggest me the best way to do.

Body:
Your code is good but what i have implemented will give you some modifications

 static void characterCount(String inputString) {
        //Creating a HashMap containing char as a key and occurrences as  a value
        HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        //Converting given string to char array
        char[] strArray = inputString.toCharArray();
        //checking each char of strArray
        for (char c : strArray) {
            if (charCountMap.containsKey(c)) {
                //If char is present in charCountMap, incrementing it's count by 1
                charCountMap.put(c, charCountMap.get(c) + 1);
            } else {
                //If char is not present in charCountMap,
                //putting this char to charCountMap with 1 as it's value
                charCountMap.put(c, 1);
            }
        }
        //Printing the charCountMap
        System.out.println(charCountMap);
    }

Thanks and Regards.


问:
How long should Golang graceful HTTP shutdown take?
According to https://golang.org/pkg/net/http/#Server.Shutdown

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, then the context's error is returned.

What does "then waiting indefinitely for connections to return to idle and then shut down" mean exactly? Should I expect that the context timeout should typically occur before this graceful shutdown finishes, given a timeout on the order of seconds?

答:
waiting indefinitely for connections to return to idle

refers to HTTP Handlers that have already been called as part of incoming connections. All these handlers need to be closed / returned, usually by calling w.Write or w.WriteHeader


问:
I want change bezier curve's endpoint
Sorry for my paint:

I want change bezier curve's endpoint

start from s point with control points(c1, c2) to end point

when point arrive at changepoint(pink), I want change endpoint and

get the new path for new endpoint smoothly

How ? help me..

答:
So if I got it right you want to change control point E but still want that your curve goes through the same pink point. There are several ways to achieve this. For example you could duplicate the change point as a control point. For cubics using triple control point will force the curve to go through it. for more info on stacking up cubics see:

piecewise cubics call sequence

However using approximation polynomials will be always problematic for this kind of task. Why not use interpolation polynomial instead. So convert BEZIER control points to interpolation cubic (so that change point is one of the control points) then change E and convert back to BEZIER control points (in case you can render only BEZIER). The transformation between BEZIER and interpolation cubics is here:

BEZIER vs. interpolation cubic

Also as your change point is not one of the control points then you can make it one by:

Split a cubic bezier curve at multiple points

Title: I want change bezier curve's endpoint