问:
Multiple @EnableGlobalMethodSecurity annotations
If multiple configuration classes have the @EnableGlobalMethodSecurity annotation, then is one used and one ignored?

In a spring boot application there are two instances of WebSecurityConfigurerAdapter- one is annotated with @EnableGlobalMethodSecurity(secured = true), and another has @EnableGlobalMethodSecurity(prePostEnabled = true).  But so far I cannot get the @PreAuthorize annotation to work. With only one annotation I can see verify it is being applied.
eg

```<code>@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class FirstConfigurer extends WebSecurityConfigurerAdapter {
...

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class AnotherConfiguration extends WebSecurityConfigurerAdapter{
...
</code>```

Does spring-security support multiple configuration classes being annotated with @EnableGlobalMethodSecurity?

Is there a way to see what has actually been configured?

答:
I debug it (into springframework source) to see what it was being load and in which order.

I had a situation similar where I had a library (which I couldn't change) that configures @EnableGlobalMethodSecurity(securedEnabled = true).

And I wanted to use @EnableGlobalMethodSecurity(prePostEnabled=true)

What was happening it was that the library configurations was being loaded over my configuration (only the last one being loaded would be used)

I tried to use @Order(Ordered.LOWEST_PRECEDENCE) and @EnableGlobalMethodSecurity(order = Ordered.HIGHEST_PRECEDENCE, ... but with no effect.

My solution was to set the order that I wanted by importing the library configuration at my configuration like this:

```<code>@Import(LibraryConfig.class)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MyConfiguration extends GlobalMethodSecurityConfiguration {
    /* my code */
}
</code>```

PLUS: I found out that my situation is even more complicated, since the library that I'm using configures @EnableGlobalMethodSecurity(securedEnabled = true) more than once.
So the behave was a bit different and to force the use of my configurations I had to override the implementations of this methods:

```<code>@Bean
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
    return super.methodSecurityMetadataSource();
}

@Bean
public MethodInterceptor methodSecurityInterceptor() throws Exception {
    return super.methodSecurityInterceptor();
}

@Bean
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() {
    return super.preInvocationAuthorizationAdvice();
}
</code>```

Body:
If multiple configuration classes have the @EnableGlobalMethodSecurity annotation, then is one used and one ignored?

In a spring boot application there are two instances of WebSecurityConfigurerAdapter- one is annotated with @EnableGlobalMethodSecurity(secured = true), and another has @EnableGlobalMethodSecurity(prePostEnabled = true).  But so far I cannot get the @PreAuthorize annotation to work. With only one annotation I can see verify it is being applied.
eg

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class FirstConfigurer extends WebSecurityConfigurerAdapter {
...

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class AnotherConfiguration extends WebSecurityConfigurerAdapter{
...

Does spring-security support multiple configuration classes being annotated with @EnableGlobalMethodSecurity?

Is there a way to see what has actually been configured?

Body:
I debug it (into springframework source) to see what it was being load and in which order.

I had a situation similar where I had a library (which I couldn't change) that configures @EnableGlobalMethodSecurity(securedEnabled = true).

And I wanted to use @EnableGlobalMethodSecurity(prePostEnabled=true)

What was happening it was that the library configurations was being loaded over my configuration (only the last one being loaded would be used)

I tried to use @Order(Ordered.LOWEST_PRECEDENCE) and @EnableGlobalMethodSecurity(order = Ordered.HIGHEST_PRECEDENCE, ... but with no effect.

My solution was to set the order that I wanted by importing the library configuration at my configuration like this:

@Import(LibraryConfig.class)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MyConfiguration extends GlobalMethodSecurityConfiguration {
    /* my code */
}

PLUS: I found out that my situation is even more complicated, since the library that I'm using configures @EnableGlobalMethodSecurity(securedEnabled = true) more than once.
So the behave was a bit different and to force the use of my configurations I had to override the implementations of this methods:

@Bean
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
    return super.methodSecurityMetadataSource();
}

@Bean
public MethodInterceptor methodSecurityInterceptor() throws Exception {
    return super.methodSecurityInterceptor();
}

@Bean
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() {
    return super.preInvocationAuthorizationAdvice();
}


来源: stackexchange

问:
Copy and paste value to the next 2 empty row looping
I currently have a code like this

```<code>    Sub Rowname()

    Const SHEET_NAME As String = "Sheet1"
    Const START_ROW As String = "A"
    Const ROW_NUM As Long = 1
    Const COPY_SIZE As Integer = 2
    Dim rng As Range

    Set rng = ThisWorkbook.Worksheets(SHEET_NAME).Cells(ROW_NUM, START_ROW)
    Do Until IsEmpty(rng)
    rng.Offset(1, 0).Resize(COPY_SIZE, 1) = rng.Value2
    Set rng = rng.Offset(, COPY_SIZE + 1)
    Loop

    End Sub
</code>```

I am trying to make my filenames auto loop to copy another 2 times until the end.

```<code>    |  A    |         to something like  |  A    |
    |123.jpg|                            |123.jpg|
    |       |                            |123.jpg|
    |       |                            |123.jpg|
    |456.jpg|                            |456.jpg|
    |       |                            |456.jpg|
    |       |                            |456.jpg|
</code>```

I have around 2000 unique jpg files.

答:
You did mistake here, and your range moves right by columns:

```<code>Set rng = rng.Offset(, COPY_SIZE + 1)
</code>```

You need to move it by rows:

```<code> Set rng = rng.Offset(COPY_SIZE + 1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I currently have a code like this

    Sub Rowname()

    Const SHEET_NAME As String = "Sheet1"
    Const START_ROW As String = "A"
    Const ROW_NUM As Long = 1
    Const COPY_SIZE As Integer = 2
    Dim rng As Range

    Set rng = ThisWorkbook.Worksheets(SHEET_NAME).Cells(ROW_NUM, START_ROW)
    Do Until IsEmpty(rng)
    rng.Offset(1, 0).Resize(COPY_SIZE, 1) = rng.Value2
    Set rng = rng.Offset(, COPY_SIZE + 1)
    Loop

    End Sub

I am trying to make my filenames auto loop to copy another 2 times until the end.

    |  A    |         to something like  |  A    |
    |123.jpg|                            |123.jpg|
    |       |                            |123.jpg|
    |       |                            |123.jpg|
    |456.jpg|                            |456.jpg|
    |       |                            |456.jpg|
    |       |                            |456.jpg|

I have around 2000 unique jpg files.

Body:
You did mistake here, and your range moves right by columns:

Set rng = rng.Offset(, COPY_SIZE + 1)

You need to move it by rows:

 Set rng = rng.Offset(COPY_SIZE + 1)


问:
Learners in CNTK C# API
I am using C# CNTK 2.2.0 API for training.
I have installed Nuget package CNTK.CPUOnly and CNTK.GPU.

I am looking for following learners in C#.
1. AdaDelta
2. Adam
3. AdaGrad
4. Neterov

Looks like Python supports these learners but C#
package is not showing them.

I can see only SGD and SGDMomentun learners in C# there.

Any thoughts, how to get and set other learners in C#.
Do I need to install any additional package to get these learners?

Appreciate your help.

答:
The CNTKLib class in the CNTK namespace provides several learners, even not all of those you have listed. I list them in the following without their overloads.

```<code>public static Learner SGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);
public static Learner MomentumSGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner FSAdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner AdamLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner AdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);
public static Learner RMSPropLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, double gamma, double inc, double dec, double max, double min);
public static Learner AdaDeltaLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);
</code>```

You easily can access them like the following:

```<code>using CNTK;
CNTKLib.AdaDeltaLearner([...])
</code>```

This was done with the GPU version of CNTK 2.2. Maybe it is different with the CPU version.

Title: Learners in CNTK C# API

Body:
The CNTKLib class in the CNTK namespace provides several learners, even not all of those you have listed. I list them in the following without their overloads.

public static Learner SGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);
public static Learner MomentumSGDLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner FSAdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner AdamLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, TrainingParameterScheduleDouble momentumSchedule);
public static Learner AdaGradLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);
public static Learner RMSPropLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule, double gamma, double inc, double dec, double max, double min);
public static Learner AdaDeltaLearner(ParameterVector parameters, TrainingParameterScheduleDouble learningRateSchedule);

You easily can access them like the following:

using CNTK;
CNTKLib.AdaDeltaLearner([...])

This was done with the GPU version of CNTK 2.2. Maybe it is different with the CPU version.


问:
Understanding using a method in map in Scala
Why does the line of asdf1 work in

```<code>  def trytoDouble(s: String): Option[Double] = {
    try {
      Some(s.toDouble)
    } catch {
      case e: Exception => None
    }
  }

val asdf1 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(_.trim).map(trytoDouble(_)))

