问:
INotifyPropertyChanged wrapper
I found some solution of INotifyPropertyChanged wrapper but it doesnot do anything. What I am doing wrong? Name updating asynchronous but value in windows do not change. Why?*                                                                                *

```<code>namespace WpfApplication1.ViewModel
{
class CustomerViewModel : INotifyPropertyChanged, IWeakEventListener
{
    private readonly Customer _customer;

    internal CustomerViewModel(Customer customer)
    {
        if (customer == null)
        {
            throw new ArgumentNullException("personModel");
        }

        _customer = customer;
        NotifyPropertyChangedEventManager.AddListener(_customer, this);

        Action Start = new Action(UpdateAsync);
        IAsyncResult result = Start.BeginInvoke(null, null);
    }
    private void UpdateAsync()
    {
        int i = 0;
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
            _customer.Name = (++i).ToString();
        }
    }

    public string Name
    {
        get { return _customer.Name; }
        set { _customer.Name = value; }
    }

    public string JobTitle
    {
        get { return _customer.Work; }
        set { _customer.Work = value; }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region IWeakEventListener Members
    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        PropertyChangedEventArgs pcArgs = e as PropertyChangedEventArgs;
        if (pcArgs != null)
        {
            OnPropertyChanged(pcArgs.PropertyName);
            return true;
        }
        return false;
    }
    #endregion
}
public class NotifyPropertyChangedEventManager : WeakEventManager
{
    public static NotifyPropertyChangedEventManager CurrentManager
    {
        get
        {
            var manager_type = typeof(NotifyPropertyChangedEventManager);
            var manager = WeakEventManager.GetCurrentManager(manager_type) as NotifyPropertyChangedEventManager;
            if (manager == null)
            {
                manager = new NotifyPropertyChangedEventManager();
                WeakEventManager.SetCurrentManager(manager_type, manager);
            }
            return manager;
        }
    }

    public static void AddListener(INotifyPropertyChanged source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedAddListener(source, listener);
        return;
    }

    public static void RemoveListener(INotifyPropertyChanged source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedRemoveListener(source, listener);
        return;
    }
    protected override void StartListening(object source)
    {
        ((INotifyPropertyChanged)source).PropertyChanged += Source_PropertyChanged; return;
    }
    protected override void StopListening(object source)
    {
        ((INotifyPropertyChanged)source).PropertyChanged -= Source_PropertyChanged;
        return;
    }

    void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        { CurrentManager.DeliverEvent(sender, e); };
    }
}
</code>```

}

Customer

```<code>    public class Customer:INotifyPropertyChanged
{
    public string Name { get; set; }
    public string Number { get; set; }
    public string Work { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

And Xaml code

```<code><Grid>
    <Label Content="{Binding Name}"></Label>