val asdf2 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(trytoDouble(_.trim)))
</code>```

while the line of asdf2 gives me the error message

Type mismatch, expected String => NotInferedB, actual: Option[Double]

for trytoDouble?

答:
Because after calling tryToDouble It will return Iterator[Array[Option[Double]]], and you are trying to trim value of type Option[Double]. trim is not a member of Option[Double]. trim expects string but it finds Option[Double] type value. That's why it throws an error

```<code>Type mismatch, expected String => NotInferedB, actual: Option[Double]
</code>```

You can't apply trim on Option[Double]. That's why first method works because there you apply trim on string.

Body:
Why does the line of asdf1 work in

  def trytoDouble(s: String): Option[Double] = {
    try {
      Some(s.toDouble)
    } catch {
      case e: Exception => None
    }
  }

val asdf1 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(_.trim).map(trytoDouble(_)))

val asdf2 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(trytoDouble(_.trim)))

while the line of asdf2 gives me the error message

Type mismatch, expected String => NotInferedB, actual: Option[Double]

for trytoDouble?

Body:
Because after calling tryToDouble It will return Iterator[Array[Option[Double]]], and you are trying to trim value of type Option[Double]. trim is not a member of Option[Double]. trim expects string but it finds Option[Double] type value. That's why it throws an error

Type mismatch, expected String => NotInferedB, actual: Option[Double]

You can't apply trim on Option[Double]. That's why first method works because there you apply trim on string.


问:
What is the point of the diamond operator (<>) in Java?
The diamond operator in java 7 allows code like the following:

```<code>List<String> list = new LinkedList<>();
</code>```

However in Java 5/6, I can simply write:

```<code>List<String> list = new LinkedList();
</code>```

My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway).

Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?

答:
In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?

No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.

The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.

IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.

Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as

```<code>package 7 com.example;
</code>```

could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.

ContentLicense: CC BY-SA 4.0

Body:
The diamond operator in java 7 allows code like the following:

List<String> list = new LinkedList<>();

However in Java 5/6, I can simply write:

List<String> list = new LinkedList();

My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway).

Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?

Body:
In theory, the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments. In practice, it's just two confusing chars more giving you nothing. Why?

No sane programmer uses raw types in new code. So the compiler could simply assume that by writing no type arguments you want it to infer them.

The diamond operator provides no type information, it just says the compiler, "it'll be fine". So by omitting it you can do no harm. At any place where the diamond operator is legal it could be "inferred" by the compiler.

IMHO, having a clear and simple way to mark a source as Java 7 would be more useful than inventing such strange things. In so marked code raw types could be forbidden without losing anything.

Btw., I don't think that it should be done using a compile switch. The Java version of a program file is an attribute of the file, no option at all. Using something as trivial as

package 7 com.example;

could make it clear (you may prefer something more sophisticated including one or more fancy keywords). It would even allow to compile sources written for different Java versions together without any problems. It would allow introducing new keywords (e.g., "module") or dropping some obsolete features (multiple non-public non-nested classes in a single file or whatsoever) without losing any compatibility.

ContentLicense: CC BY-SA 2.5


问:
Side menu not covering all screen (DrawerNavigator - React Native)
I adding image of screen, this work in part of screen.
The Contacts screen need to be main page and not screen1 but its didn't work if i replace between them.
I adding the code, in 'LogedInNavigator' have there TabNavigator and DrawerNavigator - the 'Contants' page initializing from TabNavigator and part two - Screen1 with the side menu it's from DrawerNavigator - maybe it's doing the problem?

LogedInNavigator.js

```<code>import.......
styles......

const LoggedInNavigator = TabNavigator(
  {
    Contacts: {screen: ContactScreen,},
    Chat: {screen: ChatScreen,},
    Dashbaord: {screen: DashbaordScreen,},
    Profile: {screen: ProfileScreen,},
    Search: {screen: SearchScreen,},
  },
  {
    initialRouteName: "Contacts",
    tabBarPosition: "bottom",
    tabBarOptions: {
      showIcon: true,
      activeTintColor: 'white',
    }
  }
);

export default () => <LoggedInNavigator onNavigationStateChange={null} />

export const Drawer = DrawerNavigator ({
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
})
</code>```

Contants.js

```<code>class Contacts extends Component {
  componentDidMount() {
    // TBD loggedin should come from login process and removed from here
    const { loggedIn, getContacts } = this.props;
    loggedIn(1);
    getContacts();
  }

  render() {
    const Router = createRouter( () => ({})); //IDAN
    const { navigation, avatar, contacts } = this.props;
    return (
      <NavigationProvider router={Router}>
        <View style={{flex:1}}>
          <ContactView
            navigation={navigation}
            avatar={avatar}
            contacts={contacts}
          />
         <Drawer />
        </View>
      </NavigationProvider>
    );
  }
}

const mapStateToProps = (state) => {
  return (
    {
      avatar: state.user.user.avatar,
      contacts: state.contacts.contacts,
    }
  );
};

export default connect(mapStateToProps, { loggedIn, getContacts })(Contacts);
</code>```

Help me please..

答:
You can set the drawer width using Dimensions width. See the docs here

https://reactnavigation.org/docs/navigators/drawer

```<code>import { Dimensions } from 'react-native';

...

const { width } = Dimensions.get('screen');

...

export const Drawer = DrawerNavigator (
{
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
},
{
  drawerWidth: width
});
</code>```

Body:
I adding image of screen, this work in part of screen.
The Contacts screen need to be main page and not screen1 but its didn't work if i replace between them.
I adding the code, in 'LogedInNavigator' have there TabNavigator and DrawerNavigator - the 'Contants' page initializing from TabNavigator and part two - Screen1 with the side menu it's from DrawerNavigator - maybe it's doing the problem?

LogedInNavigator.js

import.......
styles......

const LoggedInNavigator = TabNavigator(
  {
    Contacts: {screen: ContactScreen,},
    Chat: {screen: ChatScreen,},
    Dashbaord: {screen: DashbaordScreen,},
    Profile: {screen: ProfileScreen,},
    Search: {screen: SearchScreen,},
  },
  {
    initialRouteName: "Contacts",
    tabBarPosition: "bottom",
    tabBarOptions: {
      showIcon: true,
      activeTintColor: 'white',
    }
  }
);

export default () => <LoggedInNavigator onNavigationStateChange={null} />

export const Drawer = DrawerNavigator ({
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
})

Contants.js

class Contacts extends Component {
  componentDidMount() {
    // TBD loggedin should come from login process and removed from here
    const { loggedIn, getContacts } = this.props;
    loggedIn(1);
    getContacts();
  }

  render() {
    const Router = createRouter( () => ({})); //IDAN
    const { navigation, avatar, contacts } = this.props;
    return (
      <NavigationProvider router={Router}>
        <View style={{flex:1}}>
          <ContactView
            navigation={navigation}
            avatar={avatar}
            contacts={contacts}
          />
         <Drawer />
        </View>
      </NavigationProvider>
    );
  }
}

const mapStateToProps = (state) => {
  return (
    {
      avatar: state.user.user.avatar,
      contacts: state.contacts.contacts,
    }
  );
};

export default connect(mapStateToProps, { loggedIn, getContacts })(Contacts);

Help me please..

Body:
You can set the drawer width using Dimensions width. See the docs here

https://reactnavigation.org/docs/navigators/drawer

import { Dimensions } from 'react-native';

...

const { width } = Dimensions.get('screen');

...

export const Drawer = DrawerNavigator (
{
  Home:{
    screen: Screen1,
    navigationOptions: {
      drawer:{
        label: 'Home',
      },
    }
  },
  Camera: {
    screen: Screen2,
    navigationOptions: {
      drawer:{
        label: 'Camera',
      },
    }
  },
},
{
  drawerWidth: width
});


问:
SQL Server RowNumbering
```<code>SrNo   TextCol
--------------
NULL   ABC
NULL   ABC
NULL   ASC
NULL   qwe
</code>```

I want to update the SrNo column with numbers 1,2,3,4 without changing sequence of other columns.

答:
It only makes sense to speak of using row number if there exist a column which can provide ordering.  Assuming the ordering is specified by the TextCol column, then we can try the following:

```<code>WITH cte AS (
    SELECT SrNo, TextCol, ROW_NUMBER() OVER (ORDER BY TextCol) rn
    FROM yourTable
)

UPDATE cte
SET SrNo = rn;
</code>```

Title: SQL Server RowNumbering

Body:
SrNo   TextCol
--------------
NULL   ABC
NULL   ABC
NULL   ASC
NULL   qwe

I want to update the SrNo column with numbers 1,2,3,4 without changing sequence of other columns.

Body:
It only makes sense to speak of using row number if there exist a column which can provide ordering.  Assuming the ordering is specified by the TextCol column, then we can try the following:

WITH cte AS (
    SELECT SrNo, TextCol, ROW_NUMBER() OVER (ORDER BY TextCol) rn
    FROM yourTable
)

UPDATE cte
SET SrNo = rn;


问:
How to handle multiple layout clicks in recyclerView in Android
In our app we have list of messages. We are switching to RecyclerView.
Our messages can consist from texts, images.
Sample message can look like this.

To handle clicks use this class:

```<code>public class RecyclerViewItemClickListener implement  RecyclerView.OnItemTouchListener {

    public static interface OnItemClickListener {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerViewItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }
}
</code>```

and we implement this clicks in activity like this:

```<code>chatView.setLongClickable(true);
        chatView.addOnItemTouchListener(
                new RecyclerViewItemClickListener(this, chatView, new RecyclerViewItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {

                        //handleSingleClick(view, position);

                    }
                    @Override
                    public void onItemLongClick(View view, int position)
                    {
                        handleLongPress(position);
                    }
                })
        );
</code>```

Clicks for message is working, now I want also handle userAvatar clicks from same GestureDetection. Is it possible to detect which list item layout was clicked from GestureDetector?

In other words, can I get GestureDetecter clicked child. In my case click is set to whole item(avatar, text message, image). Can I detect which element inside this item was clicked(for example I want catch avatar click).

答:
I tried this same way like @user320676, But I tried to complete with a Listener:

```<code>interface MultipleClickListener {
        void onItemClickOne(int position, View v);
        void onItemClickTwo(int position, View v);
        void onItemClickThree(int position, View v);
}
</code>```

then you can use the listener in a activity or fragment. Here you can see my full Adapter:

```<code>public class MultipleClicksAdapter extends RecyclerView
        .Adapter<MultipleClicksAdapter
        .DataObjectHolder> {

    private ArrayList<MultipleClickData> mDataset;
    private static MultipleClickListener sClickListener;

    static class DataObjectHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.multiple_clicks_one_textView)
        TextView mOne;
        @BindView(R.id.multiple_clicks_two_textView)
        TextView mTwo;
        @BindView(R.id.multiple_clicks_three_textView)
        TextView mThree;

        DataObjectHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);

            mOne.setOnClickListener((View v) ->
                    sClickListener.onItemClickOne(getAdapterPosition(), mOne));

            mTwo.setOnClickListener((View v) ->
                    sClickListener.onItemClickTwo(getAdapterPosition(), mTwo));

            mThree.setOnClickListener((View v) ->
                    sClickListener.onItemClickThree(getAdapterPosition(), mThree));
        }

    }

    void setOnItemClickListener(MultipleClickListener myClickListener) {
        this.sClickListener = myClickListener;
    }

    MultipleClicksAdapter(ArrayList<MultipleClickData> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public MultipleClicksAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.multiple_clicks_list_item, parent, false);

        MultipleClicksAdapter.DataObjectHolder dataObjectHolder = new MultipleClicksAdapter.DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(MultipleClicksAdapter.DataObjectHolder holder, int position) {
        holder.mOne.setText(mDataset.get(position).getmTitle());
        holder.mTwo.setText(mDataset.get(position).getmSubTitle());
        holder.mThree.setText(mDataset.get(position).getmThirdTitle());
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    interface MultipleClickListener {
        void onItemClickOne(int position, View v);
        void onItemClickTwo(int position, View v);
        void onItemClickThree(int position, View v);
    }

}
</code>```

Also you can check the complete code in GitHub.

Body:
In our app we have list of messages. We are switching to RecyclerView.
Our messages can consist from texts, images.
Sample message can look like this.

To handle clicks use this class:

public class RecyclerViewItemClickListener implement  RecyclerView.OnItemTouchListener {

    public static interface OnItemClickListener {
        public void onItemClick(View view, int position);
        public void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;
    private GestureDetector mGestureDetector;

    public RecyclerViewItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e)
            {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if(childView != null && mListener != null)
                {
                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }
}

and we implement this clicks in activity like this:

chatView.setLongClickable(true);
        chatView.addOnItemTouchListener(
                new RecyclerViewItemClickListener(this, chatView, new RecyclerViewItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {

                        //handleSingleClick(view, position);

                    }
                    @Override
                    public void onItemLongClick(View view, int position)
                    {
                        handleLongPress(position);
                    }
                })
        );

Clicks for message is working, now I want also handle userAvatar clicks from same GestureDetection. Is it possible to detect which list item layout was clicked from GestureDetector?

In other words, can I get GestureDetecter clicked child. In my case click is set to whole item(avatar, text message, image). Can I detect which element inside this item was clicked(for example I want catch avatar click).

Body:
I tried this same way like @user320676, But I tried to complete with a Listener:

interface MultipleClickListener {
        void onItemClickOne(int position, View v);
        void onItemClickTwo(int position, View v);
        void onItemClickThree(int position, View v);
}

then you can use the listener in a activity or fragment. Here you can see my full Adapter:

public class MultipleClicksAdapter extends RecyclerView
        .Adapter<MultipleClicksAdapter
        .DataObjectHolder> {

    private ArrayList<MultipleClickData> mDataset;
    private static MultipleClickListener sClickListener;

    static class DataObjectHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.multiple_clicks_one_textView)
        TextView mOne;
        @BindView(R.id.multiple_clicks_two_textView)
        TextView mTwo;
        @BindView(R.id.multiple_clicks_three_textView)
        TextView mThree;

        DataObjectHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);

            mOne.setOnClickListener((View v) ->
                    sClickListener.onItemClickOne(getAdapterPosition(), mOne));

            mTwo.setOnClickListener((View v) ->
                    sClickListener.onItemClickTwo(getAdapterPosition(), mTwo));

            mThree.setOnClickListener((View v) ->
                    sClickListener.onItemClickThree(getAdapterPosition(), mThree));
        }

    }

    void setOnItemClickListener(MultipleClickListener myClickListener) {
        this.sClickListener = myClickListener;
    }

    MultipleClicksAdapter(ArrayList<MultipleClickData> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public MultipleClicksAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                                                           int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.multiple_clicks_list_item, parent, false);

        MultipleClicksAdapter.DataObjectHolder dataObjectHolder = new MultipleClicksAdapter.DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(MultipleClicksAdapter.DataObjectHolder holder, int position) {
        holder.mOne.setText(mDataset.get(position).getmTitle());
        holder.mTwo.setText(mDataset.get(position).getmSubTitle());
        holder.mThree.setText(mDataset.get(position).getmThirdTitle());
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    interface MultipleClickListener {
        void onItemClickOne(int position, View v);
        void onItemClickTwo(int position, View v);
        void onItemClickThree(int position, View v);
    }

}

Also you can check the complete code in GitHub.


问:
App not installed manually from sd card of android studio 3.0 run
I build a new fresh project on android studio 3.0 and copy APK on sd card, when i install that APK manually it's shows me dialog of 'app not installed' whereas if run and install same app from android studio it get install successfully. I tested the same scenario with lower version of studio but no such problem occurred. What change i have to do in my new project for installation.</p>

答: You have to signed your apk with enabling v1 jar and v2 full apk signature.</p>


问:
mysql with many tables
I have a major problem getting this to work properly. Here is the deal.

I have 4 tables - timeline, connections, images, votes

Timeline table:

```<code>time_id
time_title
</code>```

etc.

The timeline table connects with the images table via the connections table

Connections table:

```<code>time_id
image_id
</code>```

So the connections hold information about the id of the "post" the timeline and about image id

Images table:

```<code>image_id
image_url
image_type
</code>```

Images table contains images that could be used in the same timeline(post), so by this i can see the connection by looking at the connection table.

I also have a votes table that holds information about votes for the specific timeline post

Votes table:

```<code>vote_id
time_id
</code>```

the votes table contains many rows of each time_id and the idea is to count the number of times to se wich is the most popular

So heres the question:
I need to get the 5 most voted time_titles and show them with the first image for each time_title(post) so that it look like this for example

Image 1 that corresponds to Title 1 - that is the highest voted

Image 2 that corresponds to Title 2 - that is the second highest voted

etc.

Each timeline row (post) can hold many images and i only want to show the first of each post.

Hope you understand my problem!

Thanks a lot!

答:
```<code>SELECT  t.time_title, i.*
FROM    (
        SELECT  t.time_title
        FROM    timeline t
        LEFT JOIN
                votes v
        ON      v.time_id = t.time_id
        GROUP BY
                t.id
        ORDER BY
                COUNT(vote_id) DESC, t.time_id DESC
        LIMIT 5
        ) t
JOIN    images i
ON      i.id =
        (
        SELECT  ii.image_id
        FROM    connections c
        JOIN    image ii
        ON      ii.image_id = c.image_id
        WHERE   c.time_id = t.time_id
        ORDER BY
                ii.id DESC -- or whatever order you define for the "first" image
        LIMIT 1
        )
</code>```

Title: mysql with many tables

Body:
I have a major problem getting this to work properly. Here is the deal.

I have 4 tables - timeline, connections, images, votes

Timeline table:

time_id
time_title

etc.

The timeline table connects with the images table via the connections table

Connections table:

time_id
image_id

So the connections hold information about the id of the "post" the timeline and about image id

Images table:

image_id
image_url
image_type

Images table contains images that could be used in the same timeline(post), so by this i can see the connection by looking at the connection table.

I also have a votes table that holds information about votes for the specific timeline post

Votes table:

vote_id
time_id

the votes table contains many rows of each time_id and the idea is to count the number of times to se wich is the most popular

So heres the question:
I need to get the 5 most voted time_titles and show them with the first image for each time_title(post) so that it look like this for example

Image 1 that corresponds to Title 1 - that is the highest voted

Image 2 that corresponds to Title 2 - that is the second highest voted

etc.

Each timeline row (post) can hold many images and i only want to show the first of each post.

Hope you understand my problem!

Thanks a lot!


答:
Or like this:</p>

```<code>WITH CTE AS
(
SELECT
BL.FORMID,
BL.NOOFISSUES AS BLI,
RV.NOOFISSUES AS RVI,
RV.DATE,
ROW_NUMBER() OVER(PARTITION BY BL.FORMID ORDER BY RV.DATE) AS RN
FROM Baseline BL
INNER JOIN Revisits RV ON RV.FORMID = BL.FORMID
)