</Grid>
</code>```

答:
I know this question is old and doesn't exactly answer your question.  I thought this would be a better solution for you.

Bindable uses a dictionary as a property store. It's easy enough to add the necessary overloads for a subclass to manage its own backing field using ref parameters.

No magic string

No reflection

Can be improved to suppress the default dictionary lookup

The code:

```<code>    public class Bindable : INotifyPropertyChanged
    {
        private Dictionary<string, object> _properties = new Dictionary<string, object>();

        /// <summary>
        /// Gets the value of a property
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T Get<T>([CallerMemberName] string name = null)
        {
            object value = null;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T)value;
            return default(T);
        }

        /// <summary>
        /// Sets the value of a property
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="name"></param>
        protected void Set<T>(T value, [CallerMemberName] string name = null)
        {
            if (Equals(value, Get<T>(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
</code>```

used like this

```<code>public class Item : Bindable
{
     public Guid Id { get { return Get<Guid>(); } set { Set<Guid>(value); } }
}
</code>```

Title: INotifyPropertyChanged wrapper

Body:
I found some solution of INotifyPropertyChanged wrapper but it doesnot do anything. What I am doing wrong? Name updating asynchronous but value in windows do not change. Why?*                                                                                *

namespace WpfApplication1.ViewModel
{
class CustomerViewModel : INotifyPropertyChanged, IWeakEventListener
{
    private readonly Customer _customer;

    internal CustomerViewModel(Customer customer)
    {
        if (customer == null)
        {
            throw new ArgumentNullException("personModel");
        }

        _customer = customer;
        NotifyPropertyChangedEventManager.AddListener(_customer, this);

        Action Start = new Action(UpdateAsync);
        IAsyncResult result = Start.BeginInvoke(null, null);
    }
    private void UpdateAsync()
    {
        int i = 0;
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
            _customer.Name = (++i).ToString();
        }
    }

    public string Name
    {
        get { return _customer.Name; }
        set { _customer.Name = value; }
    }

    public string JobTitle
    {
        get { return _customer.Work; }
        set { _customer.Work = value; }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region IWeakEventListener Members
    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        PropertyChangedEventArgs pcArgs = e as PropertyChangedEventArgs;
        if (pcArgs != null)
        {
            OnPropertyChanged(pcArgs.PropertyName);
            return true;
        }
        return false;
    }
    #endregion
}
public class NotifyPropertyChangedEventManager : WeakEventManager
{
    public static NotifyPropertyChangedEventManager CurrentManager
    {
        get
        {
            var manager_type = typeof(NotifyPropertyChangedEventManager);
            var manager = WeakEventManager.GetCurrentManager(manager_type) as NotifyPropertyChangedEventManager;
            if (manager == null)
            {
                manager = new NotifyPropertyChangedEventManager();
                WeakEventManager.SetCurrentManager(manager_type, manager);
            }
            return manager;
        }
    }

    public static void AddListener(INotifyPropertyChanged source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedAddListener(source, listener);
        return;
    }

    public static void RemoveListener(INotifyPropertyChanged source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedRemoveListener(source, listener);
        return;
    }
    protected override void StartListening(object source)
    {
        ((INotifyPropertyChanged)source).PropertyChanged += Source_PropertyChanged; return;
    }
    protected override void StopListening(object source)
    {
        ((INotifyPropertyChanged)source).PropertyChanged -= Source_PropertyChanged;
        return;
    }

    void Source_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        { CurrentManager.DeliverEvent(sender, e); };
    }
}

}

Customer

    public class Customer:INotifyPropertyChanged
{
    public string Name { get; set; }
    public string Number { get; set; }
    public string Work { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

And Xaml code

<Grid>

</Grid>

Body:
I know this question is old and doesn't exactly answer your question.  I thought this would be a better solution for you.

Bindable uses a dictionary as a property store. It's easy enough to add the necessary overloads for a subclass to manage its own backing field using ref parameters.

No magic string

No reflection

Can be improved to suppress the default dictionary lookup

The code:

    public class Bindable : INotifyPropertyChanged
    {
        private Dictionary<string, object> _properties = new Dictionary<string, object>();

        /// <summary>
        /// Gets the value of a property
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T Get<T>([CallerMemberName] string name = null)
        {
            object value = null;
            if (_properties.TryGetValue(name, out value))
                return value == null ? default(T) : (T)value;
            return default(T);
        }

        /// <summary>
        /// Sets the value of a property
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="name"></param>
        protected void Set<T>(T value, [CallerMemberName] string name = null)
        {
            if (Equals(value, Get<T>(name)))
                return;
            _properties[name] = value;
            OnPropertyChanged(name);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

used like this

public class Item : Bindable
{
     public Guid Id { get { return Get<Guid>(); } set { Set<Guid>(value); } }
}


来源: stackexchange

问:
Add a COUNTIFS column to a Pandas DataFrame
I'm working with a Pandas DataFrame in Python, that contains the first 2 columns from the below image: user_id, user_time.

I simply need to add the 3rd column to it, which is basically the sequence of "user_time" for each "user_id". In Excel, the formula would be:

=COUNTIFS([user_id],[@[user_id]], [user_time], "<="&[@[user_time]])

How would I do that in Python, please?

答:
You need cumcount.

Thanks Ding for comment - if necessary use sort_values:

```<code>df = df.sort_values(['user_id', 'user_time'])
df['COUNTIFS'] = df.groupby('user_id').cumcount() + 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You need cumcount.

Thanks Ding for comment - if necessary use sort_values:

df = df.sort_values(['user_id', 'user_time'])
df['COUNTIFS'] = df.groupby('user_id').cumcount() + 1


问:
execute function in created and inserted DOM element
My intention is very simple: I have a newSpan() function, that creates a new span and inserts it before the first child of the main element (or appends it if main is empty), and a letterTyper() function, that fills the inserted element with the string stored in a CONTENT constant while generating a sort of backwards typing effect. The idea is to create a new element and then triggering the effect inside it a given number of times with a loop in window.onload.

But when I fill the window.onload anonymous function with

```<code>window.onload = function() {
  newSpan();
  letterTyper();
  newSpan();
  letterTyper();
}
</code>```

What I end up with in the DOM is

```<code><main>
  <span id="#span1">lorem ipsum</span>
  <span id="#span0"></span>
</main>
</code>```

I also tried to use a DOMContentLoaded event, to no effect. Why is that? What am I doing wrong?

My code:

```<code>const CONTENT = 'lorem ipsum';
var main = document.querySelector('main');
var spanId = 0;
var charCount = CONTENT.length;

window.onload = function() {
  newSpan();
  letterTyper();
  newSpan();
  letterTyper();
}

function newSpan() {
  var newSpan = document.createElement('span');
  var isEmpty = main.innerHTML === '';

  newSpan.setAttribute('id', '#span' + spanId);

  if (isEmpty) {
    main.appendChild(newSpan);
  } else {
    main.insertBefore(newSpan, document.getElementById('#span' + (spanId - 1)));
  }

  spanId++;
}

function letterTyper() {
  var targetSpan = main.firstChild;
  targetSpan.textContent = CONTENT.substring(charCount, charCount + 1) + targetSpan.textContent.substring(0, targetSpan.textContent.length);
  charCount--;

  if ( charCount < 0) {
      clearTimeout(timer);
      charCount = CONTENT.length;
  } else {
      timer = setTimeout('letterTyper()', 100);
  }
}
</code>```

答:
setTimeout is asynchronous. When you call letterTyper for the first time, it will return to your window.onload and trigger the next newSpan() and letterTyper().

That means that the letterTyper loop of the first span interferes with the second loop, because the first loop hasn't finished when the second one is started. In other words, the second loop is never created, but all calls of letterTyper will see the #span1 element (the second span element) as the first child of main.

You have to wait until the first loop is finished before you start the second loop. I suggest you take a look at Promises.

I changed a few things in your code so that is now uses promises:

const CONTENT = 'lorem ipsum';
var main = document.querySelector('main');
var spanId = 0;
var charCount = CONTENT.length;

window.onload = function() {
  // start the first loop
  letterTyper(newSpan()).then(function () {
    // the first loop has finished, start the second loop
    return letterTyper(newSpan());
  }).then(function () {
    // the second loop has finished, start the third loop
    return letterTyper(newSpan());
  });
}

function newSpan() {
  var newSpan = document.createElement('span');
  var isEmpty = main.children.length === 0;

  newSpan.setAttribute('id', '#span' + spanId);

  if (isEmpty) {
    main.appendChild(newSpan);
  } else {
    main.insertBefore(newSpan, document.getElementById('#span' + (spanId - 1)));
  }

  spanId++;
  charCount = CONTENT.length; // reset the character count

  return newSpan;
}

function letterTyper(span) {
  return new Promise(function (resolve, reject) {
    // executes one tick (adds one character and calls itself after 100ms)
    var tick = function () {
      // prepend a new character
      span.textContent = CONTENT[charCount -= 1] + span.textContent;
      if (charCount > 0) {
        // call tick again in 100ms
        setTimeout(tick, 100);
      } else {
        // loop is finished, the "then" part will be called
        resolve();
      }
    };
    // start the loop
    setTimeout(tick, 100);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main></main></code>```

Body:
My intention is very simple: I have a newSpan() function, that creates a new span and inserts it before the first child of the main element (or appends it if main is empty), and a letterTyper() function, that fills the inserted element with the string stored in a CONTENT constant while generating a sort of backwards typing effect. The idea is to create a new element and then triggering the effect inside it a given number of times with a loop in window.onload.

But when I fill the window.onload anonymous function with

window.onload = function() {
  newSpan();
  letterTyper();
  newSpan();
  letterTyper();
}

What I end up with in the DOM is

  lorem ipsum

I also tried to use a DOMContentLoaded event, to no effect. Why is that? What am I doing wrong?

My code:

const CONTENT = 'lorem ipsum';
var main = document.querySelector('main');
var spanId = 0;
var charCount = CONTENT.length;

window.onload = function() {
  newSpan();
  letterTyper();
  newSpan();
  letterTyper();
}

function newSpan() {
  var newSpan = document.createElement('span');
  var isEmpty = main.innerHTML === '';

  newSpan.setAttribute('id', '#span' + spanId);

  if (isEmpty) {
    main.appendChild(newSpan);
  } else {
    main.insertBefore(newSpan, document.getElementById('#span' + (spanId - 1)));
  }

  spanId++;
}

function letterTyper() {
  var targetSpan = main.firstChild;
  targetSpan.textContent = CONTENT.substring(charCount, charCount + 1) + targetSpan.textContent.substring(0, targetSpan.textContent.length);
  charCount--;

  if ( charCount < 0) {
      clearTimeout(timer);
      charCount = CONTENT.length;
  } else {
      timer = setTimeout('letterTyper()', 100);
  }
}

Body:
setTimeout is asynchronous. When you call letterTyper for the first time, it will return to your window.onload and trigger the next newSpan() and letterTyper().

That means that the letterTyper loop of the first span interferes with the second loop, because the first loop hasn't finished when the second one is started. In other words, the second loop is never created, but all calls of letterTyper will see the #span1 element (the second span element) as the first child of main.

You have to wait until the first loop is finished before you start the second loop. I suggest you take a look at Promises.

I changed a few things in your code so that is now uses promises:

const CONTENT = 'lorem ipsum';
var main = document.querySelector('main');
var spanId = 0;
var charCount = CONTENT.length;

window.onload = function() {
  // start the first loop
  letterTyper(newSpan()).then(function () {
    // the first loop has finished, start the second loop
    return letterTyper(newSpan());
  }).then(function () {
    // the second loop has finished, start the third loop
    return letterTyper(newSpan());
  });
}

function newSpan() {
  var newSpan = document.createElement('span');
  var isEmpty = main.children.length === 0;

  newSpan.setAttribute('id', '#span' + spanId);

  if (isEmpty) {
    main.appendChild(newSpan);
  } else {
    main.insertBefore(newSpan, document.getElementById('#span' + (spanId - 1)));
  }

  spanId++;
  charCount = CONTENT.length; // reset the character count

  return newSpan;
}

function letterTyper(span) {
  return new Promise(function (resolve, reject) {
    // executes one tick (adds one character and calls itself after 100ms)
    var tick = function () {
      // prepend a new character
      span.textContent = CONTENT[charCount -= 1] + span.textContent;
      if (charCount > 0) {
        // call tick again in 100ms
        setTimeout(tick, 100);
      } else {
        // loop is finished, the "then" part will be called
        resolve();
      }
    };
    // start the loop
    setTimeout(tick, 100);
  });
}

<main></main>


问:
Parse Server [Cloud Code]: Handle concurrent requests
Let's say I have some Cloud Code on Parse Server:

```<code>Parse.Cloud.beforeSave("UserProfiles", function(request, response) {
    const query = new Parse.Query("UserProfiles");
    query.equalTo("user", request.user);
    query.count({
        success: function(count) {
            if(count == 0)
                response.success();
            else
                response.error("only one profile is allowed");
            },
        error: function(error) {
                response.error(error.message);
            }
    });
});
</code>```

It works fine unless concurrency happen. If two or more requests at the same time execute creation of new classes then this code wouldn't check that profile under pointer field user already exist.

My question is how properly handle concurrent requests in beforeSave trigger?

答:
If you want to use BeforeSave() you can set the the UserProfiles pointer to the user object before saving like so:

```<code>Parse.Cloud.beforeSave(Parse.User, function(request, respone){
    // only apply to new users
      if(request.object.isNew()){
        var UserProfile = new Parse.Object.extend("UserProfiles");
        var userProfile = new UserProfile();
        return userProfile.save().then(function(savedUserProfile){
          request.object.set("key", savedUserProfile);
          return request.object.save();
        });
      }
});
</code>```

you can achive that by either Cloud jobs, beforeSave or afterSave callbacks

Body:
Let's say I have some Cloud Code on Parse Server:

Parse.Cloud.beforeSave("UserProfiles", function(request, response) {
    const query = new Parse.Query("UserProfiles");
    query.equalTo("user", request.user);
    query.count({
        success: function(count) {
            if(count == 0)
                response.success();
            else
                response.error("only one profile is allowed");
            },
        error: function(error) {
                response.error(error.message);
            }
    });
});

It works fine unless concurrency happen. If two or more requests at the same time execute creation of new classes then this code wouldn't check that profile under pointer field user already exist.

My question is how properly handle concurrent requests in beforeSave trigger?

Body:
If you want to use BeforeSave() you can set the the UserProfiles pointer to the user object before saving like so:

Parse.Cloud.beforeSave(Parse.User, function(request, respone){
    // only apply to new users
      if(request.object.isNew()){
        var UserProfile = new Parse.Object.extend("UserProfiles");
        var userProfile = new UserProfile();
        return userProfile.save().then(function(savedUserProfile){
          request.object.set("key", savedUserProfile);
          return request.object.save();
        });
      }
});

you can achive that by either Cloud jobs, beforeSave or afterSave callbacks


问:
NATS creating duplicate inboxes for reply
I have been playing with NATS messaging, using the C# client. I create a message publisher that sends synchronous requests:

```<code>IConnection connection = new ConnectionFactory().CreateConnection();
Msg rsp = connection.Request("subject", Encoding.ASCII.GetBytes("some text"));
</code>```

I create multiple subscribers using a queue group:

```<code>IConnection connection = new ConnectionFactory().CreateConnection();
connection.SubscribeAsync(
    "subject",
    "queue",
    (sender, args) =>
    {
        connection.Publish(args.Message.Reply, new byte[] { 0x00 });
    });
</code>```

All well and good. I can send multiple messages, each goes to one and only one subscriber, responses are sent.

If I start using multiple queue groups, however, things go wrong. Say I create 20 publishers, publishing using subjects "S1", "S2", "S3", ... For each publisher I create 5 subscribers, so the subscribers for the first publisher have a subject of "S1" and a queue name of "Q1" &c.

When I start a test app running with the 20 publishers each running in their own thread, things quickly stop working. Publishers hang while waiting for synchronous responses.

I added some tracing and it seems that the the reply token is being duplicated. So, for instance, two different subscribers receive messages specifying the same inbox for replies:

```<code>Subject=S3;Reply=_INBOX.C403F3CD707D0EA6F4B1167CE0;Payload=<some text>}
Subject=S4;Reply=_INBOX.C403F3CD707D0EA6F4B1167CE0;Payload=<some text>}
</code>```

I'm guessing the reply can only go to one publisher, so the other one gets lost.

答:
Thank you for raising this; the reply subject being duplicated was a bug.
 A contributor recently added a fix for this issue (stemming from howRandom uses Environment.TickCount as a seed).

The fix is currently in master branch; I'll update this answer when a new release is cut.

Body:
I have been playing with NATS messaging, using the C# client. I create a message publisher that sends synchronous requests:

IConnection connection = new ConnectionFactory().CreateConnection();
Msg rsp = connection.Request("subject", Encoding.ASCII.GetBytes("some text"));

I create multiple subscribers using a queue group:

IConnection connection = new ConnectionFactory().CreateConnection();
connection.SubscribeAsync(
    "subject",
    "queue",
    (sender, args) =>
    {
        connection.Publish(args.Message.Reply, new byte[] { 0x00 });
    });

All well and good. I can send multiple messages, each goes to one and only one subscriber, responses are sent.

If I start using multiple queue groups, however, things go wrong. Say I create 20 publishers, publishing using subjects "S1", "S2", "S3", ... For each publisher I create 5 subscribers, so the subscribers for the first publisher have a subject of "S1" and a queue name of "Q1" &c.

When I start a test app running with the 20 publishers each running in their own thread, things quickly stop working. Publishers hang while waiting for synchronous responses.

I added some tracing and it seems that the the reply token is being duplicated. So, for instance, two different subscribers receive messages specifying the same inbox for replies:

Subject=S3;Reply=_INBOX.C403F3CD707D0EA6F4B1167CE0;Payload=<some text>}
Subject=S4;Reply=_INBOX.C403F3CD707D0EA6F4B1167CE0;Payload=<some text>}

I'm guessing the reply can only go to one publisher, so the other one gets lost.


问:
Java generics - ArrayList initialization
It is known that arraylist init. should be like this

```<code>ArrayList<A> a = new ArrayList<A>();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
</code>```

so, why does java allow these ?

```<code>1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();
</code>```

then, if they are correct why doesn't allow these ?

```<code>1. a1.add(3);
2. a2.add(3);
</code>```

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

```<code>  1. a1.add(null e);
  2. a2.add(? e);
</code>```

I read about this but it is good to hear from you. thanks

the other amusing point is :

```<code> ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above
</code>```

答:
You can't assign a List<Number> to a reference of type List<Integer> because List<Number> allows types of numbers other than Integer. If you were allowed to do that, the following would be allowed:

```<code>List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!
</code>```

The type List<Integer> is making a guarantee that anything it contains will be an Integer. That's why you're allowed to get an Integer out of it without casting. As you can see, if the compiler allowed a List of another type such as Number to be assigned to a List<Integer> that guarantee would be broken.

Assigning a List<Integer> to a reference of a type such as List<?> or List<? extends Number> is legal because the ? means "some unknown subtype of the given type" (where the type is Object in the case of just ? and Number in the case of ? extends Number).

Since ? indicates that you do not know what specific type of object the List will accept, it isn't legal to add anything but null to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X bounded wildcard type. Note that the opposite is true for a ? super X bounded wildcard type... a List<? super Integer> is "a list of some unknown type that is at least a supertype of Integer". While you don't know exactly what type of List it is (could be List<Integer>, List<Number>, List<Object>) you do know for sure that whatever it is, an Integer can be added to it.

Finally, new ArrayList<?>() isn't legal because when you're creating an instance of a paramterized class like ArrayList, you have to give a specific type parameter. You could really use whatever in your example (Object, Foo, it doesn't matter) since you'll never be able to add anything but null to it since you're assigning it directly to an ArrayList<?> reference.

ContentLicense: CC BY-SA 2.5

Body:
It is known that arraylist init. should be like this

ArrayList a = new ArrayList();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

so, why does java allow these ?

1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();

then, if they are correct why doesn't allow these ?

1. a1.add(3);
2. a2.add(3);

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

  1. a1.add(null e);
  2. a2.add(? e);

I read about this but it is good to hear from you. thanks

the other amusing point is :

 ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above

Body:
You can't assign a List<Number> to a reference of type List<Integer> because List<Number> allows types of numbers other than Integer. If you were allowed to do that, the following would be allowed:

List<Number> numbers = new ArrayList<Number>();
numbers.add(1.1); // add a double
List<Integer> ints = numbers;
Integer fail = ints.get(0); // ClassCastException!

The type List<Integer> is making a guarantee that anything it contains will be an Integer. That's why you're allowed to get an Integer out of it without casting. As you can see, if the compiler allowed a List of another type such as Number to be assigned to a List<Integer> that guarantee would be broken.

Assigning a List<Integer> to a reference of a type such as List<?> or List<? extends Number> is legal because the ? means "some unknown subtype of the given type" (where the type is Object in the case of just ? and Number in the case of ? extends Number).

Since ? indicates that you do not know what specific type of object the List will accept, it isn't legal to add anything but null to it. You are, however, allowed to retrieve any object from it, which is the purpose of using a ? extends X bounded wildcard type. Note that the opposite is true for a ? super X bounded wildcard type... a List<? super Integer> is "a list of some unknown type that is at least a supertype of Integer". While you don't know exactly what type of List it is (could be List<Integer>, List<Number>, List<Object>) you do know for sure that whatever it is, an Integer can be added to it.

Finally, new ArrayList<?>() isn't legal because when you're creating an instance of a paramterized class like ArrayList, you have to give a specific type parameter. You could really use whatever in your example (Object, Foo, it doesn't matter) since you'll never be able to add anything but null to it since you're assigning it directly to an ArrayList<?> reference.


问:
Make a photo or video with the camera and automatically find you via GPS
I want to make a button that when you press open the camera and you can take a photo and that automatically takes the coordinates of where you made that photo.
I would appreciate if you could give me the code because I have no idea.

Thanks.

PD: Sorry for my English but I´m not english.

答:
I think your requirement is need to take photo with GPS Location Details. If yes means please refer the following link. It will help you.

Getting location data for a taken photo in Android


问:
Download Google Storage file using acl and redirect
Users can download csv-files från my Google App Enigne-application.
Larger files hit the 1min timeout-window and I have re-imagened my solution giving users read-access in Storage-ACL and redirecting to a downloadlink.

This is a working example for giving the user access and redirects to "https://storage.cloud.google.com/[bucket]/[object]" (1)

```<code>storage_client = storage.Client()
bucket = storage_client.get_bucket(app_identity.get_default_gcs_bucket_name())
acl = bucket.acl
acl.user(ndb_user.primaryEmail).grant_read()
acl.save()

self.redirect("https://storage.cloud.google.com" + filename)
</code>```

It seems my solution don't work programatically nor in-browser.
Any ideas why or suggestions on alternatives ways to actually do this?

1: https://cloud.google.com/storage/docs/xml-api/reference-uris

答:
This doesn't work because you are only granting READ access on the bucket via the the ACL api.  This maps to the IAM Role roles/storage.legacyBucketReader, which does not grant storage.objects.get permission (it only grants storage.buckets.get and storage.objects.list).  If you switch to the new IAM api, and instead grant roles/storage.objectViewer this should work.

That being said, I strongly recommend looking at Signed URLs instead.  Signed URLs will grant temporary access via delegation rather than permanently granting the user access via ACLs and is made for precisely this use case.  Google's google-cloud library has a "generate_signed_url" function you can use to generate them instead of rolling your own.  Here is the documentation.

Body:
Users can download csv-files från my Google App Enigne-application.
Larger files hit the 1min timeout-window and I have re-imagened my solution giving users read-access in Storage-ACL and redirecting to a downloadlink.

This is a working example for giving the user access and redirects to "https://storage.cloud.google.com/[bucket]/[object]" (1)

storage_client = storage.Client()
bucket = storage_client.get_bucket(app_identity.get_default_gcs_bucket_name())
acl = bucket.acl
acl.user(ndb_user.primaryEmail).grant_read()
acl.save()

self.redirect("https://storage.cloud.google.com" + filename)

It seems my solution don't work programatically nor in-browser.
Any ideas why or suggestions on alternatives ways to actually do this?

1: https://cloud.google.com/storage/docs/xml-api/reference-uris


问:
first date and last date of month from month and year
How to get first date and last date of month in oracle by giving input parameter as month.

For eg. if i give input month as 'Jan' and Year as '2016' it should give first date and last date of the month.

答:
You can use TRUNC for that:

First day:

```<code>TRUNC(your_date, 'MM')
</code>```

Last day:

```<code>ADD_MONTHS(TRUNC(your_date, 'MM'), 1) - 1
</code>```

You basically TRUNC the month to its first day, add one month to get the first day of the next month, and then go back a day.

If you do not have a date in the month but only the month and the year you can simply use the first of each month to construct a date:

```<code>TO_DATE('1.' || your_month || '.' || your_year, 'DD.MM.YYYY')
ADD_MONTHS(TO_DATE('1.' || your_month || '.' || your_year, 'DD.MM.YYYY'), 1) - 1
</code>```

Body:
You can use TRUNC for that:

First day:

TRUNC(your_date, 'MM')

Last day:

ADD_MONTHS(TRUNC(your_date, 'MM'), 1) - 1

You basically TRUNC the month to its first day, add one month to get the first day of the next month, and then go back a day.

If you do not have a date in the month but only the month and the year you can simply use the first of each month to construct a date:

TO_DATE('1.' || your_month || '.' || your_year, 'DD.MM.YYYY')
ADD_MONTHS(TO_DATE('1.' || your_month || '.' || your_year, 'DD.MM.YYYY'), 1) - 1


问:
Unique word count on selected word in file python
With Python 2.7 I open an external file which contains:

```<code>Text another word1
Lorem ipsem word1 something
hello first word2 post
</code>```

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

```<code>$ script.py
2x word1
1x word2
</code>```

What I got so far but fails..:

```<code>import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())
</code>```

答:
You can try this:</p>

```<code>from itertools import chain

f = open('datafile.txt').readlines()

f = [i.strip('\n').split() for i in f]

f = list(chain(*f))

new = {i:f.count(i) for i in f if "word" in i}

for a, b in new.items():
    print str(b)+"x"+" "+a
</code>```

Body:
With Python 2.7 I open an external file which contains:

Text another word1
Lorem ipsem word1 something
hello first word2 post

I want to perform an unique count on the word word only, not on the 3rd row.

Desired output:

$ script.py
2x word1
1x word2

What I got so far but fails..:

import os
import sys
from collections import Counter

with open('./file.txt', 'r') as file:
        for item in file:
            if '.sh' in item:
                    all = item.split()[2]
                    print Counter(all.split())

Body:
You can try this:

from itertools import chain

f = open('datafile.txt').readlines()

f = [i.strip('\n').split() for i in f]

f = list(chain(*f))

new = {i:f.count(i) for i in f if "word" in i}

for a, b in new.items():
    print str(b)+"x"+" "+a


问:
Finding an element in a table - selenium
I have a table where I have several columns but what I'm trying to do is to find the Edit link of a certain entity.
The entities names and the edit links are identified as follows:

```<code>@FindBy(css = "div#entity_data_manager_table_cell_name")
public List<WebElement> entityNameList;
@FindBy(css = "button#entity_data_manager_table_item_action_edit")
public List<WebElement> entityEditLinkList;
</code>```

what would be the best way to identify the edit link corresponding to a certain entity name?

答:
Solution 1:

You could use a forward axis or an ancestor in an xpath. Assuming there is a tr that contains your entity and edit button for that entity you could do this:

```<code>//div[@id='entity_data_manager_table_cell_name'][contains(text(),'some identifying text)]/ancestor::tr//button[@id='entity_data_manager_table_item_action_edit']
</code>```

forward axis version:

```<code>//tr[descendant::div[@id='entity_data_manager_table_cell_name'][contains(text(),'some identifying text)]]//button[@id='entity_data_manager_table_item_action_edit']
</code>```

This would probably mean you want a dynamic selector, and not a @FindBy, so something like this:

```<code>protected WebElement getEntityEditButtonElement(string entity)
{
    return driver.findElement(By.xpath(/*xpath from above plugging in the identifiable text*/));
}
</code>```

Solution 2:

Find which index the entity you're looking for is in your entityNameList, and assuming they match up, use that index in your entityEditLinkList to click the correct button. This is a little less precise so I wouldn't recommend it.

Body:
I have a table where I have several columns but what I'm trying to do is to find the Edit link of a certain entity.
The entities names and the edit links are identified as follows:

@FindBy(css = "div#entity_data_manager_table_cell_name")
public List<WebElement> entityNameList;
@FindBy(css = "button#entity_data_manager_table_item_action_edit")
public List<WebElement> entityEditLinkList;

what would be the best way to identify the edit link corresponding to a certain entity name?

Body:
Solution 1:

You could use a forward axis or an ancestor in an xpath. Assuming there is a tr that contains your entity and edit button for that entity you could do this:

//div[@id='entity_data_manager_table_cell_name'][contains(text(),'some identifying text)]/ancestor::tr//button[@id='entity_data_manager_table_item_action_edit']

forward axis version:

//tr[descendant::div[@id='entity_data_manager_table_cell_name'][contains(text(),'some identifying text)]]//button[@id='entity_data_manager_table_item_action_edit']

This would probably mean you want a dynamic selector, and not a @FindBy, so something like this:

protected WebElement getEntityEditButtonElement(string entity)
{
    return driver.findElement(By.xpath(/*xpath from above plugging in the identifiable text*/));
}

Solution 2:

Find which index the entity you're looking for is in your entityNameList, and assuming they match up, use that index in your entityEditLinkList to click the correct button. This is a little less precise so I wouldn't recommend it.


问:
How to round a time down to the nearest 15 minutes in Ruby?
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

```<code>t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
</code>```

答:
Your current evaluation using

```<code>min / 15 * 15
</code>```

is only truncating the min,  so

```<code>15 => 15
16 => 15
..
29 => 15
30 => 30
</code>```

Which is not 'rounding'.

You can approximate rounding in a bad-way with

```<code>(( min + 7.5 ) / 15).to_i * 15
</code>```

Or,  using internals:

```<code>( min.to_f / 15 ).round * 15
</code>```

OwnerDisplayName: Readonly

Body:
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)

Body:
Your current evaluation using

min / 15 * 15

is only truncating the min,  so

15 => 15
16 => 15
..
29 => 15
30 => 30

Which is not 'rounding'.

You can approximate rounding in a bad-way with

(( min + 7.5 ) / 15).to_i * 15

Or,  using internals:

( min.to_f / 15 ).round * 15

OwnerDisplayName: Kent Fredric


问:
How to attach a jQuery event to a grid view that is not visible on document ready?
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from</p>

```<code>              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });
</code>```

答:
Take a look at jQuery.live().

http://api.jquery.com/live/

```<code>$(document).ready(function(){
    $('a .myLink').live('click', function(){
        var link = $(this).attr('href');
        alert(link);
        return false;
    });
});
</code>```

Body:
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from

              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });

Body:
Take a look at jQuery.live().

http://api.jquery.com/live/

$(document).ready(function(){
    $('a .myLink').live('click', function(){
        var link = $(this).attr('href');
        alert(link);
        return false;
    });
});


问:
request not work, Error: Invalid protocol: 127.0.0.1:?
I am new to node.js, I use request send the post request.but I got a error!</p>

```<code>     request({
         method: 'POST',
         url: config.api + '/index',
         body: {
         name: "name"
        },
        json: true
      })

        throw er; // Unhandled 'error' event
        ^

         Error: Invalid protocol: 127.0.0.1:
</code>```

答:
I write this: It work fine, you can modify it like this.</p>

```<code>     request({
           method: 'POST',
           url: 'http://127.0.0.1:3000' + '/index',
           body: {
           name: "name"
          },
          json: true
          })
</code>```

Body:
I am new to node.js, I use request send the post request.but I got a error!

     request({
         method: 'POST',
         url: config.api + '/index',
         body: {
         name: "name"
        },
        json: true
      })

        throw er; // Unhandled 'error' event
        ^

         Error: Invalid protocol: 127.0.0.1:

Body:
I write this: It work fine, you can modify it like this.

     request({
           method: 'POST',
           url: 'http://127.0.0.1:3000' + '/index',
           body: {
           name: "name"
          },
          json: true
          })


问:
Failed to query database

<?php
 //Get Value
 $username = $_POST['user'];
 $password = $_POST['pass'];

 //Connet To The Server And Select Database
 mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
 mysqli_select_db("xxxxx");

 //Query The Database For User
 $result = mysqli_query("select * from user where username = '$username' and password = '$password'")
  or die("Failed to query database ".mysqli_connect_error());
 $row = mysqli_fetch_array($result);
 if (empty($username)) {
  header('Location: fa.html');
 } elseif (empty($password)) {
  header('Location: fa.html');
 } elseif ($row['username'] == $username && $row['password'] == $password){
  header('Location: su.html');
 } else{
  header('Location: fa.html');
 }
?>```

I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".

答:
Add the fourth parameter here as database name like

```<code>mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx", "database_name");
</code>```

and remove

```<code>mysqli_select_db("xxxxx");
</code>```

A sample way of writing php code would be

```<code>$link = mysqli_connect("server_name","username","password","database_name");

if(mysqli_connect_error()) {

    die("There was an error connecting to the database");

}

$query = 'yourQuery';

$result=mysqli_query($link,$query);

if ( false==$result ) {
  printf("error: %s\n", mysqli_error($link));
}
</code>```

This will work

Hope it helps

Title: Failed to query database

Body:
<?php
 //Get Value
 $username = $_POST['user'];
 $password = $_POST['pass'];

 //Connet To The Server And Select Database
 mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
 mysqli_select_db("xxxxx");

 //Query The Database For User
 $result = mysqli_query("select * from user where username = '$username' and password = '$password'")
  or die("Failed to query database ".mysqli_connect_error());
 $row = mysqli_fetch_array($result);
 if (empty($username)) {
  header('Location: fa.html');
 } elseif (empty($password)) {
  header('Location: fa.html');
 } elseif ($row['username'] == $username && $row['password'] == $password){
  header('Location: su.html');
 } else{
  header('Location: fa.html');
 }
?>

I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".

Body:
Add the fourth parameter here as database name like

mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx", "database_name");

and remove

mysqli_select_db("xxxxx");

A sample way of writing php code would be

$link = mysqli_connect("server_name","username","password","database_name");

if(mysqli_connect_error()) {

    die("There was an error connecting to the database");

}

$query = 'yourQuery';

$result=mysqli_query($link,$query);

if ( false==$result ) {
  printf("error: %s\n", mysqli_error($link));
}

This will work

Hope it helps


问:
Removing keyword from list after matching the keyword with answer
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

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

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}
</code>```

and

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

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}
</code>```

but in both cases the score continues to be added

答:
You forgot break in the second foreach. You can't run foreach over collection that you modify inside Foreach!!!! Enumerator allows you only to READ. It becomes not valid after you modify collection.

```<code>foreach (string s in sPattern)
    {

        if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
        {
            sPattern.Remove(s);
            break;
        }
    }
</code>```

Body:
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}