SELECT COALESCE(SUM(CASE WHEN RVI > BLI THEN 1 END), 0) AS INCREASED,
COALESCE(SUM(CASE WHEN RVI < BLI THEN 1 END), 0) AS DECREASED,
COALESCE(SUM(CASE WHEN RVI = BLI THEN 1 END), 0) AS EQUAL
FROM CTE
WHERE RN=1;
</code>```

Title: SQL group by count across two tables

Body:
I have got two tables called baseline and revisits

baseline

formid-------NoOfIssues

1--------------3

2--------------4

3--------------5

revisits

id------formid-------NoOfIssues-----------date--------------fid

1---------2--------------4-------------5/06/2016------------1

2---------3--------------3-------------15/06/2016-----------1

3---------1--------------4-------------20/07/2016-----------1

4---------1--------------3-------------25/07/2016-----------1

5---------2--------------5-------------28/07/2016-----------1

6---------1--------------5-------------01/06/2016-----------1

7---------3--------------8-------------21/02/2016-----------1

8---------3--------------2-------------21/02/2016-----------2

These tables are joined by 'formid'.
I need to compare number of issues in baseline vs revisits(only first) and get a count as reduced, increased or equal

Based upon the above table i am expecting the following, for example across all three baseline entries no equals were found comparing NoOfissues in first revisit against same formid, but 1 equal and 2 increased were found

Addition: if same date and same formid is found than take the lower fid, so in the last two rows of revisits table both formid and date are equal but need to consider the lower formid which is 1

status----------Count

reduced----------0

equal------------1

increased--------2

Body:
Or like this:

WITH CTE AS
(
SELECT
BL.FORMID,
BL.NOOFISSUES AS BLI,
RV.NOOFISSUES AS RVI,
RV.DATE,
ROW_NUMBER() OVER(PARTITION BY BL.FORMID ORDER BY RV.DATE) AS RN
FROM Baseline BL
INNER JOIN Revisits RV ON RV.FORMID = BL.FORMID
)

SELECT COALESCE(SUM(CASE WHEN RVI > BLI THEN 1 END), 0) AS INCREASED,
COALESCE(SUM(CASE WHEN RVI < BLI THEN 1 END), 0) AS DECREASED,
COALESCE(SUM(CASE WHEN RVI = BLI THEN 1 END), 0) AS EQUAL
FROM CTE
WHERE RN=1;


问:
Go error: unexpected Nul in input
I just installed the go.msi in C:/Go.
And I set my Path(C:\Go\bin) and GOPATH(E:\code\go).But when I try to run "go run test.go" I get the following error:  test.go:2:8: read C:\Go\src\fmt\export_test.go: unexpected NUL in input
package main
        imports runtime: read C:\Go\src\runtime\export_unix_test.go: unexpected NUL in input

I can not open these files.
The code i have is:

```<code>    package main

    import "fmt"

    func main()  {
        fmt.Println("Something")
    }
</code>```

The path of the test.go file is E:\code\go\test.go
When i run go env i get:

```<code>set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=E:\code\go
set GORACE=
set GOROOT=C:\Go
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0
set CXX=g++
set CGO_ENABLED=1
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
</code>```

the output of go version is:
    go version go1.9.2 windows/amd64

答:
You are missing some things in your GOPATH. You need a folder structure like the following:

```<code>E:\code\go\src\{repository}\{package}\gofile.go
</code>```

So for this, you could have it be:

```<code>E:\code\go\src\local-only\testing\test.go
</code>```

Title: Go error: unexpected Nul in input

Body:
I just installed the go.msi in C:/Go.
And I set my Path(C:\Go\bin) and GOPATH(E:\code\go).But when I try to run "go run test.go" I get the following error:  test.go:2:8: read C:\Go\src\fmt\export_test.go: unexpected NUL in input
package main
        imports runtime: read C:\Go\src\runtime\export_unix_test.go: unexpected NUL in input

I can not open these files.
The code i have is:

    package main

    import "fmt"

    func main()  {
        fmt.Println("Something")
    }

The path of the test.go file is E:\code\go\test.go
When i run go env i get:

set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=E:\code\go
set GORACE=
set GOROOT=C:\Go
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0
set CXX=g++
set CGO_ENABLED=1
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config

the output of go version is:
    go version go1.9.2 windows/amd64

Body:
You are missing some things in your GOPATH. You need a folder structure like the following:

E:\code\go\src\{repository}\{package}\gofile.go

So for this, you could have it be:

E:\code\go\src\local-only\testing\test.go


问:
Xcode automatically perform build opertaion
I am facing unexpected issue with Xcode 9.0. Even if I am writing code in the app, Xcode automatically performs build operation. See below image

Even I deleted derived data, restarts Xcode and System but issue is the same. Because of this my system in getting slow down.

Can anyone suggest how should I stop this build operation.

Please let me know if I have explain my question more.

答:
When Live issues setting enabled it will come like that. Please turn it off by following below.

Please do this step:

Go to Preferences -> General and disable Live Issues in Editors and in Issue Navigator

Talking about this in case if you won't understand


问:
serialize only one property of a class
I have a class which have about 20 members. I need to serialize my the object of this  class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

答:
mark the other attributes

```<code><NonSerializable()> _
Property someproperty
</code>```

End Property

Title: serialize only one property of a class

Body:
mark the other attributes

<NonSerializable()> _
Property someproperty

End Property


问:
How can I deal the flash when I turn back to a Activity has DrawerLayout?
I use A DrawerLayout in ActivityA.

I open the Drawer at first. When I click a item on Drawer, I skip to ActivityB.

In ActivityB ,I close the Drawer by EventBus. When I click the back button,ActivityB move out,and ActivityA move in.

But the screen flash once when Activity move in.

I know it's because that when I open a Drawer,ActivityA dark down.

When I turn back, Activity become normal because the Drawer is closed.

How can I deal with this problem?

答:
Just remove these lines from DrawerLayout tag.

```<code>android:fitsSystemWindows="true"
tools:openDrawer="start"
</code>```

The flash effect will be remove when you turn back. Hope it works on your side.

Body:
Just remove these lines from DrawerLayout tag.

android:fitsSystemWindows="true"
tools:openDrawer="start"

The flash effect will be remove when you turn back. Hope it works on your side.


问:
Time-Efficient Sorting of structure in c++
I have a structure

```<code> struct abc
       {
        int p;
        int q;
       }
</code>```

and a file which gives the value of p and q and the operation that is to be done( insert,delete or modify) and then accordingly the values needs to be maintained in a sorted manner(sort acc to p).

The sequence is

```<code>1.Read the line from file
2.If insert, insert in a sorted manner<br>
  If modify,delete; first remove the element and then sort<br>
3.Repeat step 1<br><br>
</code>```

I already implemented this with a linked list but is there any other more time-efficient method than this?

I thought of an array(with memcpy-ing to ease the operations),set and vector but implementation wise it seems to be a bit difficult as all the operations has to done.

Would be helpful if i could get an algorithm or snapshot of the code

答:
You can use array of structure to get input and then use built-in sort according to a compare function.</p>

```<code>bool compare(struct abc c1,struct abc c2)
{
 return c1.p < c2.p;
}

//main
abc arr[n];
for(int i=0;i<n;i++)
{
 cin>>arr[i].p>>arr[i].q;
}
//O(n lg n)
sort(arr,arr+n,compare);
</code>```

Body:
I have a structure

 struct abc
       {
        int p;
        int q;
       }

and a file which gives the value of p and q and the operation that is to be done( insert,delete or modify) and then accordingly the values needs to be maintained in a sorted manner(sort acc to p).

The sequence is

1.Read the line from file
2.If insert, insert in a sorted manner

  If modify,delete; first remove the element and then sort

3.Repeat step 1

I already implemented this with a linked list but is there any other more time-efficient method than this?

I thought of an array(with memcpy-ing to ease the operations),set and vector but implementation wise it seems to be a bit difficult as all the operations has to done.

Would be helpful if i could get an algorithm or snapshot of the code

Body:
You can use array of structure to get input and then use built-in sort according to a compare function.

bool compare(struct abc c1,struct abc c2)
{
 return c1.p < c2.p;
}

//main
abc arr[n];
for(int i=0;i<n;i++)
{
 cin>>arr[i].p>>arr[i].q;
}
//O(n lg n)
sort(arr,arr+n,compare);


问:
Manually skip a component from being created from the dfm
Is there a way to skip a component from being created from the dfm?

I have an visual component I sometimes do not want to be created. Of course I could create the component by hand, but this would be a lot of work since the component has a lot of items.

答:
Is there a way to skip a component from being created from the dfm?

There is no clean way to do this, in my opinion. I think you are looking for a method that can be applied using the form designer.

Uwe's answer shows a code based method that does indeed do what you ask, but I personally would regard it as too unwieldy for practical use. Furthermore Uwe's answer requires the optional component to be the only component of that class on the for. That is just not realistic.

In my view, the best options are either:

Have the component be created automatically as part of .dfm streaming, and then either destroy it or hide it at runtime.

Create the component optionally at runtime.


问:
Create json array format in android
I want to create json request string. How can I do that? This is my following array:

```<code>[1,2,3,4,5];
</code>```

Now I want to create this type of json request:

```<code>{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}
</code>```

Does anyone has the idea about how to create this type of json string?

答:
Iterate through the array and print the relevant string for each element.</p>

```<code>public static String ConvertToContactJson(int [] array)
{
    String finalstr = "{\"contact_approve\":[";

    for (int i=0; i< array.length; i++)
    {
        finalstr += "{\"contact_id\":"+array[i]+"}";

        if (i < array.length-1) finalstr += ",";
    }

    finalstr += "]}";

    return finalstr;
}
</code>```

Title: Create json array format in android

Body:
I want to create json request string. How can I do that? This is my following array:

[1,2,3,4,5];

Now I want to create this type of json request:

{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}

Does anyone has the idea about how to create this type of json string?

Body:
Iterate through the array and print the relevant string for each element.

public static String ConvertToContactJson(int [] array)
{
    String finalstr = "{\"contact_approve\":[";

    for (int i=0; i< array.length; i++)
    {
        finalstr += "{\"contact_id\":"+array[i]+"}";

        if (i < array.length-1) finalstr += ",";
    }

    finalstr += "]}";

    return finalstr;
}


问:
SVG color gets black when using dom-to-image plugin
I am in a situation where I need to export the following SVG as a pdf so I am using the dom-to-image plugin listed in NPM plugin directory.
So the problem is when I try to export the following SVG as an image the color of the SVG gets black.

I tried some options listed in the dom-to-image options but those are for the parent node the SVG I am trying to export is in its child node.

HTML:

```<code><div id="foo"><svg class="cone" viewBox="-25 0 1175 1419" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Canvas" transform="translate(19600 8843)">
<g id="Group 5">
<g id="Group 6">
<g id="Group 5">
<g id="Vector 3.4">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path10_fill" transform="translate(-19604.5 -7783)" fill="#3596ff">
</use>
</g>
</g>
</g>
</g>
</g>
<defs>
<path id="path10_fill" d="M 0 208L 85 0C 230.833 82 623.9 196.8 1047.5 0L 1138 208C 842 441.5 137 369.5 0 208Z">
</path>
</defs>
</svg>
</div>
</code>```

JavaScript:

```<code>const render = node =>
  domtoimage.toPng(node)
  .then(dataUrl => {
  console.log(performance.now()-pf)
    const img = new Image();
    img.src = dataUrl;
    $('body').append(img);
  })
  .catch(error =>
    console.error('oops, something went wrong!', error)
  );

const foo = document.getElementById('foo');

var pf=performance.now();
render(foo);
</code>```

Fiddle Link

NOTE: Please scroll down in the output part to see the result.

答: The plugin probably doesn't recognize the <use> tag. You can just change the fill="#3596ff" to the <svg> tag or the <path> tag if you're going to have more than one path.

Body:
I am in a situation where I need to export the following SVG as a pdf so I am using the dom-to-image plugin listed in NPM plugin directory.
So the problem is when I try to export the following SVG as an image the color of the SVG gets black.

I tried some options listed in the dom-to-image options but those are for the parent node the SVG I am trying to export is in its child node.

HTML:

<svg class="cone" viewBox="-25 0 1175 1419" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Canvas" transform="translate(19600 8843)">
<g id="Group 5">
<g id="Group 6">
<g id="Group 5">
<g id="Vector 3.4">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path10_fill" transform="translate(-19604.5 -7783)" fill="#3596ff">
</use>
</g>
</g>
</g>
</g>
</g>
<defs>
<path id="path10_fill" d="M 0 208L 85 0C 230.833 82 623.9 196.8 1047.5 0L 1138 208C 842 441.5 137 369.5 0 208Z">
</path>
</defs>
</svg>

JavaScript:

const render = node =>
  domtoimage.toPng(node)
  .then(dataUrl => {
  console.log(performance.now()-pf)
    const img = new Image();
    img.src = dataUrl;
    $('body').append(img);
  })
  .catch(error =>
    console.error('oops, something went wrong!', error)
  );

const foo = document.getElementById('foo');

var pf=performance.now();
render(foo);

Fiddle Link

NOTE: Please scroll down in the output part to see the result.


问:
Android shape border with gradient
I want to create a border for a linearLayout. So I decide to create a shape. I want the border to have a gradient. The following is not doing it. It fills the rectangle and then creates a stroke. I don't want a filled rectangle, just the stroke. And I want to apply the gradient to the stroke.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="360"
        android:centerColor="#e95a22"
        android:endColor="#ff00b5"
        android:gradientRadius="360"
        android:startColor="#006386"
        android:type="sweep" />

    <stroke
        android:width="2dp"
        android:color="#ff207d94" />

</shape>
</code>```

答:
since the accepted answer didn't work exactly as i wanted it to work for me, i'll post my solution too, maybe it helps someone else :)</p>

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>
<!-- create gradient you want to use with the angle you want to use -->
    <shape android:shape="rectangle" >
        <gradient
            android:angle="0"
            android:centerColor="@android:color/holo_blue_bright"
            android:endColor="@android:color/holo_red_light"
            android:startColor="@android:color/holo_green_light" />

    </shape>
</item>
<!-- create the stroke for top, left, bottom and right with the dp you want -->
<item
    android:bottom="2dp"
    android:left="2dp"
    android:right="2dp"
    android:top="2dp">
    <shape android:shape="rectangle" >
        <!-- fill the inside in the color you want (could also be a gradient again if you want to, just change solid to gradient and enter angle, start, maybe center, and end color) -->
        <solid android:color="#fff" />
    </shape>
</item>

</layer-list>
</code>```

Title: Android shape border with gradient

Body:
I want to create a border for a linearLayout. So I decide to create a shape. I want the border to have a gradient. The following is not doing it. It fills the rectangle and then creates a stroke. I don't want a filled rectangle, just the stroke. And I want to apply the gradient to the stroke.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="360"
        android:centerColor="#e95a22"
        android:endColor="#ff00b5"
        android:gradientRadius="360"
        android:startColor="#006386"
        android:type="sweep" />

    <stroke
        android:width="2dp"
        android:color="#ff207d94" />

</shape>

Body:
since the accepted answer didn't work exactly as i wanted it to work for me, i'll post my solution too, maybe it helps someone else :)

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>
<!-- create gradient you want to use with the angle you want to use -->
    <shape android:shape="rectangle" >
        <gradient
            android:angle="0"
            android:centerColor="@android:color/holo_blue_bright"
            android:endColor="@android:color/holo_red_light"
            android:startColor="@android:color/holo_green_light" />

    </shape>
</item>
<!-- create the stroke for top, left, bottom and right with the dp you want -->
<item
    android:bottom="2dp"
    android:left="2dp"
    android:right="2dp"
    android:top="2dp">
    <shape android:shape="rectangle" >
        <!-- fill the inside in the color you want (could also be a gradient again if you want to, just change solid to gradient and enter angle, start, maybe center, and end color) -->
        <solid android:color="#fff" />
    </shape>
</item>

</layer-list>


问:
Packer Script exited with non-zero exit status : 127
I am trying to provision an AWS AMI but the packer script terminates with the following error.

```<code>Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127
   ==> Some builds didn't complete successfully and had errors:
   --> amazon-ebs: Script exited with non-zero exit status: 127
   ==> Builds finished but no artifacts were created.
</code>```

My template for Packer is as follows:

```<code>   {
   "variables": {
    "aws_access_key": "{{env `MY_ACCESS_KEY`}}",
    "aws_secret_key": "{{env `MY_SECRET_KEY`}}"
   },
    "builders": [{
    "type": "amazon-ebs",
    "access_key": "{{user `aws_access_key`}}",
    "secret_key": "{{user `aws_secret_key`}}",
    "region": "us-east-1",
    "source_ami":"ami-8c1be5f6",
    "instance_type": "t2.micro",
    "ssh_username": "ec2-user",
    "ami_name": "packer-example {{timestamp}}"
    }],
    "provisioners":[
    {
      "type": "shell",
      "script": "provision.sh"
    }]}
</code>```

Error log is as follows: PACKER_LOG=1 packer build template.json

```<code>2017/11/01 01:30:37 [INFO] (telemetry) ending amazon-ebs
2017/11/01 01:30:37 [INFO] (telemetry) found error: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 ui error: Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 Builds completed. Waiting on interrupt barrier...
2017/11/01 01:30:37 machine readable: error-count []string{"1"}
2017/11/01 01:30:37 ui error:
==> Some builds didn't complete successfully and had errors:
2017/11/01 01:30:37 machine readable: amazon-ebs,error []string{"Script exited with non-zero exit status: 127"}
2017/11/01 01:30:37 ui error: --> amazon-ebs: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 ui:
==> Builds finished but no artifacts were created.
Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127
</code>```

provision.sh comprises of

```<code>   #!/bin/bash
   sudo yum install httpd -y
   sudo yum update -y
   sudo aws s3 cp s3://zbcxlkxcjvlxkj/index1.html /var/www/html/ --region us-east-1
   sudo service httpd start
   sudo chkconfig httpd on
</code>```

答: Exit code 127 is returned by bash when a command is not found. Most likely you do not have all of the commands used in your script installed on your image prior to running it. </p>

Body:
I am trying to provision an AWS AMI but the packer script terminates with the following error.

Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127
   ==> Some builds didn't complete successfully and had errors:
   --> amazon-ebs: Script exited with non-zero exit status: 127
   ==> Builds finished but no artifacts were created.

My template for Packer is as follows:

   {
   "variables": {
    "aws_access_key": "{{env `MY_ACCESS_KEY`}}",
    "aws_secret_key": "{{env `MY_SECRET_KEY`}}"
   },
    "builders": [{
    "type": "amazon-ebs",
    "access_key": "{{user `aws_access_key`}}",
    "secret_key": "{{user `aws_secret_key`}}",
    "region": "us-east-1",
    "source_ami":"ami-8c1be5f6",
    "instance_type": "t2.micro",
    "ssh_username": "ec2-user",
    "ami_name": "packer-example {{timestamp}}"
    }],
    "provisioners":[
    {
      "type": "shell",
      "script": "provision.sh"
    }]}

Error log is as follows: PACKER_LOG=1 packer build template.json

2017/11/01 01:30:37 [INFO] (telemetry) ending amazon-ebs
2017/11/01 01:30:37 [INFO] (telemetry) found error: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 ui error: Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 Builds completed. Waiting on interrupt barrier...
2017/11/01 01:30:37 machine readable: error-count []string{"1"}
2017/11/01 01:30:37 ui error:
==> Some builds didn't complete successfully and had errors:
2017/11/01 01:30:37 machine readable: amazon-ebs,error []string{"Script exited with non-zero exit status: 127"}
2017/11/01 01:30:37 ui error: --> amazon-ebs: Script exited with non-zero exit status: 127
2017/11/01 01:30:37 ui:
==> Builds finished but no artifacts were created.
Build 'amazon-ebs' errored: Script exited with non-zero exit status: 127

provision.sh comprises of

   #!/bin/bash
   sudo yum install httpd -y
   sudo yum update -y
   sudo aws s3 cp s3://zbcxlkxcjvlxkj/index1.html /var/www/html/ --region us-east-1
   sudo service httpd start
   sudo chkconfig httpd on


问:
How to setup timeout dynamically with retrofit2?
```<code>public class Router {

    ...

    private static Retrofit retrofit = null;

    ...

    public Retrofit getRetrofit() {
        if (retrofit == null) {

            ...

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("***")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
        }
        return retrofit;
    }

    ...

}
</code>```

I setup timeout in OkHttpClient. Now there is a API needs different timeout.

How can i do?

Is there something like this?

```<code>@Timeout
Observable<ResponseBody> exapmle(@Timeout("connect") int connect
 , @Timeout("read") int read
 , @Timeout("write") int write);