and

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}

but in both cases the score continues to be added

Body:
You forgot break in the second foreach. You can't run foreach over collection that you modify inside Foreach!!!! Enumerator allows you only to READ. It becomes not valid after you modify collection.

foreach (string s in sPattern)
    {

        if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
        {
            sPattern.Remove(s);
            break;
        }
    }


问:
Removing all child node elements from XML in C#?
I have the following XML structure:

XML

```<code><?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
</code>```

At some point, the <Users> gets filled up with different users, but I want to be able to delete them all in a single, simple function.

Attempt

```<code>/// <summary>
/// Removes all nodes from XML creds file on application close
/// </summary>
public static void RemoveXMLData()
{
    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);
    document.RemoveNodes();
}
</code>```

This doesn't seem to be working. I've done the following as well:

Attempt #2

```<code>        string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
        XDocument document = XDocument.Load(xmlPath);

        foreach (var node in document.Descendants("Users"))
        {
            node.Remove();
        }
</code>```

But this yields an exception error.

At the end of the day, I just want to get back to square one with the following file data:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>
</code>```

答:
It probably blows up on the second attempt as you are iterating the collection you remove from.  Try this.</p>

```<code>    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);

    var nodes = document.Descendants("Users");
    while(nodes.Count > 0)
    {
        nodes[0].Remove();
    }