</code>```

答:
Create a new retrofit instance where you pass in timeout values as parameters.

```<code>public Retrofit getRetrofit(int connectionTimeout, int readWriteTimeout) {
        if (retrofit == null) {

            ...

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(connectionTimeout, TimeUnit.SECONDS)
                    .writeTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .readTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("***")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
        }
        return retrofit;
    }
</code>```

There is no option like the below:

```<code>@Timeout
Observable<ResponseBody> exapmle(@Timeout("connect") int connect
                , @Timeout("read") int read
                , @Timeout("write") int write);
</code>```

Body:
public class Router {

    ...

    private static Retrofit retrofit = null;

    ...

    public Retrofit getRetrofit() {
        if (retrofit == null) {

            ...

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("***")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
        }
        return retrofit;
    }

    ...

}

I setup timeout in OkHttpClient. Now there is a API needs different timeout.

How can i do?

Is there something like this?

@Timeout
Observable<ResponseBody> exapmle(@Timeout("connect") int connect
 , @Timeout("read") int read
 , @Timeout("write") int write);

Body:
Create a new retrofit instance where you pass in timeout values as parameters.

public Retrofit getRetrofit(int connectionTimeout, int readWriteTimeout) {
        if (retrofit == null) {

            ...

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(connectionTimeout, TimeUnit.SECONDS)
                    .writeTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .readTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("***")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
        }
        return retrofit;
    }

There is no option like the below:

@Timeout
Observable<ResponseBody> exapmle(@Timeout("connect") int connect
                , @Timeout("read") int read
                , @Timeout("write") int write);


问:
What would be a good project to learn node.js
Everyone is talking about NodeJS so I though I'll look into it by creating a usefull project but I cant really think of something usefull to build on NodeJS tha fully demonstrates it's capabilities.

does any of you have a good idea ?

答:
I cant really think of something usefull to build on NodeJS tha fully demonstrates it's capabilities.

Node.js can be probably hardly used to build single useful project or module which demonstrates all of it's capabilities because there are many areas which it can be applied to. I would say you should pick the area which interests you the most so that you won't lose your enthusiasm and eventually you can become an expert in that particular area.


问:
How to handle auto completion on multi word text?
My input text is a multiword english text and I have the requirement to implement a autocompletion feature for that text.

I initially looked at search completion suggesters only to figure out that those can only match the first characters of the input. This is fine for auto completion of product names or address but not very useful when requiring a auto completion on any word in the input text.

After that I setup an edge_ngram analyzer and query to locate those documents which contain the input string. That works just fine but I don't know how to use this information to provide options for my auto completion.

I could use a highlighter in order to show the words which match the query. That data could in turn be used to setup a list of options. This solution seems rather hacky and not very elegant and I wonder how this problem is usually solved?

I'm unfortunately not able to maintain another field which could include the auto completion options for the documents.

答:
I'm currently using highlight information of the query in order to construct the autocomplete options.

My Query:

```<code>{
  "query": {
    "match": {
      "fields.content.auto": {
        "query": "content co",
        "analyzer": "standard"
      }
    }
  },
  "highlight": {
    "fields": {
      "fields.content.auto": {
        "fragment_size": 0,
        "number_of_fragments": 10,
        "pre_tags" : [ "%ha%" ],
        "post_tags" : [ "%he%" ]
      }
    }
  },
  "_source": ["uuid", "language"]
}
</code>```

My auto field used the autocomplete analyzer.

```<code>"auto": {
  "type": "string",
  "analyzer": "autocomplete"
}
</code>```

And this is the index configuration that I'm using:

```<code>{
  "analysis": {
    "filter": {
      "my_stop": {
        "type":       "stop",
        "stopwords":  "_english_"
      },
      "autocomplete_filter": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 20
      }
    },
    "analyzer": {
      "autocomplete": {
        "type": "custom",
        "tokenizer": "standard",
        "filter": [
          "lowercase",
          "my_stop",
          "autocomplete_filter"
        ]
      }
    }
  }
}
</code>```

The solution was mainly inspired by the Search-as-you-type post.

I process the response JSON in order to get the autocomplete options.
The highlight information is used to extract all found tokens. These tokens are next used to construct the potential autocomplete phrase by also comparing it to the phrase that the user has already entered. The neat thing is that a stop word filter can be applied and thus stopwords will never be highlighted and in turn never be used for autocomplete suggestions.

A PoC Java code of this processor can be found here

I'm not yet sure whether I'll run with this solution but I want to share it anyway.

Body:
I'm currently using highlight information of the query in order to construct the autocomplete options.

My Query:

{
  "query": {
    "match": {
      "fields.content.auto": {
        "query": "content co",
        "analyzer": "standard"
      }
    }
  },
  "highlight": {
    "fields": {
      "fields.content.auto": {
        "fragment_size": 0,
        "number_of_fragments": 10,
        "pre_tags" : [ "%ha%" ],
        "post_tags" : [ "%he%" ]
      }
    }
  },
  "_source": ["uuid", "language"]
}

My auto field used the autocomplete analyzer.

"auto": {
  "type": "string",
  "analyzer": "autocomplete"
}

And this is the index configuration that I'm using:

{
  "analysis": {
    "filter": {
      "my_stop": {
        "type":       "stop",
        "stopwords":  "_english_"
      },
      "autocomplete_filter": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 20
      }
    },
    "analyzer": {
      "autocomplete": {
        "type": "custom",
        "tokenizer": "standard",
        "filter": [
          "lowercase",
          "my_stop",
          "autocomplete_filter"
        ]
      }
    }
  }
}

The solution was mainly inspired by the Search-as-you-type post.

I process the response JSON in order to get the autocomplete options.
The highlight information is used to extract all found tokens. These tokens are next used to construct the potential autocomplete phrase by also comparing it to the phrase that the user has already entered. The neat thing is that a stop word filter can be applied and thus stopwords will never be highlighted and in turn never be used for autocomplete suggestions.

A PoC Java code of this processor can be found here

I'm not yet sure whether I'll run with this solution but I want to share it anyway.


问:
Cannot convert String array to Int array from core data and sum it in Swift 4
I have 2 question. First, I can't convert String array to Int array from core data

```<code>let sum = recordFilter.map{$0.amount!.dropFirst()} //["9.99", "6.58"]
let intSum = sum.map({Int($0)})  //[nil, nil]
</code>```

My array format:

```<code>[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), ...})]
</code>```

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)' How to fix it?

```<code>let sum = recordFilter.map{$0.amount!.dropFirst()}.reduce(0, +)
let intSum = sum.map({Int($0)}).reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)'
</code>```

答:
First, I can't convert String array to Int array from core data

From the description of init?(_ description: String)

The string passed as description may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9)

9.99 is an invalid format for an Int which is probably why the map that tries to do the conversion is returning nil for each element.

If you do this:

```<code>let doubleSum = sum.map({Double($0)})
</code>```

You'll get close to what you want but the elements of the array will be optionals.

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)'

The problem is that the constructor returns an optional. One way to fix this would be to unwrap the optionals but make nils zero for the purpose of the addition.

```<code>let doubleSum = sum.map{ Double($0) ?? 0.0 }.reduce(0, +)
</code>```

you'll get what you want. The ?? unwraps the result of the string to double conversion, using 0 where the conversion fails.

Or, even better, as Martin R suggests, you can use flatMap to eliminate the need for ??.

```<code>let doubleSum = sum.flatMap{ Double($0) }.reduce(0, +)
</code>```

Body:
I have 2 question. First, I can't convert String array to Int array from core data

let sum = recordFilter.map{$0.amount!.dropFirst()} //["9.99", "6.58"]
let intSum = sum.map({Int($0)})  //[nil, nil]

My array format:

[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), ...})]

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)' How to fix it?

let sum = recordFilter.map{$0.amount!.dropFirst()}.reduce(0, +)
let intSum = sum.map({Int($0)}).reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)'

Body:
First, I can't convert String array to Int array from core data

From the description of init?(_ description: String)

The string passed as description may begin with a plus or minus sign character (+ or -), followed by one or more numeric digits (0-9)

9.99 is an invalid format for an Int which is probably why the map that tries to do the conversion is returning nil for each element.

If you do this:

let doubleSum = sum.map({Double($0)})

You'll get close to what you want but the elements of the array will be optionals.

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)'

The problem is that the constructor returns an optional. One way to fix this would be to unwrap the optionals but make nils zero for the purpose of the addition.

let doubleSum = sum.map{ Double($0) ?? 0.0 }.reduce(0, +)

you'll get what you want. The ?? unwraps the result of the string to double conversion, using 0 where the conversion fails.

Or, even better, as Martin R suggests, you can use flatMap to eliminate the need for ??.

let doubleSum = sum.flatMap{ Double($0) }.reduce(0, +)


问:
File metadata not kept in S3 after a CLI copy
I have two buckets (let‘s say A and B) in different regions. I have archives in the bucket A with a metadata (x-amz-meta-mymeta). I do perform a copy command using the CLI:

```<code>aws s3 cp s3://A/${file}.tar.gz s3://B/
</code>```

Depending on the file, metadata are kept or not. Files pikachu have both the same metadata after the copy, but a file pika-chu does not have the metadata in the target bucket B.

I have read the doc but could not find any other information than the one exposed in this SO answer.

The metadata is lost even though the destination file already exists or not.

Any hints on that?

Edit: metadata is lost even if the copy command is

```<code>aws s3 cp s3://A/${file}.tar.gz s3://B/${file}
</code>```

Edit: For info, the size of the files differs, pikachu is few Mb large whereas pika-chu is more like 50Mb.

Edit: Files are uploaded using aws s3 cp with no multipart information.

答:
Here is the official documentation on the PUT COPY REST API.

Look into the x-amz-metadata-directive.

REST Object Copy

For the CLI add (valid only for files smaller than 5 GB and no multipart copy / upload - multipart copy does not preserve all headers):

```<code>--metadata-directive COPY
</code>```

--metadata-directive (string) Specifies whether the metadata is copied from the source object or replaced with metadata provided when copying
  S3 objects. Note that if the object is copied over in parts, the
  source object's metadata will not be copied over, no matter the value
  for --metadata-directive, and instead the desired metadata values must
  be specified as parameters on the command line. Valid values are COPY
  and REPLACE. If this parameter is not specified, COPY will be used by
  default. If REPLACE is used, the copied object will only have the
  metadata values that were specified by the CLI command. Note that if
  you are using any of the following parameters: --content-type,
  content-language, --content-encoding, --content-disposition,
  --cache-control, or --expires, you will need to specify --metadata-directive REPLACE for non-multipart copies if you want the copied objects to have the specified metadata values.

[EDIT after question]

The AWS CLI will automatically use multipart upload. This is configurable. This link shows the S3 configuration options.

AWS CLI S3 Configuration

Body:
I have two buckets (let‘s say A and B) in different regions. I have archives in the bucket A with a metadata (x-amz-meta-mymeta). I do perform a copy command using the CLI:

aws s3 cp s3://A/${file}.tar.gz s3://B/

Depending on the file, metadata are kept or not. Files pikachu have both the same metadata after the copy, but a file pika-chu does not have the metadata in the target bucket B.

I have read the doc but could not find any other information than the one exposed in this SO answer.

The metadata is lost even though the destination file already exists or not.

Any hints on that?

Edit: metadata is lost even if the copy command is

aws s3 cp s3://A/${file}.tar.gz s3://B/${file}

Edit: For info, the size of the files differs, pikachu is few Mb large whereas pika-chu is more like 50Mb.

Edit: Files are uploaded using aws s3 cp with no multipart information.

Body:
Here is the official documentation on the PUT COPY REST API.

Look into the x-amz-metadata-directive.

REST Object Copy

For the CLI add (valid only for files smaller than 5 GB and no multipart copy / upload - multipart copy does not preserve all headers):

--metadata-directive COPY

--metadata-directive (string) Specifies whether the metadata is copied from the source object or replaced with metadata provided when copying
  S3 objects. Note that if the object is copied over in parts, the
  source object's metadata will not be copied over, no matter the value
  for --metadata-directive, and instead the desired metadata values must
  be specified as parameters on the command line. Valid values are COPY
  and REPLACE. If this parameter is not specified, COPY will be used by
  default. If REPLACE is used, the copied object will only have the
  metadata values that were specified by the CLI command. Note that if
  you are using any of the following parameters: --content-type,
  content-language, --content-encoding, --content-disposition,
  --cache-control, or --expires, you will need to specify --metadata-directive REPLACE for non-multipart copies if you want the copied objects to have the specified metadata values.

[EDIT after question]

The AWS CLI will automatically use multipart upload. This is configurable. This link shows the S3 configuration options.

AWS CLI S3 Configuration


问:
Angularjs file upload
html

```<code>    <form method='POST' enctype='multipart/form-data' name="formName">
        <div class="row">
            <div class="col-md-6">
                <input type="file" style="text-align: left" ng-model="value" class="btn"/>
            </div>
            <div class="col-md-2">
                <input type="submit" value="upload" class="btn btn-info" ng-click="submitFile()"/>
            </div>
        </div>
    </form>
</code>```

AngularJs

```<code>$scope.submitFile = function(){
    document.formName.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid; //$rootScope.reply.Sid is secession id
    document.formName.submit();
};
</code>```

I am trying to do a fileupload with AngularJs. Will this logic work?. My selected path is also coming as given below.

```<code>C:\fakepath\license.txt
</code>```

Is this an error?

Note:
Our UI team was able to the fileupload with the below code. I was trying to attain the same thing in AngularJs

```<code><body>
    <form method='POST' enctype='multipart/form-data' action="http://xxx.xxx.xx.xxx:xxxx/yyy/yyyyyyyyy?s=3e3646ea-48cc-4342-a388-e0c0d7bbf4e4"/'>
    File to upload: <input type=file id='up_file' name=upfile><br>
</body>
</code>```

答:
I am providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.

```<code><html>

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>

   <body ng-app = "myApp">

      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>

      <script>
         var myApp = angular.module('myApp', []);

         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;

                  element.bind('change', function(){
                     scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);

         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);

               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })

               .success(function(){
               })

               .error(function(){
               });
            }
         }]);

         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;

               console.log('file is ' );
               console.dir(file);

               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);

      </script>

   </body>
</html>
</code>```

This is a working example with no other dependencies than AngularJS

Title: Angularjs file upload

Body:
html

    <form method='POST' enctype='multipart/form-data' name="formName">

                <input type="file" style="text-align: left" ng-model="value" class="btn"/>

                <input type="submit" value="upload" class="btn btn-info" ng-click="submitFile()"/>

    </form>

AngularJs

$scope.submitFile = function(){
    document.formName.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid; //$rootScope.reply.Sid is secession id
    document.formName.submit();
};

I am trying to do a fileupload with AngularJs. Will this logic work?. My selected path is also coming as given below.

C:\fakepath\license.txt

Is this an error?

Note:
Our UI team was able to the fileupload with the below code. I was trying to attain the same thing in AngularJs

    <form method='POST' enctype='multipart/form-data' action="http://xxx.xxx.xx.xxx:xxxx/yyy/yyyyyyyyy?s=3e3646ea-48cc-4342-a388-e0c0d7bbf4e4"/'>
    File to upload: <input type=file id='up_file' name=upfile>

Body:
I am providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.

<html>

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>

   <body ng-app = "myApp">

      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>

      <script>
         var myApp = angular.module('myApp', []);

         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;

                  element.bind('change', function(){
                     scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);

         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);

               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })

               .success(function(){
               })

               .error(function(){
               });
            }
         }]);

         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;

               console.log('file is ' );
               console.dir(file);

               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);

      </script>

   </body>
</html>

This is a working example with no other dependencies than AngularJS


问:
Compile Python Program include imports
I wrote a Python program on my Mac running Python 2.7.10.

It's just 1 single .py file.
The first few lines of the program are like this:

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

import clipboard
import time
import sys
import os
import pyperclip
import re

sys.path.append(os.path.abspath("SO_site-packages"))
</code>```

I want to compile this .py file to an .exe that can be run on any Windows machine.

I thus want to include the imported libraries in the .exe.

Is this even possible? If yes, how do I achieve this?

答:
If you're using Mac you need this package: http://www.pyinstaller.org/

call it using: pyinstaller -F myscript.py

You can use py2exe if you're under windows: http://www.py2exe.org/index.cgi/Tutorial

You will create a separate setup.py that will call your python script.

Title: Compile Python Program include imports

Body:
I wrote a Python program on my Mac running Python 2.7.10.

It's just 1 single .py file.
The first few lines of the program are like this:

#!/usr/bin/env python

import clipboard
import time
import sys
import os
import pyperclip
import re

sys.path.append(os.path.abspath("SO_site-packages"))

I want to compile this .py file to an .exe that can be run on any Windows machine.

I thus want to include the imported libraries in the .exe.

Is this even possible? If yes, how do I achieve this?


问:
PHP setlocale has no effect
The setlocale() function doesn't set the desired language (German).

The goal is to output month names.

This is my test code with trials so far:

```<code><?php

date_default_timezone_set('Europe/Berlin');
setlocale(LC_ALL, 'de_DE.utf8');
// Or
setlocale(LC_ALL, 'de_DE@euro');
// Or
setlocale(LC_ALL, 'de_DE');
// Or
setlocale(LC_ALL, 'de');
// Or
setlocale(LC_ALL, 'ge');

echo strftime('%B');
</code>```

Output:

June

instead of

Juni

Any suggestions?

I don't have ssh or other shell access.

The script is running on a linux server.