</code>```

Body:
I have the following XML structure:

XML

<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>

At some point, the <Users> gets filled up with different users, but I want to be able to delete them all in a single, simple function.

Attempt

///
/// Removes all nodes from XML creds file on application close
///
public static void RemoveXMLData()
{
    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);
    document.RemoveNodes();
}

This doesn't seem to be working. I've done the following as well:

Attempt #2

        string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
        XDocument document = XDocument.Load(xmlPath);

        foreach (var node in document.Descendants("Users"))
        {
            node.Remove();
        }

But this yields an exception error.

At the end of the day, I just want to get back to square one with the following file data:

<?xml version="1.0" encoding="utf-8" ?>
<Users>
</Users>

Body:
It probably blows up on the second attempt as you are iterating the collection you remove from.  Try this.

    string xmlPath = Path.Combine(Environment.CurrentDirectory, @"Data\Credential.xml");
    XDocument document = XDocument.Load(xmlPath);

    var nodes = document.Descendants("Users");
    while(nodes.Count > 0)
    {
        nodes[0].Remove();
    }


问:
Regular Expression Syntax for URL extraction
I need to extract the string to the right of the equal sign character in an Apache Jmeter project. I am not familiar with Regular Expression syntax at all, but I think this would be the easiest way to extract it. The url is:  https://myserver.com:portnum/im;jsessionid=48E10C95151BFB84D795C90FBC31E8E6
I only need the string to the right of the equal sign, not including the equal sign. My question is, what regular expression should I use to extract the string? Thanks!

答:
It is as simple as =(\w+)

Demo:

References:

JMeter - Regular Expressions

Using RegEx (Regular Expression Extractor) with JMeter

Perl 5 Regex Cheat sheet

Also be aware that there are "smarter" ways of handling JSESSIONID:

In case if it comes as a Cookie you can get its value via HTTP Cookie Manager

If it is being passed as an URL parameter you could use HTTP URL Re-writing Modifier


问:
How to hide y axis?
I plot a horizontal boxplot in MATLAB -- boxplot(y, group,'orientation','horizontal'), and then hide the y-axis using set(gca,'box','off','ycolor','w').

It looks fine on the screen - only the bottom x-axis is visible. But whenever I save the figure to file, using either the print() function or matlabfrag.m, the left y-axis reappears in the output file (although it doesn't show up in MATLAB's visualization of the figure).

How can I keep this y-axis hidden?

答:
Try:</p>

```<code>ax1 = gca;                   % gca = get current axis
ax1.YAxis.Visible = 'off';   % remove y-axis
ax1.XAxis.Visible = 'off';   % remove x-axis
</code>```

Title: How to hide y axis?

Body:
Try:

ax1 = gca;                   % gca = get current axis
ax1.YAxis.Visible = 'off';   % remove y-axis
ax1.XAxis.Visible = 'off';   % remove x-axis


问:
How to build ionic 2 ios app on windows 10?
I am new to ionic 2 and i want to build my app to ios version. What requirements need to install on my windows 10 PC?  Thanks. I hope you can help me. :)</p>

答:
You can't build it to iOS in Windows. Neither in Linux.
You will need an Mac OS.
Either one running on a real Apple device (iMac, Macbook, Mac Mini), or in an virtual box or you can use a cloud service.</p>


问:
Construct a static lookup
Say I have a giant list of definitions that are used to lookup values that an object can default to given a "type number". This type number is unique, and points to data that the object will be set to when initialized with it.

My usual go-to is to have a static property that will return a new Dictionary with each get. E.g.

```<code>public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>()
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ...
         }
   }
}
</code>```

This works, and the lookup list will likely never be large enough for this to noticeably impact performance or memory usage, but being somewhat stingy on performance I don't like the idea of having a new Dictionary instantiated every time it is referenced. I would much rather it be completely hard-coded into memory.

How would this be solved in a professional way? I feel like the way I am doing it above is incredibly sloppy.

答:
You can use an auto-property initializer or set the value in the static constructor. The latter is shown below.

```<code>static MyClass()
{
   Defaults = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };
}

public static Dictionary<long, DefaultValue> Defaults {get; private set;}
</code>```

Example with Auto-property initializer (no static constructor is needed and the private set is omitted as the assumption can now be made you are using a c# version that supports that).

```<code>public static Dictionary<long, DefaultValue> Defaults {get;} = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };
</code>```

Side note: If the values should not be altered you could also expose the IReadonlyDictionary interface on the property.

Title: Construct a static lookup

Body:
Say I have a giant list of definitions that are used to lookup values that an object can default to given a "type number". This type number is unique, and points to data that the object will be set to when initialized with it.

My usual go-to is to have a static property that will return a new Dictionary with each get. E.g.

public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>()
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ...
         }
   }
}

This works, and the lookup list will likely never be large enough for this to noticeably impact performance or memory usage, but being somewhat stingy on performance I don't like the idea of having a new Dictionary instantiated every time it is referenced. I would much rather it be completely hard-coded into memory.

How would this be solved in a professional way? I feel like the way I am doing it above is incredibly sloppy.

Body:
You can use an auto-property initializer or set the value in the static constructor. The latter is shown below.

static MyClass()
{
   Defaults = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };
}

public static Dictionary<long, DefaultValue> Defaults {get; private set;}

Example with Auto-property initializer (no static constructor is needed and the private set is omitted as the assumption can now be made you are using a c# version that supports that).

public static Dictionary<long, DefaultValue> Defaults {get;} = new Dictionary<long, DefaultValue>(){
        { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
        { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
      };

Side note: If the values should not be altered you could also expose the IReadonlyDictionary interface on the property.


问:
How to list the file path while using grep?
So, I'm using

```<code>imhead ../rawdata/m13/m13_dark/*.fit | grep 'Dark Frame'
</code>```

imhead basically prints the header of the FITS files(FITS is one of the major image files used in astronomy). Think of it as exif for photography files. So, I'm running it through all the .fits files in the directory and I get the output

```<code>IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
</code>```

Which is expected because I know that there are only 5 files in this directory whose headers contain the string 'Dark Frame'

I want to print the file paths of these files in which grep finds the string 'dark frame'.

How do I go about it? Is there another command that I should be using along with grep for that.

grep -l or grep -H do not seem to work

Here is a typical output of the imhead command run on a single file
Imhead Output

答:
Edited to use imhead

Now that I understand what you are doing a bit more, the approach mentioned in the comment about using find and a short helper script (say chkDarkFrame.sh) should provide a solution. For example, you can pass each *.fit file found in your ../rawdata/m13/m13_dark/ directory to chkDarkFrame.sh using a call to find similar to:

```<code>find ../rawdata/m13/m13_dark/ -type f -name "*.fit" -exec ./chkDarkFrame.sh '{}' \;
</code>```

(note: you can limit whether find checks resursively with the -maxdepth option)

Your chkDarkFrame.sh helper script could call imhead on the filename and pipe the result to grep -q and if 'Dark Frame' is present in the imhead output, print the filename, e.g.

```<code>#!/bin/bash
imhead "$1" | grep -q 'Dark Frame' && printf "%s\n" "$1"
</code>```

Give that a try and let me know if that is closer. Sorry for the early confusion.

Body:
So, I'm using

imhead ../rawdata/m13/m13_dark/*.fit | grep 'Dark Frame'

imhead basically prints the header of the FITS files(FITS is one of the major image files used in astronomy). Think of it as exif for photography files. So, I'm running it through all the .fits files in the directory and I get the output

IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image
IMAGETYP= 'Dark Frame' /        Type of image

Which is expected because I know that there are only 5 files in this directory whose headers contain the string 'Dark Frame'

I want to print the file paths of these files in which grep finds the string 'dark frame'.

How do I go about it? Is there another command that I should be using along with grep for that.

grep -l or grep -H do not seem to work

Here is a typical output of the imhead command run on a single file
Imhead Output

Body:
Edited to use imhead

Now that I understand what you are doing a bit more, the approach mentioned in the comment about using find and a short helper script (say chkDarkFrame.sh) should provide a solution. For example, you can pass each *.fit file found in your ../rawdata/m13/m13_dark/ directory to chkDarkFrame.sh using a call to find similar to:

find ../rawdata/m13/m13_dark/ -type f -name "*.fit" -exec ./chkDarkFrame.sh '{}' \;

(note: you can limit whether find checks resursively with the -maxdepth option)

Your chkDarkFrame.sh helper script could call imhead on the filename and pipe the result to grep -q and if 'Dark Frame' is present in the imhead output, print the filename, e.g.

#!/bin/bash
imhead "$1" | grep -q 'Dark Frame' && printf "%s\n" "$1"

Give that a try and let me know if that is closer. Sorry for the early confusion.


问:
Hibernate Java Config Versus Xml
I am new to hibernate and I don't fully understand how to choose between java configuration and xml in hibernate config file? Tutorials that I have watched seem to be out of date. So my question is what is the best and most up to date way of configuring a model to hibernate.

The following is my current approach which seems to be the only one working for me:

```<code><hibernate-configuration>
<session-factory>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>

<!-- <property name="hibernate.generate_statistics">true</property> -->
</code>```

I am configuring my model in a java file as shown below:

```<code>public class HibernateUtil {

private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {

        // Create your SessionFactory with mappings for every Entity in a specific package
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addAnnotatedClass(PersonModel.class);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

        return sessionFactory;

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
</code>```

Is this the right way of doing it? or should it be done via XML file, if so can someone show me an example please?

Thanks in advance

答:
This way you can scan all entity classes at once</p>

```<code>SessionFactory sessionFactory = new LocalSessionFactoryBuilder(yourDataSource())
        .scanPackages("com.yourpackage.name")
        .addProperties(properties)
        .buildSessionFactory();
</code>```

Title: Hibernate Java Config Versus Xml

Body:
I am new to hibernate and I don't fully understand how to choose between java configuration and xml in hibernate config file? Tutorials that I have watched seem to be out of date. So my question is what is the best and most up to date way of configuring a model to hibernate.

The following is my current approach which seems to be the only one working for me:

<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>

I am configuring my model in a java file as shown below:

public class HibernateUtil {

private static SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {

        // Create your SessionFactory with mappings for every Entity in a specific package
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addAnnotatedClass(PersonModel.class);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        //SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

        return sessionFactory;

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

Is this the right way of doing it? or should it be done via XML file, if so can someone show me an example please?

Thanks in advance

Body:
This way you can scan all entity classes at once

SessionFactory sessionFactory = new LocalSessionFactoryBuilder(yourDataSource())
        .scanPackages("com.yourpackage.name")
        .addProperties(properties)
        .buildSessionFactory();


问:
How can I replace/speed up a text search query which uses LIKE?
I'm trying to speed up my query...

```<code>select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC
</code>```

I've done some work already, I have a keywords table so I can add

```<code>... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...
</code>```

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)

答:
Jules,

You need to provide output of explain on the query. Something like:

```<code>mysql> EXPLAIN select id from mytable WHERE (keywords like '%$search%' or ProgramName like '%$search%' or English45 like '%$search%') AND RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC
</code>```

And if possible table structure by doing a DESC on the table. This will help us to identify your index structure and if they are being used in the query.

Thanks.

Body:
I'm trying to speed up my query...

select PadID from Pads WHERE (keywords like '%$search%' or
ProgramName like '%$search%' or English45 like '%$search%') AND
RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC

I've done some work already, I have a keywords table so I can add

... PadID IN (SELECT PadID FROM Keywords WHERE word = '$search') ...

However its going to be a nightmare to split up the words from English45 and ProgramName into a word table.

Any ideas ?
EDIT : (also provided actual table names)

Body:
Jules,

You need to provide output of explain on the query. Something like:

mysql> EXPLAIN select id from mytable WHERE (keywords like '%$search%' or ProgramName like '%$search%' or English45 like '%$search%') AND RemovemeDate = '2001-01-01 00:00:00' ORDER BY VersionAddDate DESC

And if possible table structure by doing a DESC on the table. This will help us to identify your index structure and if they are being used in the query.

Thanks.


问:
Sending data to MVC Action via jQuery ajax, parameter is null
I've gone through several questions here related to this, and so far none of them have fixed my particular issue. I'm sending data related to the selected rows in a DataGrid to an action on the server using ajax. The JavaScript code looks like this:

```<code>function addSelected() {
        var grid = $("#optionsGrid").dxDataGrid("instance");
        var gridData = grid.getSelectedRowsData();

        $.ajax({
            type: "POST",
            url: "/api/Options/AddRange",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ data: gridData })
        });
    }
</code>```

And the action on the server (for now):

```<code>[HttpPost("api/[controller]/[action]")]
public async Task<IActionResult> AddRange(string data)
{

    return Ok();
}
</code>```

I've inspected it in a browser and the gridData value is definitely populated with the data I want before being sent to the server, and the action is hit, but the 'data' parameter is always null. I also tried putting the [FromBody] attribute on the parameter but it didn't change it. No matter what I name the data or whether or not I stringify it the parameter is null.

Changing the datatype to dynamic didn't help either, it was still null. The data needing to be sent is also included in the Request body upon inspection.

答:
Try this way</p>

```<code>function addSelected() {
    var grid = $("#optionsGrid").dxDataGrid("instance");
    var gridData = grid.getSelectedRowsData();

    $.ajax({
        type: "POST",
        url: "/api/Options/AddRange?data=" + JSON.stringify(gridData),
        contentType: "application/json; charset=utf-8"
    });
}
</code>```

Body:
I've gone through several questions here related to this, and so far none of them have fixed my particular issue. I'm sending data related to the selected rows in a DataGrid to an action on the server using ajax. The JavaScript code looks like this:

function addSelected() {
        var grid = $("#optionsGrid").dxDataGrid("instance");
        var gridData = grid.getSelectedRowsData();

        $.ajax({
            type: "POST",
            url: "/api/Options/AddRange",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ data: gridData })
        });
    }

And the action on the server (for now):

[HttpPost("api/[controller]/[action]")]
public async Task<IActionResult> AddRange(string data)
{

    return Ok();
}

I've inspected it in a browser and the gridData value is definitely populated with the data I want before being sent to the server, and the action is hit, but the 'data' parameter is always null. I also tried putting the [FromBody] attribute on the parameter but it didn't change it. No matter what I name the data or whether or not I stringify it the parameter is null.

Changing the datatype to dynamic didn't help either, it was still null. The data needing to be sent is also included in the Request body upon inspection.

Body:
Try this way

function addSelected() {
    var grid = $("#optionsGrid").dxDataGrid("instance");
    var gridData = grid.getSelectedRowsData();

    $.ajax({
        type: "POST",
        url: "/api/Options/AddRange?data=" + JSON.stringify(gridData),
        contentType: "application/json; charset=utf-8"
    });
}


问:
File extension naming: .p vs .pkl vs .pickle
When reading and writing pickle files, I've noticed that some snippets use .p others .pkl and some the full .pickle.  Is there one most pythonic way of doing this?

My current view is that there is no one right answer, and that any of these will suffice.  In fact, writing a filename of awesome.pkl or awesome.sauce won't make a difference when running pickle.load(open(filename, "rb")).  This is to say, the file extension is just a convention which doesn't actually affect the underlying data.  Is that right?

Bonus: What if I saved a PNG image as myimage.jpg?  What havoc would that create?

答:
The extension makes no difference because "The Pickle Protocol" runs every time.

That is to say whenever pickle.dumps or pickle.loads is run the objects are serialized/un-serialized according to the pickle protocol.

(The pickle protocol is a serialization format)

The pickle protocol is python specific(and there are several versions). It's only really designed for a user to re-use data themselves -> if you sent the pickled file to someone else who happened to have a different version of pickle/Python then the file might not load correctly and you probably can't do anything useful with that pickled file in another language like Java.

So, use what extensions you like because the pickler will ignore them.

JSON is another more popular way of serializing data, it can also be used by other languages unlike pickle - however it does not cater directly to python and so certain variable types are not understood by it :/

source if you want to read more

EDIT: while you could use any name, what should you use?

1 As mentioned by @Mike Williamson .pickle is used in the pickle docs

2 The python standard library json module loads files named with a .json extension. So it would follow the the pickle module would load a .pickle extension.

3 Using .pickle would also minimise any chance of accidental use by other programs.

.p extensions are used by some other programs, most notably MATLAB as the suffix for binary run-time files[sources: one, two]. Some risk of conflict

.pkl is used by some obscure windows "Migration Wizard Packing List file"[ source]. Incredibly low risk of conflict.

.pickle is only used for python pickling[source]. No risk of conflict.

ContentLicense: CC BY-SA 4.0


答:
The parameter name of data is in the stringify, you still need to specify that you are sending data as a parameter. Switch it like the below:

```<code>function addSelected() {
    var grid = $("#optionsGrid").dxDataGrid("instance");
    var gridData = grid.getSelectedRowsData();

    $.ajax({
        type: "POST",
        url: "/api/Options/AddRange",
        contentType: "application/json; charset=utf-8",
        data: { data: JSON.stringify(gridData) }
    });
}
</code>```

Title: Sending data to MVC Action via jQuery ajax, parameter is null

Body:
The parameter name of data is in the stringify, you still need to specify that you are sending data as a parameter. Switch it like the below:

function addSelected() {
    var grid = $("#optionsGrid").dxDataGrid("instance");
    var gridData = grid.getSelectedRowsData();

    $.ajax({
        type: "POST",
        url: "/api/Options/AddRange",
        contentType: "application/json; charset=utf-8",
        data: { data: JSON.stringify(gridData) }
    });
}


问:
Creating a short unique ID based on other values in Python?
I have a number of variables in python that I want to use to generate a unique ID for those variables (yet have that ID always produce for those same matching variables).

I have used .encode('hex','strict') to produce an ID which seems to work, however the output value is very long.  Is there a way to produce a shorter ID using variables?

```<code>myname = 'Midavalo'
mydate = '5 July 2017'
mytime = '8:19am'

codec = 'hex'

print "{}{}{}".format(myname, mydate, mytime).encode(codec,'strict')
</code>```

This outputs

```<code>4d69646176616c6f35204a756c792032303137383a3139616d
</code>```

I realise with hex it is probably dependant on the length of the three variables, so I'm wondering if there is another codec that can/will produce shorter values without excluding any of the variables?

So far I have tested base64, bz2, hex, quopri, uu, zip from 7.8.4. Python Specific Encodings, but I'm unsure how to get any of these to produce shorter values without removing variables.

Is there another codec I could use, or a way to shorten the values from any of them without removing the uniqueness, or even a completely different way to produce what I require?

All I am trying to do is produce an ID so I can identify those rows when loading them into a database.  If the same value already exists it will not create a new row in the database.  There is no security requirement, just a unique ID.  The values are generated elsewhere into python, so I can't just use a database issued ID for these values.

答:
You could use some hashing algorithm from the hashlib package: https://docs.python.org/3/library/hashlib.html or for python 2: https://docs.python.org/2.7/library/hashlib.html

```<code>import hashlib
s = "some string"
hash = hashlib.sha1(str.encode(s)).hexdigest() # you need to encode the strings into bytes here
</code>```

This hash would be the same for the same string.
Your choice of algorithm depends of the number of chars you want and the risk of collision(two different strings yielding the same hash).

Body:
I have a number of variables in python that I want to use to generate a unique ID for those variables (yet have that ID always produce for those same matching variables).

I have used .encode('hex','strict') to produce an ID which seems to work, however the output value is very long.  Is there a way to produce a shorter ID using variables?

myname = 'Midavalo'
mydate = '5 July 2017'
mytime = '8:19am'

codec = 'hex'

print "{}{}{}".format(myname, mydate, mytime).encode(codec,'strict')

This outputs

4d69646176616c6f35204a756c792032303137383a3139616d

I realise with hex it is probably dependant on the length of the three variables, so I'm wondering if there is another codec that can/will produce shorter values without excluding any of the variables?

So far I have tested base64, bz2, hex, quopri, uu, zip from 7.8.4. Python Specific Encodings, but I'm unsure how to get any of these to produce shorter values without removing variables.

Is there another codec I could use, or a way to shorten the values from any of them without removing the uniqueness, or even a completely different way to produce what I require?

All I am trying to do is produce an ID so I can identify those rows when loading them into a database.  If the same value already exists it will not create a new row in the database.  There is no security requirement, just a unique ID.  The values are generated elsewhere into python, so I can't just use a database issued ID for these values.

Body:
You could use some hashing algorithm from the hashlib package: https://docs.python.org/3/library/hashlib.html or for python 2: https://docs.python.org/2.7/library/hashlib.html

import hashlib
s = "some string"
hash = hashlib.sha1(str.encode(s)).hexdigest() # you need to encode the strings into bytes here

This hash would be the same for the same string.
Your choice of algorithm depends of the number of chars you want and the risk of collision(two different strings yielding the same hash).


问:
AVAssetExportSession not exporting time range
I have this problem. I'm trimming a sound file via AVAssetExportSession. I set the time range and then export asynchronously. I'm saving the output file under different name than the input file.

It works fine BUT only for the first time. When I try to trim the trimmed file, it exports it with whole duration, but CMTimeRangeShow shows right time range.

Anyone knows, what I'm doing wrong?

答:
Check the export session's state and error info within exportAsynchronouslyWithCompletionHandler, make sure the output URL file not exists.

Refer to these two threads, good luck!

Unable to trim a video using AVAssetExportSession

Creating a time range for AVAssetExportSession


问:
Charjs 2 with reactjs
I am totally new to reactjs library. I found this library very interesting and want to implement in my chart-analyzing project(which is Java based spring project). Basically I want to implement it conventional way, do not want to install npm or any package manager. I have two files:

File: index.html

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.31.0/react-bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-chartjs-2/2.1.0/react-chartjs-2.min.js"></script>
    <script type="text/babel" src="chart.js"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>
</code>```

File: chart.js

```<code>var MyComponent = React.createClass({
    render: function(){
      return <Line data={chartData} optionis={chartOptions} width="90%" height="70%" />
    }
});
ReactDOM.render(<MyComponent />, document.getElementById("root"));
</code>```

I think, it should work, but I get error:
Uncaught ReferenceError: Line is not defined

Note: I do NOT want to use npm manager. So, answers with npm, or using javascript require or import are not applicable to my requirement.

答:
Try this react library
 https://github.com/reactjs/react-chartjs .

 You just have to run
npm install --save react-chartjs in you project .

Then simply import LineChart from eact-chartjs

```<code> var LineChart = require("react-chartjs").Line;
    var MyComponent = React.createClass({
        render: function() {
      return <LineChart data={chartData} optionis={chartOptions} width="90%" height="70%" />
        }
    });
    ReactDOM.render(<MyComponent />, document.getElementById("root"));
</code>```

Title: Charjs 2 with reactjs

Body:
I am totally new to reactjs library. I found this library very interesting and want to implement in my chart-analyzing project(which is Java based spring project). Basically I want to implement it conventional way, do not want to install npm or any package manager. I have two files:

File: index.html

    <!DOCTYPE html>

File: chart.js

var MyComponent = React.createClass({
    render: function(){
      return <Line data={chartData} optionis={chartOptions} width="90%" height="70%" />
    }
});
ReactDOM.render(<MyComponent />, document.getElementById("root"));

I think, it should work, but I get error:
Uncaught ReferenceError: Line is not defined

Note: I do NOT want to use npm manager. So, answers with npm, or using javascript require or import are not applicable to my requirement.

Body:
Try this react library
 https://github.com/reactjs/react-chartjs .

 You just have to run
npm install --save react-chartjs in you project .

Then simply import LineChart from eact-chartjs

 var LineChart = require("react-chartjs").Line;
    var MyComponent = React.createClass({
        render: function() {
      return <LineChart data={chartData} optionis={chartOptions} width="90%" height="70%" />
        }
    });
    ReactDOM.render(<MyComponent />, document.getElementById("root"));


问:
C# : How to get running combination from two List<String> based on a master list
Dear all , this is something like my previous  question How to get moving combination from two List<String> in C#?

I'm having a masterlist and two childlist like below

```<code>        List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
        List<String> ListOne = new List<string> { "A", "B", "C" };
        List<String> ListTwo = new List<String> { "B", "D" };
</code>```

I just need to get the running combination from the above list for that i'm using like(previous question's answer(Thanks Danny Chen))

```<code>        List<String> Result = new List<string>();
        Result = ListOne.SelectMany((a, indexA) => ListTwo
                                    .Where((b, indexB) => ListTwo
                                    .Contains(a) ? !b.Equals(a) && indexB > indexA :
                                    !b.Equals(a)).Select(b => string.Format("{0}-{1}", a, b))).ToList();
</code>```

so the Result list will contain

```<code>        "A-B"
        "A-D"
        "B-D"
        "C-B"
        "C-D"
</code>```

Now my problem is the sorting issue

In the above result the fourth entry is C-B but it should be B-C. Because in the MasterList the C is after B.

How to do this in my existing linq .

Please help me to do this.

答:
Not really clear on the exact requirement here, so does the MasterList dictate which of the two items should appear first? What about the order of the X1-X2 list? i.e. should B-C appear before B-D because C appears before D in the MasterList?

Anyway, here's something that produces the result you've asked for so far:

```<code>List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
List<String> ListOne = new List<string> { "A", "B", "C" };
List<String> ListTwo = new List<String> { "B", "D" };

ListOne.SelectMany(i =>
ListTwo.Where(i2 => i != i2)
       .Select(i2 =>
            {
                if (MasterList.IndexOf(i) < MasterList.IndexOf(i2))
                    return string.Format("{0}-{1}", i, i2);
                else
                    return string.Format("{0}-{1}", i2, i);
            }
       ));
</code>```

outputs:

```<code>A-B
A-D
B-D
B-C
C-D
</code>```

Body:
Dear all , this is something like my previous  question How to get moving combination from two List<String> in C#?

I'm having a masterlist and two childlist like below

        List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
        List<String> ListOne = new List<string> { "A", "B", "C" };
        List<String> ListTwo = new List<String> { "B", "D" };

I just need to get the running combination from the above list for that i'm using like(previous question's answer(Thanks Danny Chen))

        List<String> Result = new List<string>();
        Result = ListOne.SelectMany((a, indexA) => ListTwo
                                    .Where((b, indexB) => ListTwo
                                    .Contains(a) ? !b.Equals(a) && indexB > indexA :
                                    !b.Equals(a)).Select(b => string.Format("{0}-{1}", a, b))).ToList();

so the Result list will contain

        "A-B"
        "A-D"
        "B-D"
        "C-B"
        "C-D"

Now my problem is the sorting issue

In the above result the fourth entry is C-B but it should be B-C. Because in the MasterList the C is after B.

How to do this in my existing linq .

Please help me to do this.

Body:
Not really clear on the exact requirement here, so does the MasterList dictate which of the two items should appear first? What about the order of the X1-X2 list? i.e. should B-C appear before B-D because C appears before D in the MasterList?

Anyway, here's something that produces the result you've asked for so far:

List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
List<String> ListOne = new List<string> { "A", "B", "C" };
List<String> ListTwo = new List<String> { "B", "D" };

ListOne.SelectMany(i =>
ListTwo.Where(i2 => i != i2)
       .Select(i2 =>
            {
                if (MasterList.IndexOf(i) < MasterList.IndexOf(i2))
                    return string.Format("{0}-{1}", i, i2);
                else
                    return string.Format("{0}-{1}", i2, i);
            }
       ));

outputs:

A-B
A-D
B-D
B-C
C-D


问:
Linq OrderBy last n values
Lets say i have array of ints:

```<code>int[] values = new int[]{1,2,7,9,8,0};
</code>```

How to OrderBy last 2 values?

```<code>int[] values = new int[]{1,2,7,9,0,8};
</code>```

答:
Try this

```<code>int[] values = new int[]{1,2,7,9,8,0};
var temp = values. Length > 1 ? new int[2] { values[length -2],values[values. Length-1] } : new inte[];

Var templist = values.tolist();
IF (values.length >1)
{
templist.removeat(values. Length-1)
templist.removeat(values.length-1)
}
templist.addrange(temp.tolist().orderby(x=> x))
Values= templist. Toarray()
</code>```

Im writing from my mobile sorry for the unformated text

Title: Linq OrderBy last n values

Body:
Lets say i have array of ints:

int[] values = new int[]{1,2,7,9,8,0};

How to OrderBy last 2 values?

int[] values = new int[]{1,2,7,9,0,8};

Body:
Try this

int[] values = new int[]{1,2,7,9,8,0};
var temp = values. Length > 1 ? new int[2] { values[length -2],values[values. Length-1] } : new inte[];

Var templist = values.tolist();
IF (values.length >1)
{
templist.removeat(values. Length-1)
templist.removeat(values.length-1)
}
templist.addrange(temp.tolist().orderby(x=> x))
Values= templist. Toarray()

Im writing from my mobile sorry for the unformated text


问:
Failed to query database

<?php
 //Get Value
 $username = $_POST['user'];
 $password = $_POST['pass'];

 //Connet To The Server And Select Database
 mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
 mysqli_select_db("xxxxx");

 //Query The Database For User
 $result = mysqli_query("select * from user where username = '$username' and password = '$password'")
  or die("Failed to query database ".mysqli_connect_error());
 $row = mysqli_fetch_array($result);
 if (empty($username)) {
  header('Location: fa.html');
 } elseif (empty($password)) {
  header('Location: fa.html');
 } elseif ($row['username'] == $username && $row['password'] == $password){
  header('Location: su.html');
 } else{
  header('Location: fa.html');
 }
?>```

I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".

答:
You need to trap for more errors to see where it's failing.  Right now all you know is that it's failing at-least by the mysqli_query() line where you do trap for errors.

First you have to ensure that you can actually connect to the database server.
Change:

```<code>mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
</code>```

to

```<code>if(!mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxx"))
{
    die("Could not connect");
}
</code>```

then you should also trap for errors on selecting the database. Change:

```<code>mysqli_select_db("xxxxx");
</code>```

to

```<code>if(!mysqli_select_db("xxxx"))
{
    die("Could not select database");
}
</code>```

Edit: Also you really didn't need to blank-out your IP.  192.168.1.* is a class C private address - meaning it is not accessible from outside your local network.

Title: Failed to query database

Body:
<?php
 //Get Value
 $username = $_POST['user'];
 $password = $_POST['pass'];

 //Connet To The Server And Select Database
 mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
 mysqli_select_db("xxxxx");

 //Query The Database For User
 $result = mysqli_query("select * from user where username = '$username' and password = '$password'")
  or die("Failed to query database ".mysqli_connect_error());
 $row = mysqli_fetch_array($result);
 if (empty($username)) {
  header('Location: fa.html');
 } elseif (empty($password)) {
  header('Location: fa.html');
 } elseif ($row['username'] == $username && $row['password'] == $password){
  header('Location: su.html');
 } else{
  header('Location: fa.html');
 }
?>

I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".

Body:
You need to trap for more errors to see where it's failing.  Right now all you know is that it's failing at-least by the mysqli_query() line where you do trap for errors.

First you have to ensure that you can actually connect to the database server.
Change:

mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");

to

if(!mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxx"))
{
    die("Could not connect");
}

then you should also trap for errors on selecting the database. Change:

mysqli_select_db("xxxxx");

to

if(!mysqli_select_db("xxxx"))
{
    die("Could not select database");
}

Edit: Also you really didn't need to blank-out your IP.  192.168.1.* is a class C private address - meaning it is not accessible from outside your local network.


答: You need to learn more, because these are really just the basics. The reason why your code works locally and doesn't on the remote server is probably caused by your DB access - it obviously isn't the same. You need to change your credentials and your db IP to match your remote server if you want to deploy your code there.</p>

Title: Failed to query database