PHP version 5.6

答:
If your are on a Red Hat machine you can run :

```<code>localedef -v -c -i de_DE -f UTF-8 de_DE.UTF-8
</code>```

Then restart your Apache server

Title: PHP setlocale has no effect

Body:
The setlocale() function doesn't set the desired language (German).

The goal is to output month names.

This is my test code with trials so far:

<?php

date_default_timezone_set('Europe/Berlin');
setlocale(LC_ALL, 'de_DE.utf8');
// Or
setlocale(LC_ALL, 'de_DE@euro');
// Or
setlocale(LC_ALL, 'de_DE');
// Or
setlocale(LC_ALL, 'de');
// Or
setlocale(LC_ALL, 'ge');

echo strftime('%B');

Output:

June

instead of

Juni

Any suggestions?

I don't have ssh or other shell access.

The script is running on a linux server.

PHP version 5.6

Body:
If your are on a Red Hat machine you can run :

localedef -v -c -i de_DE -f UTF-8 de_DE.UTF-8

Then restart your Apache server


问:
Converting oracle to mysql to select listagg and left join
Please, I have the below oracle query to select post and list all share image attached to a post and at the same time join user table and post table. My problem now is to run this query in MySQL. I have tried so many modifications but it kept giving me errors can someone help out?

```<code>SELECT
        post_image_id,
        LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
        FROM social_post_photos
        GROUP BY post_image_id;

        WITH i AS (
          SELECT post_image_id,
            LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
          FROM social_post_photos
          GROUP BY post_image_id
        )

        SELECT sp.post_body_message, i.imgs AS images
        FROM social_posts sp
        LEFT JOIN vendor_account va
           ON sp.vendor_owner_id = va.eu_vendor_id
        LEFT JOIN i
           ON sp.social_page_id = i.post_image_id

           WHERE sp.social_page_id = 'page1'
           AND sp.vendor_owner_id = 'v100'
</code>```

FULL DEMO WITH TABLE http://sqlfiddle.com/#!9/9c39ef/2

答:
The mysql equivalent of listagg is group_concat -

```<code>SELECT
        post_image_id,
        group_concat(photo_url ORDER BY photo_url) imgs
        FROM social_post_photos
        GROUP BY post_image_id;
</code>```

There is no with(cte) in mysql until version 8 but i think you can replace this in your query with a sub query to create i.

Body:
Please, I have the below oracle query to select post and list all share image attached to a post and at the same time join user table and post table. My problem now is to run this query in MySQL. I have tried so many modifications but it kept giving me errors can someone help out?

SELECT
        post_image_id,
        LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
        FROM social_post_photos
        GROUP BY post_image_id;

        WITH i AS (
          SELECT post_image_id,
            LISTAGG(photo_url, ", ") WITHIN GROUP (ORDER BY photo_url) imgs
          FROM social_post_photos
          GROUP BY post_image_id
        )

        SELECT sp.post_body_message, i.imgs AS images
        FROM social_posts sp
        LEFT JOIN vendor_account va
           ON sp.vendor_owner_id = va.eu_vendor_id
        LEFT JOIN i
           ON sp.social_page_id = i.post_image_id

           WHERE sp.social_page_id = 'page1'
           AND sp.vendor_owner_id = 'v100'

FULL DEMO WITH TABLE http://sqlfiddle.com/#!9/9c39ef/2

Body:
The mysql equivalent of listagg is group_concat -

SELECT
        post_image_id,
        group_concat(photo_url ORDER BY photo_url) imgs
        FROM social_post_photos
        GROUP BY post_image_id;

There is no with(cte) in mysql until version 8 but i think you can replace this in your query with a sub query to create i.


问:
How to loop through cookie's lengths that starts with a specific word?
I have used this method on PHP in the past, but cant figure out how to do it in javascript.

Basically I want to loop through a list of cookie that starts with the word "order" each cookie order contains the word "order" plus a unique number to it. the unique number is unknown which is why i need a loop to find out a specific "order".

So the idea is i need to some how check if word "order" exist in a cookie once I find out how many then I can loop that many times.

This is what I have in PHP I would need something like this in javascript.

```<code>foreach ($_COOKIE as $name=>$value){
    if(strpos($name, 'order') !== false){
    //do something amazing!!!!
    }
}
</code>```

答:
Try this</p>

```<code>var yourcookie;
    if (navigator.cookieEnabled) {
      cookieArray = document.cookie.split(";");
      cookieArray.forEach(myFunction);

      console.log(cookieArray)

      function myFunction(item, index) {
        if (item.split("=")[0] == " yourcookie" || item.split("=")[0] == "yourcookie") {
          yourcookie = item.split("=")[1];
          console.log("yourcookie " + yourcookie)
        }
      }
    }
</code>```

Body:
I have used this method on PHP in the past, but cant figure out how to do it in javascript.

Basically I want to loop through a list of cookie that starts with the word "order" each cookie order contains the word "order" plus a unique number to it. the unique number is unknown which is why i need a loop to find out a specific "order".

So the idea is i need to some how check if word "order" exist in a cookie once I find out how many then I can loop that many times.

This is what I have in PHP I would need something like this in javascript.

foreach ($_COOKIE as $name=>$value){
    if(strpos($name, 'order') !== false){
    //do something amazing!!!!
    }
}

Body:
Try this

var yourcookie;
    if (navigator.cookieEnabled) {
      cookieArray = document.cookie.split(";");
      cookieArray.forEach(myFunction);

      console.log(cookieArray)

      function myFunction(item, index) {
        if (item.split("=")[0] == " yourcookie" || item.split("=")[0] == "yourcookie") {
          yourcookie = item.split("=")[1];
          console.log("yourcookie " + yourcookie)
        }
      }
    }


问:
Flash cs5 form TLF is not receiving hebrew in some computers and do in others
i have a TLF in a form in one of my sites.

from a reason i can not trace, in some cases users report that they can not write in hebrew while they can in english.
 i know that others can as
1. i get completed forms in hebrew to my mail.
2. i can write in hebrew in my computers (mac and pc with win xp).

the users report that in hebrew they cant write nothing as the TLF is not responding to their typing.

the problem is the same when i try to embed the fonts and when i try to use "use system fonts" with Arial font.

i have asked one of my users who have reported that issue to update his flash player but that didn't help.

i have tried to get the users OS and browser and could not find any consistency.

I will appreciate any help as i am stuck.

thanks
shani

答:
What WMODE do you use?

There are many known issues regarding dynamic fonts and "opaque" or "transparent" WMODE.

Try to search in the Adobe Flash Player Bug and Issue Management System.


问:
Select only IDs of customers that have orders in every year
Somehow I am getting the wrong customer IDs, I only want the IDs that have ordered in every year at least once since the date of the first order.

Table orders:

```<code>o_id   o_c_id   o_type    o_date
1345   13       TA        2015-01-01
7499   13       TA        2015-01-16
7521   15       GA        2015-01-08
7566   16       TA        2016-01-24
7654   15       FB        2016-01-28
</code>```

Table customers:

```<code>c_id   c_name    c_email
13     Trump     example@gmail.com
14     Obama     example@gmail.com
15     Miguel    example@gmail.com
16     Dequavo   example@gmail.com
</code>```

My query:

SELECT c_id, YEAR(o_date), c_email
FROM orders
WHERE YEAR(o_date) BETWEEN YEAR(MIN(o_date)) AND YEAR(CURDATE())
GROUP BY YEAR(o_date)
HAVING COUNT(c_id) > 0
ORDER BY c_id
```

答:
AS indoor question you're only asking for the Customer ID I've got you an example of what you might be looking for. Feel free to change the query as I'm only selecting the o_c_id assuming that is the Customer ID

```<code>SELECT
  o_c_id
FROM
  orders
GROUP BY
  o_c_id
HAVING
  (MIN(YEAR(o_date)) + COUNT(DISTINCT(YEAR(o_date))) -1) = YEAR(NOW())
</code>```

This should give you a list of all the o_c_id that have placed an order every year since their first order.

Body:
Somehow I am getting the wrong customer IDs, I only want the IDs that have ordered in every year at least once since the date of the first order.

Table orders:

o_id   o_c_id   o_type    o_date
1345   13       TA        2015-01-01
7499   13       TA        2015-01-16
7521   15       GA        2015-01-08
7566   16       TA        2016-01-24
7654   15       FB        2016-01-28

Table customers:

c_id   c_name    c_email
13     Trump     example@gmail.com
14     Obama     example@gmail.com
15     Miguel    example@gmail.com
16     Dequavo   example@gmail.com

My query:

SELECT c_id, YEAR(o_date), c_email
FROM orders
WHERE YEAR(o_date) BETWEEN YEAR(MIN(o_date)) AND YEAR(CURDATE())
GROUP BY YEAR(o_date)
HAVING COUNT(c_id) > 0
ORDER BY c_id

Body:
AS indoor question you're only asking for the Customer ID I've got you an example of what you might be looking for. Feel free to change the query as I'm only selecting the o_c_id assuming that is the Customer ID

SELECT
  o_c_id
FROM
  orders
GROUP BY
  o_c_id
HAVING
  (MIN(YEAR(o_date)) + COUNT(DISTINCT(YEAR(o_date))) -1) = YEAR(NOW())

This should give you a list of all the o_c_id that have placed an order every year since their first order.


答:
```<code>const theCookies = document.cookie.split(';');
theCookies.forEach(cookie => {
  // do something amazing !!
});
</code>```

Title: How to loop through cookie's lengths that starts with a specific word?