问:
What happens to a running method if its object is deleted?
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

```<code>// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}
</code>```

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)

答:
Lets take this function step by step:

```<code>void MyClass::doSomething() {
    this->counterFromObject++;
</code>```

This is perfectly legal. But you knew that.

```<code>    delete object;
</code>```

Again, perfectly legal. However, after that, it is your job to ensure that no code tries to access the object behind the object pointer anymore. The problem is, that the this pointer of the currently running method contains a copy of the dead objects address; the this pointer is left dangling. Thus, dereferencing this in any way, explicitly or implicitly, will immediately yield undefined behavior.

```<code>    MyClass* object = new MyClass();    //I added the missing * to the type, we are not using java here.
</code>```

This does not dereference this, so it's perfectly ok. Note that this does not have any effect on the currently running method. The this pointer is dangling, and there's no way of reassigning it.

```<code>    this->counterFromClass++;
</code>```

Formally, this is undefined behavior, as you are dereferencing this. However, since counterFromClass is static, it is likely that this won't crash your process, as the compiled code won't actually access the memory behind this. Nevertheless, writing this-> means you have undefined behavior, so your process may crash anyway, or your compiler may simply throw this statement away! Whether it does so depends only on whether the compiler is smart enough to prove that you have undefined behavior here.

(As MartinBonner has found, the standard says in section 9.4 that the object expression is evaluated even when a static member is accessed via this->, which means that the dangling this pointer is actually dereferenced according to the standard. And dereferencing a dangling pointer is undefined behavior.)

So, it is mostly ok to delete an object while a method is running on it, and there are uses for this (one example is a reference counted object committing suicide when it's reference count drops to zero). However, if you ever need to do this,

write a warning comment that you may be deleting the this object, and

make sure to return immediately afterwards.

Body:
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)

Body:
Lets take this function step by step:

void MyClass::doSomething() {
    this->counterFromObject++;

This is perfectly legal. But you knew that.

    delete object;

Again, perfectly legal. However, after that, it is your job to ensure that no code tries to access the object behind the object pointer anymore. The problem is, that the this pointer of the currently running method contains a copy of the dead objects address; the this pointer is left dangling. Thus, dereferencing this in any way, explicitly or implicitly, will immediately yield undefined behavior.

    MyClass* object = new MyClass();    //I added the missing * to the type, we are not using java here.

This does not dereference this, so it's perfectly ok. Note that this does not have any effect on the currently running method. The this pointer is dangling, and there's no way of reassigning it.

    this->counterFromClass++;

Formally, this is undefined behavior, as you are dereferencing this. However, since counterFromClass is static, it is likely that this won't crash your process, as the compiled code won't actually access the memory behind this. Nevertheless, writing this-> means you have undefined behavior, so your process may crash anyway, or your compiler may simply throw this statement away! Whether it does so depends only on whether the compiler is smart enough to prove that you have undefined behavior here.

(As MartinBonner has found, the standard says in section 9.4 that the object expression is evaluated even when a static member is accessed via this->, which means that the dangling this pointer is actually dereferenced according to the standard. And dereferencing a dangling pointer is undefined behavior.)

So, it is mostly ok to delete an object while a method is running on it, and there are uses for this (one example is a reference counted object committing suicide when it's reference count drops to zero). However, if you ever need to do this,

write a warning comment that you may be deleting the this object, and

make sure to return immediately afterwards.


来源: stackexchange

问:
Is it possible to make child exceed parent' overflow restriction?
I am curious to figure out if it's possible to make child div exceed parent div' overflow restriction.

```<code><div id="parent" style="overflow: hidden;">
    <div id="child1"></div>
    <div id="child2"></div>
</div>
</code>```

In this case, can i make specifically child1 exceed parent' overflow: hidden, and at the same time keep the overflow restriction for child2? I want to know this, because I'm trying to make a "zoom" effect using transform: scale().

This is a jsfiddle for a bit more advanced example: https://jsfiddle.net/f10vovcg/

I am very curious. Any help is very much appreciated :3 Thanks on advance.

答:
If you set the position: absolute to the element, in your case #child1, it will appear even outside parent container because it will be taken out of the flow.
I hope this answers your question.

ContentLicense: CC BY-SA 3.0

Body:
I am curious to figure out if it's possible to make child div exceed parent div' overflow restriction.

In this case, can i make specifically child1 exceed parent' overflow: hidden, and at the same time keep the overflow restriction for child2? I want to know this, because I'm trying to make a "zoom" effect using transform: scale().

This is a jsfiddle for a bit more advanced example: https://jsfiddle.net/f10vovcg/

I am very curious. Any help is very much appreciated :3 Thanks on advance.


问:
Android studio 3 Unable to resolve dependency
I update android studio to version 3.0.0 and installed gradle 4.
i create new project but Unable to resolve dependency.

i test this method but not working:
 - invalidate and restart
 - delete .gradle folder and build
 - clean and rebuild
 - deactive offline mode

how to fix?

details screenshots:

答:
fixed this problem after a lot of search. in gradle.propertices file set proxy both http and https and sync again.</p>

```<code>systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyPort=12345
org.gradle.jvmargs=-Xmx1234m
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=12345
</code>```

Body:
fixed this problem after a lot of search. in gradle.propertices file set proxy both http and https and sync again.

systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyPort=12345
org.gradle.jvmargs=-Xmx1234m
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=12345


问:
Custom column to represent order
I am using MySQL to return columns from a data table. What I want to do is use Order By to order the results by a date fields in ascending order and then also return a custom column along with the other desired columns where the custom column represents the index in relation to the Order By results. Right, I have the following query which just returns the desired columns and orders the results:

```<code>SELECT
    `alert_id`,
    `message`,
    `expiration`
FROM
    `alert`
WHERE
    `is_active` = TRUE
ORDER BY
    `expiration`
</code>```

But what I'm having difficulty with is how to also return the custom column that represents the order. So for example, I would like the following (sample data) rows returned:

```<code>  Pior to Order and Custom Column           After the Order and Custom Column
+----------+---------+------------+  +----------+---------+------------+----------+
| alert_id | message | expiration |  | alert_id | message | expiration | order_by |
+----------+---------+------------+  +----------+---------+------------+----------+
|    1     |  alert1 | 2017-11-20 |  |    5     |  alert5 | 2017-11-16 |     1    |
|    5     |  alert5 | 2017-11-16 |  |    6     |  alert6 | 2017-11-17 |     2    |
|    6     |  alert6 | 2017-11-17 |  |    1     |  alert1 | 2017-11-20 |     3    |
+----------+---------+------------+  +----------+---------+------------+----------+
</code>```

答:
With AdrianE's assistance in mentioning the ROW_NUMBER function, even though I am using MySQL and that function is not available, I was able to emulate the function by using the following:</p>

```<code>SET @order = 0;
SELECT
    `alert_id`,
    `message`,
    DATE_FORMAT(`expiration`, '%M %D, %Y') AS formatted_date,
    (@order := @order + 1) AS order_by
FROM
    `alert`
WHERE
    `is_active` = TRUE
ORDER BY
    `expiration`;
</code>```

Title: Custom column to represent order

Body:
I am using MySQL to return columns from a data table. What I want to do is use Order By to order the results by a date fields in ascending order and then also return a custom column along with the other desired columns where the custom column represents the index in relation to the Order By results. Right, I have the following query which just returns the desired columns and orders the results:

SELECT
    `alert_id`,
    `message`,
    `expiration`
FROM
    `alert`
WHERE
    `is_active` = TRUE
ORDER BY
    `expiration`

But what I'm having difficulty with is how to also return the custom column that represents the order. So for example, I would like the following (sample data) rows returned:

  Pior to Order and Custom Column           After the Order and Custom Column
+----------+---------+------------+  +----------+---------+------------+----------+
| alert_id | message | expiration |  | alert_id | message | expiration | order_by |
+----------+---------+------------+  +----------+---------+------------+----------+
|    1     |  alert1 | 2017-11-20 |  |    5     |  alert5 | 2017-11-16 |     1    |
|    5     |  alert5 | 2017-11-16 |  |    6     |  alert6 | 2017-11-17 |     2    |
|    6     |  alert6 | 2017-11-17 |  |    1     |  alert1 | 2017-11-20 |     3    |
+----------+---------+------------+  +----------+---------+------------+----------+

Body:
With AdrianE's assistance in mentioning the ROW_NUMBER function, even though I am using MySQL and that function is not available, I was able to emulate the function by using the following:

SET @order = 0;
SELECT
    `alert_id`,
    `message`,
    DATE_FORMAT(`expiration`, '%M %D, %Y') AS formatted_date,
    (@order := @order + 1) AS order_by
FROM
    `alert`
WHERE
    `is_active` = TRUE
ORDER BY
    `expiration`;


问:
Rails3-amf and bringing an association to amf
i am changing from WebORB to Warhammerkids Rails3-amf - great choice, even tehre are some open issues. One those issues is, how can I get records from an association to the array, which is sent back to the Flex-Application.
In WebORB the method of the controller looks like:

```<code> def getClients(clientFilter,myMandant)
     clients = Client.find(:all, :conditions => {:account_id => myMandant}, :include => [:addresses, :contacts, :proofs])
  end
</code>```

in Rails3-amf I have a similar construction:

```<code>def getClients()
     @clients = Client.find(:all, :conditions => {:account_id => params[1]}, :include => [:addresses, :contacts, :proofs])
    respond_with(@clients) do |format|
       format.amf { render :amf => @clients}
  end
</code>```

With this code I get back all correctly typed Client Objects as an Array, but without the records from the ":include" argument.
How can I handle this ??

I also tried another way with:

```<code>....
respond_with(@clients) do |format|
       format.amf { render :amf => @clients.to_amf(:include => [:addresses, :contacts, :proofs])}
....
</code>```

With this try I got an error message" undefined method to_amf for #.

Thanks for any help.

答:
I don't know about rail3-amf, but you might find it worthwhile having a look at restfulx - https://github.com/dima/restfulx/tree/rails3

It consists of a library for rails, and a library for flex. It supports data transfer through json, xml, or amf.

The actionscript api for working with models is very nice too:

```<code>var user:User = new User();
user.first_name = "Ed";
user.create();
</code>```

It can also keep track of rails associations etc.:

```<code>trace(user.account.title);
</code>```

See more usage here - https://github.com/dima/restfulx_framework/wiki/Working-with-RestfulX-Models

ContentLicense: CC BY-SA 2.5

Body:
i am changing from WebORB to Warhammerkids Rails3-amf - great choice, even tehre are some open issues. One those issues is, how can I get records from an association to the array, which is sent back to the Flex-Application.
In WebORB the method of the controller looks like:

 def getClients(clientFilter,myMandant)
     clients = Client.find(:all, :conditions => {:account_id => myMandant}, :include => [:addresses, :contacts, :proofs])
  end

in Rails3-amf I have a similar construction:

def getClients()
     @clients = Client.find(:all, :conditions => {:account_id => params[1]}, :include => [:addresses, :contacts, :proofs])
    respond_with(@clients) do |format|
       format.amf { render :amf => @clients}
  end

With this code I get back all correctly typed Client Objects as an Array, but without the records from the ":include" argument.
How can I handle this ??

I also tried another way with:

....
respond_with(@clients) do |format|
       format.amf { render :amf => @clients.to_amf(:include => [:addresses, :contacts, :proofs])}
....

With this try I got an error message" undefined method to_amf for #.

Thanks for any help.

Body:
I don't know about rail3-amf, but you might find it worthwhile having a look at restfulx - https://github.com/dima/restfulx/tree/rails3

It consists of a library for rails, and a library for flex. It supports data transfer through json, xml, or amf.

The actionscript api for working with models is very nice too:

var user:User = new User();
user.first_name = "Ed";
user.create();

It can also keep track of rails associations etc.:

trace(user.account.title);

See more usage here - https://github.com/dima/restfulx_framework/wiki/Working-with-RestfulX-Models


问:
Why Github Dependency Graph has some packages that don't get rendered as links
In a github repository I own most of the dependencies are rendered as links - but some of them, including one of my own Github repository dependencies (aor-component-factory), don't.

Is it because they are not that popular and they weren't indexed yet or there is some configuration/code that needs to be added to those repositories? Thanks!

答:
One possible reason is for repo renamed (the OP confirms it wasn't).

Another reason is the path used to reference dependencies in the package.json

```<code> zifnab87/ra-component-factory
 vs.
 ra-component-factory
</code>```

The former should work better.

Following this tweet, try and apply to your repo the jgamblin/GithubDependencyCheck tools to see if that particular dependency in gray is reported any differently.

From the OP Michail Michailidis's comment, it seems that was a GitHub bug that was since fixed (Dec. 2017).

Body:
One possible reason is for repo renamed (the OP confirms it wasn't).

Another reason is the path used to reference dependencies in the package.json

 zifnab87/ra-component-factory
 vs.
 ra-component-factory

The former should work better.

Following this tweet, try and apply to your repo the jgamblin/GithubDependencyCheck tools to see if that particular dependency in gray is reported any differently.

From the OP Michail Michailidis's comment, it seems that was a GitHub bug that was since fixed (Dec. 2017).


问:
Unit test in Unity - Getting an InvalidCastException - Why? And how to fix?
I try to be as specific and helpful as possible in my questions here on S.O. but for this one, well, that means almost nothing, as I have absolutely no hint of the faintest clue about why this is happening.

It happens on any/every test (even "blank" ones). And I already tried (uninstalling and) updating unity. - Didn't work.

Anyways, here is the stacktrace of the exception:

```<code>2017.11.16 14:54:24.308   ERROR System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada.
System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada. ---> System.InvalidCastException: Não é possível converter um objeto do tipo 'NUnit.Engine.CallbackHandler' no tipo 'System.Web.UI.ICallbackEventHandler'.
   em NUnit.Framework.Api.FrameworkController.LoadTestsAction..ctor(FrameworkController controller, Object handler)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.RuntimeMethodHandle._InvokeConstructor(Object[] args, SignatureStruct& signature, IntPtr declaringType)
   em System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   em System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
   em System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
   em NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.Load()
   em NUnit.Engine.Runners.MasterTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.EnsurePackageIsLoaded()
   em NUnit.Engine.Runners.MasterTestRunner.NUnit.Engine.ITestRunner.Explore(TestFilter filter)
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.<>c__DisplayClass1.<RunTests>b__0()
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.WithExtensiveErrorHandling(IRemoteTaskServer server, Action action)
</code>```

This is making me pretty much code without (unit-)testing for the last couple of days, so if anyone has any idea about the cause and/or solutions, that would be greatly appreciated.

答:
Resharper is using the NUnit Engine to run tests But the engine only supports tests written against .NET 2.0 through 4.5. The framework you are using is one of the .NET Standard builds. I can tell this by looking at the stack trace and seeing that it doesn't have a reference to System.Web.UI.ICallbackEventHandler.

You should be able to run your tests in Test Explorer using the latest installation of the NUnit 3 VS Test Adapter.

Updating for clarity...

There's no doubt that are using a version of the nunit framework that is not supported by the platform. That's the key here.

Some builds of the framework use System.Web.UI.ICallbackEventHandler(.NET 2.0, 3.5, 4.0 and 4.5) while others (.NET Standard 1.3 and 1.6) do not. Since NUnit is looking for that interface, you are referencing one of the builds that uses it. Since it's not available, you are on a platform that doesn't include it.

A simple workaround would be for you to define the interface yourself, duplicating it exactly as defined by Microsoft. You don't have to implement it, since the framework you are using does that. Of course, that could lead to other failures due to framework / platform incompatibility so it's probably better to resolve the compatibility issue in the first place.

Unfortunately, I can't be of any help on the Unity side of the problem.

Body:
I try to be as specific and helpful as possible in my questions here on S.O. but for this one, well, that means almost nothing, as I have absolutely no hint of the faintest clue about why this is happening.

It happens on any/every test (even "blank" ones). And I already tried (uninstalling and) updating unity. - Didn't work.

Anyways, here is the stacktrace of the exception:

2017.11.16 14:54:24.308   ERROR System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada.
System.Reflection.TargetInvocationException: Uma exceção foi acionada pelo destino de uma chamada. ---> System.InvalidCastException: Não é possível converter um objeto do tipo 'NUnit.Engine.CallbackHandler' no tipo 'System.Web.UI.ICallbackEventHandler'.
   em NUnit.Framework.Api.FrameworkController.LoadTestsAction..ctor(FrameworkController controller, Object handler)
   --- Fim do rastreamento de pilha de exceções internas ---
   em System.RuntimeMethodHandle._InvokeConstructor(Object[] args, SignatureStruct& signature, IntPtr declaringType)
   em System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   em System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
   em System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
   em System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   em NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
   em NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.Load()
   em NUnit.Engine.Runners.MasterTestRunner.LoadPackage()
   em NUnit.Engine.Runners.AbstractTestRunner.EnsurePackageIsLoaded()
   em NUnit.Engine.Runners.MasterTestRunner.NUnit.Engine.ITestRunner.Explore(TestFilter filter)
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.<>c__DisplayClass1.<RunTests>b__0()
   em JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.WithExtensiveErrorHandling(IRemoteTaskServer server, Action action)

This is making me pretty much code without (unit-)testing for the last couple of days, so if anyone has any idea about the cause and/or solutions, that would be greatly appreciated.


问:
When to use a react framework such as Next or Gatsby vs Create React App
I'm in the sort of rapid prototyping phase of my React/javascript learning experience. I was wondering when folks would reach for a framework such as Next.js or Gatsby.js vs the standard Create React App.

I really dig the page based structuring and prospect for preloading links of Next.js. However, I'm not sure when you would reach for Next as apposed to CRA or even ejected CRA.

Thanks!

答: I'm doing this research myself. My understanding is that Next.js provides Server-Side Rendering out of the box. Create React App does not do this so you need to provide your own solution for SSR (for things like faster page loads and SEO).</p>


问:
Rails 3 ActiveRecord: Order by count on association
I have a model named Song. I also have a model named Listen. A Listen belongs_to :song, and a song :has_many listens (can be listen to many times).

In my model I want to define a method self.top which should return the top 5 songs listened to the most. How can I achieve that using the has_many relation?

I'm using Rails 3.1.

Thanks!

答:
For rails 4.x try this if your rows without any association matters: </p>

```<code>scope :order_by_my_association, lambda {
    select('comments.*, COUNT(listens.id) AS listens_total')
    .joins("LEFT OUTER JOIN listens ON listens.comment_id = comments.id")
    .group('comments.id')
    .order("listens_total DESC")
  }
</code>```

Body:
For rails 4.x try this if your rows without any association matters:

scope :order_by_my_association, lambda {
    select('comments.*, COUNT(listens.id) AS listens_total')
    .joins("LEFT OUTER JOIN listens ON listens.comment_id = comments.id")
    .group('comments.id')
    .order("listens_total DESC")
  }


问:
display message in button click during postback
Hai frnds , i want to show the message on button click....please help advance thanks</p>

答:
You mean like the javascript client-side handler?</p>

```<code>onclick="alert('Hi there!')"
</code>```

Body:
You mean like the javascript client-side handler?

onclick="alert('Hi there!')"


问:
what's the simplest benchmark for recurrent neural networks?
i am exploring new architectures for LSTMs. i have looked into a few commonly used datasets, such as IMDB's movie reviews and sine waves, but haven't found a good generalizable dataset. if MNIST is the "hello world" for convolutional networks, then what would be the equivalent dataset for LSTMs? </p>

答:
You can check examples in which people use simpler models, like HMM and try running LSTM on them.

For example you can try running this POS tagging code (the pos_* part) from lazyprogrammer's course (here is a script that downloads and handles the data). This code contains models that use LSTMs on Tensorflow/Theano and also HMMs (and even logistic regression that does not take into account the sequential nature of the data).


问:
How can I access a selected option's displayed value from a directive on the select element
My markup looks something like this

```<code><select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
    <option value="" selected>All</option>
</select>
</code>```

From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (i.e. lookup.lookupValue). I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up). I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.

答:
Found my answer. It turns out directives can access the dom directly.

```<code>link: function (scope, element, attrs, controller) {
    scope.getViewValue = function () {
                    if (angular.isDefined(scope.overrideTagDisplay)) {
                        return scope.overrideTagDisplay;
                    }
                    else if (element[0].nodeName == "SELECT") {
                        return element.children()[element[0].selectedIndex].text;
                    }
                    else {
                        return ngModel.$viewValue;
                    }
    }

    scope.initialize()
}
</code>```

EDIT: I found later that this method has the issue that if javascript modifies the model value somewhere else in the code and then this piece immediately runs, it does not pick up the new value because the DOM hasn't updated (this includes on page load and initial setting). I ended up passing the list of lookups into the directive as well and got around the lack of standardization in those lookups by having an optional "comparator key" that would defaultly look something like

```<code>var comparitorKey = { id: "id", lookupValue: "lookupValue"};
</code>```

which is then utilized like this

```<code>var id = ngModel.$modelValue;

var filtered = scope.lookupList.filter(function (lookup) { return lookup[scope.comparitorKey.id] == id });
return filtered.length > 0 ? filtered[0][scope.comparitorKey.lookupValue] : null;
</code>```

the idea being that someone could pass in an alternative like

```<code>var comparitorKey = {id: "userId", lookupValue: "userName" };
</code>```

Body:
My markup looks something like this

<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
    <option value="" selected>All</option>
</select>

From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (i.e. lookup.lookupValue). I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up). I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.

Body:
Found my answer. It turns out directives can access the dom directly.

link: function (scope, element, attrs, controller) {
    scope.getViewValue = function () {
                    if (angular.isDefined(scope.overrideTagDisplay)) {
                        return scope.overrideTagDisplay;
                    }
                    else if (element[0].nodeName == "SELECT") {
                        return element.children()[element[0].selectedIndex].text;
                    }
                    else {
                        return ngModel.$viewValue;
                    }
    }

    scope.initialize()
}

EDIT: I found later that this method has the issue that if javascript modifies the model value somewhere else in the code and then this piece immediately runs, it does not pick up the new value because the DOM hasn't updated (this includes on page load and initial setting). I ended up passing the list of lookups into the directive as well and got around the lack of standardization in those lookups by having an optional "comparator key" that would defaultly look something like

var comparitorKey = { id: "id", lookupValue: "lookupValue"};

which is then utilized like this

var id = ngModel.$modelValue;

var filtered = scope.lookupList.filter(function (lookup) { return lookup[scope.comparitorKey.id] == id });
return filtered.length > 0 ? filtered[0][scope.comparitorKey.lookupValue] : null;

the idea being that someone could pass in an alternative like

var comparitorKey = {id: "userId", lookupValue: "userName" };


问:
VueJs directive two way binding
I created a custom directive to handle select2 in VueJs. The code below works when I am binding a select to a data property in my viewmodel that is not a propert of an object within data.

Like this.userId but if it is bound to something like this.user.id, it would not update the value in my viewmodel data object.

```<code>Vue.directive('selected', {
    bind: function (el, binding, vnode) {
        var key = binding.expression;
        var select = $(el);

        select.select2();
        vnode.context.$data[binding.expression] = select.val();

        select.on('change', function () {
            vnode.context.$data[binding.expression] = select.val();
        });
    },
    update: function (el, binding, newVnode, oldVnode) {
        var select = $(el);
        select.val(binding.value).trigger('change');
    }
});

<select v-selected="userEditor.Id">
   <option v-for="user in users" v-bind:value="user.id" >
       {{ user.fullName}}
   </option>
</select>
</code>```

Related fiddle:
https://jsfiddle.net/raime910/rHm4e/4/

答:
A custom directive is perfectly fine, except use the insertedhook instead of bind.  Adapted from Vue Wrapper Component Example.

To bind to an object property, the simplest way is to wrap it in a computed setter Computed Setter and bind to that.

Note, 'deep setting' does not appear to work. The problem is one of change detection, which the computed setter overcomes. (Note that the on('change' function is jQuery not Vue.)

console.clear()

Vue.directive('selected', {
  inserted: function (el, binding, vnode) {
    var select = $(el);
    select
      .select2()
      .val(binding.value)
      .trigger('change')
      .on('change', function () {
        if (vnode.context[binding.expression]) {
          vnode.context[binding.expression] = select.val();
        }
      })
    },
});

var vm = new Vue({
  el: '#my-app',
  computed: {
    selectedValue: {
      get: function() { return this.myObj.type },
      set: function (value) { this.myObj.type = value }
    }
  },
  data: {
    selectedVal: 0,
    myObj: { type: 3 },
    opts: [{
      id: 1,
      text: 'Test 1'
    }, {
      id: 2,
      text: 'Test 2'
    }, {
      id: 3,
      text: 'Test 3'
    }]
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.js"></script>

<div id="my-app">
  <div>
    <label for="example">Test dropdown list ({{ myObj.type }})</label>
  </div>
  <div>
    <select id="example" style="width: 300px" v-selected="selectedValue">
      <option v-for="(opt,index) in opts" :value="opt.id" :key="index">
        {{ opt.text }}
      </option>
    </select>
  </div>
</div></code>```

Title: VueJs directive two way binding

Body:
I created a custom directive to handle select2 in VueJs. The code below works when I am binding a select to a data property in my viewmodel that is not a propert of an object within data.

Like this.userId but if it is bound to something like this.user.id, it would not update the value in my viewmodel data object.

Vue.directive('selected', {
    bind: function (el, binding, vnode) {
        var key = binding.expression;
        var select = $(el);

        select.select2();
        vnode.context.$data[binding.expression] = select.val();

        select.on('change', function () {
            vnode.context.$data[binding.expression] = select.val();
        });
    },
    update: function (el, binding, newVnode, oldVnode) {
        var select = $(el);
        select.val(binding.value).trigger('change');
    }
});

<select v-selected="userEditor.Id">
   <option v-for="user in users" v-bind:value="user.id" >
       {{ user.fullName}}
   </option>
</select>

Related fiddle:
https://jsfiddle.net/raime910/rHm4e/4/

Body:
A custom directive is perfectly fine, except use the insertedhook instead of bind.  Adapted from Vue Wrapper Component Example.

To bind to an object property, the simplest way is to wrap it in a computed setter Computed Setter and bind to that.

Note, 'deep setting' does not appear to work. The problem is one of change detection, which the computed setter overcomes. (Note that the on('change' function is jQuery not Vue.)

console.clear()

Vue.directive('selected', {
  inserted: function (el, binding, vnode) {
    var select = $(el);
    select
      .select2()
      .val(binding.value)
      .trigger('change')
      .on('change', function () {
        if (vnode.context[binding.expression]) {
          vnode.context[binding.expression] = select.val();
        }
      })
    },
});

var vm = new Vue({
  el: '#my-app',
  computed: {
    selectedValue: {
      get: function() { return this.myObj.type },
      set: function (value) { this.myObj.type = value }
    }
  },
  data: {
    selectedVal: 0,
    myObj: { type: 3 },
    opts: [{
      id: 1,
      text: 'Test 1'
    }, {
      id: 2,
      text: 'Test 2'
    }, {
      id: 3,
      text: 'Test 3'
    }]
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.js"></script>

<div id="my-app">
  <div>
    <label for="example">Test dropdown list ({{ myObj.type }})</label>
  </div>
  <div>
    <select id="example" style="width: 300px" v-selected="selectedValue">
      <option v-for="(opt,index) in opts" :value="opt.id" :key="index">
        {{ opt.text }}
      </option>
    </select>
  </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
why I get wrong current user in firebase android xamarin
I use this code to define Current user and email in Firebase:

```<code>var CurrentUserEmail = FirebaseAuth.Instance.CurrentUser.Email;
</code>```

It doesn't give the right user and email. Did you have the same issue?

答:
I found my mistake, in case who will meet the same case. I typed StartActivity right away after SignInWithEmailAndPassword:

```<code>auth.SignInWithEmailAndPassword(email,password)
                .AddOnCompleteListener(this,this);
StartActivity(intent);  // incorrect
</code>```

Right way to do it :

```<code> auth.SignInWithEmailAndPassword(email,password)
                        .AddOnCompleteListener(this,this);
    ...
    public void OnComplete(Task task)
   {
                if(task.IsSuccessful){

                    StartActivity(intent);
                    Finish();
                }
   }
</code>```

Body:
I use this code to define Current user and email in Firebase:

var CurrentUserEmail = FirebaseAuth.Instance.CurrentUser.Email;

It doesn't give the right user and email. Did you have the same issue?

Body:
I found my mistake, in case who will meet the same case. I typed StartActivity right away after SignInWithEmailAndPassword:

auth.SignInWithEmailAndPassword(email,password)
                .AddOnCompleteListener(this,this);
StartActivity(intent);  // incorrect

Right way to do it :

 auth.SignInWithEmailAndPassword(email,password)
                        .AddOnCompleteListener(this,this);
    ...
    public void OnComplete(Task task)
   {
                if(task.IsSuccessful){

                    StartActivity(intent);
                    Finish();
                }
   }


问:
Tool to find duplicate sections in a text (XML) file?
I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?

I'd be fine with a tool that does this generally for text documents.

答: Not easily.  My first thought is XSLT but it's hard to implement.  You'd have to go through each node and then do an XPATH select on every node with the same data.  That would find them, but you'd end up processing all of the nodes with the same data later as well (ie, no way to keep track of what node data you've already processed and ignore it).  You could do it with a real programming language but that's outside of my experience.</p>

OwnerDisplayName: parsifal

OwnerDisplayName: Stephen Friederichs


问:
JPA NamedNativeQuery with SqlResultMapping
I have a problem with native query. I have following entity:

```<code>    @Entity
@NamedNativeQueries({
    @NamedNativeQuery(name =  ExampleEntity.Q.getTestQuery, query = "SELECT a.name as name FROM ExampleEntity a WHERE a.id = 5", resultSetMapping = "nameMapping")
})

@SqlResultSetMapping(
    name = "nameMapping",
    entities = @EntityResult(
        entityClass = ExampleEntity.class,
        fields = {
            @FieldResult(name="name", column="name")
        }))

@Table(name = "ExampleEntity")
public class ExampleEntity implements Serializable {

    public static class Q {
        public static final String getTestQuery = "getTestQuery";
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;
</code>```

and I am trying to call this query in my @Service with following code:

```<code>Query qz = em.createNativeQuery(ExampleEntity.Q.getTestQuery, "nameMapping");
qz.getResultList();
</code>```

it returns error:

```<code>org.hibernate.exception.SQLGrammarException: could not extract ResultSet
</code>```

It is only simple example, but shows my problem.
Many thanks in advance!

答:
The problem is that createNativeQuery method expects SQL query string as the first parameter rather than the name used to refer to the SQL query itself. Here is the method definition:

public Query createNativeQuery(String sqlString, String
  resultSetMapping);

which brings us to the following:

```<code>Query qz = em.createNativeQuery("SELECT a.id, a.name FROM ExampleEntity a WHERE a.id = 5",
                                "nameMapping");
</code>```

The preferred solution is to use createNamedQuery instead which expects the name of the SQL query defined in a metadata:

public Query createNamedQuery(String name);

so based on the above we can fix the exception with the following:

```<code>Query qz = em.createNamedQuery(ExampleEntity.Q.getTestQuery);
</code>```

Body:
I have a problem with native query. I have following entity:

    @Entity
@NamedNativeQueries({
    @NamedNativeQuery(name =  ExampleEntity.Q.getTestQuery, query = "SELECT a.name as name FROM ExampleEntity a WHERE a.id = 5", resultSetMapping = "nameMapping")
})

@SqlResultSetMapping(
    name = "nameMapping",
    entities = @EntityResult(
        entityClass = ExampleEntity.class,
        fields = {
            @FieldResult(name="name", column="name")
        }))

@Table(name = "ExampleEntity")
public class ExampleEntity implements Serializable {

    public static class Q {
        public static final String getTestQuery = "getTestQuery";
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "surname")
    private String surname;

and I am trying to call this query in my @Service with following code:

Query qz = em.createNativeQuery(ExampleEntity.Q.getTestQuery, "nameMapping");
qz.getResultList();

it returns error:

org.hibernate.exception.SQLGrammarException: could not extract ResultSet

It is only simple example, but shows my problem.
Many thanks in advance!

Body:
The problem is that createNativeQuery method expects SQL query string as the first parameter rather than the name used to refer to the SQL query itself. Here is the method definition:

public Query createNativeQuery(String sqlString, String
  resultSetMapping);

which brings us to the following:

Query qz = em.createNativeQuery("SELECT a.id, a.name FROM ExampleEntity a WHERE a.id = 5",
                                "nameMapping");

The preferred solution is to use createNamedQuery instead which expects the name of the SQL query defined in a metadata:

public Query createNamedQuery(String name);

so based on the above we can fix the exception with the following:

Query qz = em.createNamedQuery(ExampleEntity.Q.getTestQuery);


问:
AWS API Gateway {"error": "missing authentication token"}
I've been constantly getting the "missing authentication token" error when I click the AWS API gateway POST method url through the browser. I set "AUTH" as none and it's working totally fine through Postman but not with the browser. The problem is that I'm using swift to trigger the method and it doesn't seem to be reaching the gateway at all (no log on CloudWatch) and I don't think my code is wrong (or maybe it is). If someone could point out what my mistake is or a solution to this problem I'd appreciate it so much.

P.S. My lambda function is working totally fine and I typed in the right URL (one in the code is just for example)

Here's my code:

```<code>func postNonceToServer(paymentMethodNonce: String) {

    let paymentURL = URL(string: "https://example-url.us-east-1.amazonaws.com/prod/create-transaction")!
    var request = URLRequest(url: paymentURL)
    request.httpBody = "\(paymentMethodNonce)".data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
}
</code>```

答:
In my opinion, this should be a problem in the URL itself. I can think of:

1- Please make sure that the URL is parsed correctly by printing it to the console and pasting it into the browser URL bar. (I have no idea about swift)

2- Make sure that "execute-api" is included in your "example-url", i.e., before the region.

3- Make sure that OPTIONS method has AUTH as none.

Good luck!

Body:
I've been constantly getting the "missing authentication token" error when I click the AWS API gateway POST method url through the browser. I set "AUTH" as none and it's working totally fine through Postman but not with the browser. The problem is that I'm using swift to trigger the method and it doesn't seem to be reaching the gateway at all (no log on CloudWatch) and I don't think my code is wrong (or maybe it is). If someone could point out what my mistake is or a solution to this problem I'd appreciate it so much.

P.S. My lambda function is working totally fine and I typed in the right URL (one in the code is just for example)

Here's my code:

func postNonceToServer(paymentMethodNonce: String) {

    let paymentURL = URL(string: "https://example-url.us-east-1.amazonaws.com/prod/create-transaction")!
    var request = URLRequest(url: paymentURL)
    request.httpBody = "\(paymentMethodNonce)".data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
}


问:
Google API PHP Refresh Token returns NULL
I'm using the Google APIs Client Library for PHP for offline authentication, but when I use this code:

```<code>$this->google->refreshToken($result["google_refresh_token"]));
</code>```

it returns NULL.

$this->google refers to an instance of the Google_Client class.

Anyone an idea what this could be?

If I try to change the given refresh token it returns a Google Exception Error, so it should be a valid token.

Thank you!

Edit:

```<code>'client_id' => 'myclientid',
      'client_secret' => 'myclientsecret',
      'redirect_uri' => 'mypage',
      'developer_key' => 'mydeveloperkey',

      // Other parameters.
      'access_type' => 'offline',
      'approval_prompt' => 'force',
</code>```

Maybe this helps you

答:
I was hitting my head against a wall for a very long time.

This is not immediately obvious but:

define('CREDENTIALS_PATH', '/vendor/google/credentials/credentials.json');

The line that references "credentials.json" or whatever your credentials file will be called-- this file should not exist when you start! If you have created that file before getting authorization– delete it then visit your script page– quickstart.php or whatever, and it will then ask you for authorization.

If you've tried refreshing the page over and over again there are usage limits (i.e. requesting authorization too many times), so you might need to create a new client_id in your developer console and update your define('CLIENT_SECRET_PATH') path.

I then added this:

```<code>// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $jsonCred = file_get_contents(CREDENTIALS_PATH);
    $jsonArray = json_decode($jsonCred, true);

    $client->fetchAccessTokenWithRefreshToken($jsonArray["refresh_token"]);

    $newAccessToken = $client->getAccessToken();
    $accessToken = array_merge($jsonArray, $newAccessToken);

    file_put_contents($credentialsPath, json_encode($accessToken));
}
</code>```

```

Body:
I'm using the Google APIs Client Library for PHP for offline authentication, but when I use this code:

$this->google->refreshToken($result["google_refresh_token"]));

it returns NULL.

$this->google refers to an instance of the Google_Client class.

Anyone an idea what this could be?

If I try to change the given refresh token it returns a Google Exception Error, so it should be a valid token.

Thank you!

Edit:

'client_id' => 'myclientid',
      'client_secret' => 'myclientsecret',
      'redirect_uri' => 'mypage',
      'developer_key' => 'mydeveloperkey',

      // Other parameters.
      'access_type' => 'offline',
      'approval_prompt' => 'force',

Maybe this helps you

Body:
I was hitting my head against a wall for a very long time.

This is not immediately obvious but:

define('CREDENTIALS_PATH', '/vendor/google/credentials/credentials.json');

The line that references "credentials.json" or whatever your credentials file will be called-- this file should not exist when you start! If you have created that file before getting authorization– delete it then visit your script page– quickstart.php or whatever, and it will then ask you for authorization.

If you've tried refreshing the page over and over again there are usage limits (i.e. requesting authorization too many times), so you might need to create a new client_id in your developer console and update your define('CLIENT_SECRET_PATH') path.

I then added this:

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $jsonCred = file_get_contents(CREDENTIALS_PATH);
    $jsonArray = json_decode($jsonCred, true);

    $client->fetchAccessTokenWithRefreshToken($jsonArray["refresh_token"]);

    $newAccessToken = $client->getAccessToken();
    $accessToken = array_merge($jsonArray, $newAccessToken);

    file_put_contents($credentialsPath, json_encode($accessToken));
}

```


问:
recursion not working as desired
the keword rec do not do anything and do not cause any segmentation fault
like this example</p>

```<code> let rec x x=x+x in x 2;;
 :-int=2
</code>```

答:
In this definition:

```<code>let rec x x = x + x
</code>```

The "recursive" function name x is hidden by the parameter named x. It's just as if you had:

```<code>let rec x y = let x = y in x + x
</code>```

In essence there is an inner binding that hides the recursive one.

Title: recursion not working as desired

Body:
the keword rec do not do anything and do not cause any segmentation fault
like this example

 let rec x x=x+x in x 2;;
 :-int=2

Body:
In this definition:

let rec x x = x + x

The "recursive" function name x is hidden by the parameter named x. It's just as if you had:

let rec x y = let x = y in x + x

In essence there is an inner binding that hides the recursive one.


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答: There is no such standard, just considerations of common sense. Check this link: http://www.useit.com/alertbox/20000416.html</p>


问:
returning a pointer that points to char array. How do i print out the entire contents of the array?
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //
</code>```

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

答:
You can do two things. Either you can choose to return a char*. The code of which is below:

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  *ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char *ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return revBuffer;
}
</code>```

Or, you can print the string in your fuction only. The code of which is:

```<code>#include <iostream>
#include <string.h>
using namespace std;

void  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    ReverseString(&str[0]);

}

void  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    cout << revBuffer;
}
</code>```

The code is self explanatory.

Body:
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

Body:
You can do two things. Either you can choose to return a char*. The code of which is below:

#include <iostream>
#include <string.h>
using namespace std;

char  *ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char *ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return revBuffer;
}

Or, you can print the string in your fuction only. The code of which is:

#include <iostream>
#include <string.h>
using namespace std;

void  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    ReverseString(&str[0]);

}

void  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    cout << revBuffer;
}

The code is self explanatory.


问:
Programmatically generate methods for a class
I have about 20 methods to redirect to a wrapper method that takes the original method, and the rest of the arguments:

```<code>class my_socket(parent):

    def _in(self, method, *args, **kwargs):
        # do funky stuff

    def recv(self, *args, **kwargs):
        return self._in(super().recv, *args, **kwargs)

    def recv_into(self, *args, **kwargs):
        return self._in(super().recv_into, *args, **kwargs)

    # and so on...
</code>```

How can I add more of these methods programmatically? This is about as far as I get before everything starts to look wrong:

```<code>for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...:
    setattr(my_socket, method, ???)
</code>```

Can I do this by assigning within the class definition, or something else that feels more natural?

```<code>class my_socket(parent):

    def makes_recv_methods(name):
        # wraps call to name

    def recv_meh = makes_recv_methods('recv_meh')
</code>```

I'd prefer to use __get__ and friends when possible over magic functions from types.

答:
I'd like to expand on the accepted answer. I wanted to potentially have a very long list of decorator methods applied to a very long list of methods.

```<code>import functools

def wrap_method(cls, name, wrapper_method_name):
    # This unbound method will be pulled from the superclass.
    wrapped = getattr(cls, name, wrapper_method_name)

    @functools.wraps(wrapped)
    def wrapper(self, *args, **kwargs):
        wrapper_method = getattr(self, wrapper_method_name)
        return wrapper_method(wrapped.__get__(self, cls), *args, **kwargs)

    return wrapper

def wrap_methods(cls):
    for wrapper_method_name in cls.WRAPPER_METHOD_NAMES:
        for name in cls.WRAPPED_METHODS:
            setattr(cls, name, wrap_method(cls, name, wrapper_method_name))
    return cls
</code>```

And here is the class that wraps the original

```<code>@wrap_methods
class WrappedConnection(BaseConnection):
    """
    This class adds some quality-of-life improvements to the BaseConnection class.
    -WRAPPED_METHODS are wrapped by WRAPPER_METHOD_NAMES
    -wrappers can be toggled on and off.

    example:
    connection = WrappedConnection(show_messages=True, log_errors=False, keep_authenticated=False)

    default:
    connection = WrappedConnection(show_messages=False, log_errors=True, keep_authenticated=True)
    """
    WRAPPER_METHOD_NAMES = ['log_errors', 'keep_authenticated', 'show_messages']
    WRAPPED_METHODS = ['a_method', 'b_method', 'c_method', 'd_method']
    MESSAGE_OVERRIDE_MAP = {"a_method": "a_method_message_override_attribute",
                            "b_method": "b_method_message_override_attribute"}

    def keep_authenticated(self, method, *args, **kwargs):
        """
        If the session has expired, the session is re-authenticated. The incident is logged by the default logger.
        This option can be turned off by setting keep_authenticated during initialization of a WrappedConnection object.
        - connection = WrappedConnection(keep_authenticated=False) # why would you ever do this

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @keep_authenticated
        """
        response, expired_session = method(*args, **kwargs), None
        if response["errors"] and self._keep_authenticated:
            expired_session = list(filter(lambda x: 'expired session' in x, response["errors"]))
        if expired_session:
            self.__init__()
            logging.info('Session has been re-authenticated.')
            response = method(*args, **kwargs)
        return response

    def log_errors(self, method, *args, **kwargs):
        """
        If there is an error the incident is logged. This option can be turned off by setting log_errors
        during initialization of a WrappedConnection object.
        - connection = WrappedConnection(log_errors=False)

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @log_errors
        """
        response = method(*args, **kwargs)
        if response["errors"] and self._log_errors:
            errors = response["errors"]
            logging.error(errors)
        return response

    def show_messages(self, method, *args, **kwargs):
        """
        Shows the xml that is sent during the request. This option can be turned on by setting show_messages during
        initialization of a WrappedConnection object.
        - connection = WrappedConnection(show_messages=True)

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @show_messages
        """
        response = method(*args, **kwargs)
        if self._show_messages:
            message_override_attr = WrappedConnection.MESSAGE_OVERRIDE_MAP.get(method.__name__)
            if message_override_attr:
                message_override = getattr(self, message_override_attr)
                print(BeautifulSoup(message_override, "xml").prettify())
            else:
                self._show_message(method.__name__, *args, **kwargs)
        return response

    def __init__(self, *args, keep_authenticated=True, log_errors=True, show_messages=False, **kwargs):
        super(WrappedConnection, self).__init__(*args, **kwargs)
        self._keep_authenticated = keep_authenticated
        self._log_errors = log_errors
        self._show_messages = show_messages
</code>```

Body:
I have about 20 methods to redirect to a wrapper method that takes the original method, and the rest of the arguments:

class my_socket(parent):

    def _in(self, method, *args, **kwargs):
        # do funky stuff

    def recv(self, *args, **kwargs):
        return self._in(super().recv, *args, **kwargs)

    def recv_into(self, *args, **kwargs):
        return self._in(super().recv_into, *args, **kwargs)

    # and so on...

How can I add more of these methods programmatically? This is about as far as I get before everything starts to look wrong:

for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...:
    setattr(my_socket, method, ???)

Can I do this by assigning within the class definition, or something else that feels more natural?

class my_socket(parent):

    def makes_recv_methods(name):
        # wraps call to name

    def recv_meh = makes_recv_methods('recv_meh')

I'd prefer to use __get__ and friends when possible over magic functions from types.

Body:
I'd like to expand on the accepted answer. I wanted to potentially have a very long list of decorator methods applied to a very long list of methods.

import functools

def wrap_method(cls, name, wrapper_method_name):
    # This unbound method will be pulled from the superclass.
    wrapped = getattr(cls, name, wrapper_method_name)

    @functools.wraps(wrapped)
    def wrapper(self, *args, **kwargs):
        wrapper_method = getattr(self, wrapper_method_name)
        return wrapper_method(wrapped.__get__(self, cls), *args, **kwargs)

    return wrapper

def wrap_methods(cls):
    for wrapper_method_name in cls.WRAPPER_METHOD_NAMES:
        for name in cls.WRAPPED_METHODS:
            setattr(cls, name, wrap_method(cls, name, wrapper_method_name))
    return cls

And here is the class that wraps the original

@wrap_methods
class WrappedConnection(BaseConnection):
    """
    This class adds some quality-of-life improvements to the BaseConnection class.
    -WRAPPED_METHODS are wrapped by WRAPPER_METHOD_NAMES
    -wrappers can be toggled on and off.

    example:
    connection = WrappedConnection(show_messages=True, log_errors=False, keep_authenticated=False)

    default:
    connection = WrappedConnection(show_messages=False, log_errors=True, keep_authenticated=True)
    """
    WRAPPER_METHOD_NAMES = ['log_errors', 'keep_authenticated', 'show_messages']
    WRAPPED_METHODS = ['a_method', 'b_method', 'c_method', 'd_method']
    MESSAGE_OVERRIDE_MAP = {"a_method": "a_method_message_override_attribute",
                            "b_method": "b_method_message_override_attribute"}

    def keep_authenticated(self, method, *args, **kwargs):
        """
        If the session has expired, the session is re-authenticated. The incident is logged by the default logger.
        This option can be turned off by setting keep_authenticated during initialization of a WrappedConnection object.
        - connection = WrappedConnection(keep_authenticated=False) # why would you ever do this

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @keep_authenticated
        """
        response, expired_session = method(*args, **kwargs), None
        if response["errors"] and self._keep_authenticated:
            expired_session = list(filter(lambda x: 'expired session' in x, response["errors"]))
        if expired_session:
            self.__init__()
            logging.info('Session has been re-authenticated.')
            response = method(*args, **kwargs)
        return response

    def log_errors(self, method, *args, **kwargs):
        """
        If there is an error the incident is logged. This option can be turned off by setting log_errors
        during initialization of a WrappedConnection object.
        - connection = WrappedConnection(log_errors=False)

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @log_errors
        """
        response = method(*args, **kwargs)
        if response["errors"] and self._log_errors:
            errors = response["errors"]
            logging.error(errors)
        return response

    def show_messages(self, method, *args, **kwargs):
        """
        Shows the xml that is sent during the request. This option can be turned on by setting show_messages during
        initialization of a WrappedConnection object.
        - connection = WrappedConnection(show_messages=True)

        :param method: (method) method to be wrapped
        :param args: (args) passed args
        :param kwargs: (kwargs) passed kwargs
        :return: (method) method wrapped by @show_messages
        """
        response = method(*args, **kwargs)
        if self._show_messages:
            message_override_attr = WrappedConnection.MESSAGE_OVERRIDE_MAP.get(method.__name__)
            if message_override_attr:
                message_override = getattr(self, message_override_attr)
                print(BeautifulSoup(message_override, "xml").prettify())
            else:
                self._show_message(method.__name__, *args, **kwargs)
        return response

    def __init__(self, *args, keep_authenticated=True, log_errors=True, show_messages=False, **kwargs):
        super(WrappedConnection, self).__init__(*args, **kwargs)
        self._keep_authenticated = keep_authenticated
        self._log_errors = log_errors
        self._show_messages = show_messages


问:
How Can I Detect If One Div Is Outside Another Div?
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }</code>```

     ```

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

答:
I figured out a simple, more understandable way to do this.

I created a variables for the testdiv's width, height, x, y, x offset from
mouse, and y offset from mouse.

```<code>var divw = 50;
var divh = 50;

var divofx = 25;
var divofy = 25;
</code>```

Then I made a variable for the city divs width.

```<code>var cityw = 500;
</code>```

Then, I used screen.width / 2 to find the center of the screen.

```<code>var centerx = screen.width / 2;
</code>```

Then, I made the size of the testdiv changeable at any time by putting the code below into the main function :

```<code>document.getElementById("testdiv").style.width = divw;
document.getElementById("testdiv").style.height = divh;
</code>```

Then I used the width variable to find the edges of the city div.

Then, based off of the edges, I made some simple collision detecting if statements. I also did not need to change the Y mutch since it pretty mutch stays the same.

```<code>        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);
</code>```

Now the whole program looks like:

```<code><html>

  <head>

    <style>

      #city{
        border: 1px dotted white;
        background-color: lightgreen;
        height: 500;
        width: 500;
        overflow: none;
        max-height: 500px;
        max-width: 500px;
        min-height: 100px;
        min-width: 100px;
      }
      #xy{
        color: white;
      }
      #testdiv{
        background-color: white;
        position: absolute;
        width: 100px;
        height: 100px;
      }
      #body{
        background-color: black;
      }

    </style>
    <script>

    var mousex, mousey;
    var divw = 50;
    var divh = 50;
    var divofx = 25;
    var divofy = 25;
    var cityw = 500;

      function mousepos(e){
        mousex = e.clientX - divofx;
        mousey = e.clientY - divofy;
        document.getElementById("xy").innerText = mousex + " , " + mousey;
      }

      function testdiv(){
        var centerx = screen.width / 2;

        document.getElementById("city").style.width = cityw;
        document.getElementById("testdiv").style.width = divw;
        document.getElementById("testdiv").style.height = divh;

        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);
      }

    </script>

  </head>

  <body id="body" onload="testdiv()" onmousemove="mousepos(event);">

    <center>
      <div id="city" onmousemove="mousepos(event);">
        <div id="testdiv"></div>
      </div>

      <p id="xy"></p>
    </center>

  </body>

</html>
</code>```

Body:
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }

          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

Body:
I figured out a simple, more understandable way to do this.

I created a variables for the testdiv's width, height, x, y, x offset from
mouse, and y offset from mouse.

var divw = 50;
var divh = 50;

var divofx = 25;
var divofy = 25;

Then I made a variable for the city divs width.

var cityw = 500;

Then, I used screen.width / 2 to find the center of the screen.

var centerx = screen.width / 2;

Then, I made the size of the testdiv changeable at any time by putting the code below into the main function :

document.getElementById("testdiv").style.width = divw;
document.getElementById("testdiv").style.height = divh;

Then I used the width variable to find the edges of the city div.

Then, based off of the edges, I made some simple collision detecting if statements. I also did not need to change the Y mutch since it pretty mutch stays the same.

        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);

Now the whole program looks like:

<html>

  <head>

    <style>

      #city{
        border: 1px dotted white;
        background-color: lightgreen;
        height: 500;
        width: 500;
        overflow: none;
        max-height: 500px;
        max-width: 500px;
        min-height: 100px;
        min-width: 100px;
      }
      #xy{
        color: white;
      }
      #testdiv{
        background-color: white;
        position: absolute;
        width: 100px;
        height: 100px;
      }
      #body{
        background-color: black;
      }

    </style>
    <script>

    var mousex, mousey;
    var divw = 50;
    var divh = 50;
    var divofx = 25;
    var divofy = 25;
    var cityw = 500;

      function mousepos(e){
        mousex = e.clientX - divofx;
        mousey = e.clientY - divofy;
        document.getElementById("xy").innerText = mousex + " , " + mousey;
      }

      function testdiv(){
        var centerx = screen.width / 2;

        document.getElementById("city").style.width = cityw;
        document.getElementById("testdiv").style.width = divw;
        document.getElementById("testdiv").style.height = divh;

        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);
      }

    </script>

  </head>

  <body id="body" onload="testdiv()" onmousemove="mousepos(event);">

    <center>
      <div id="city" onmousemove="mousepos(event);">
        <div id="testdiv"></div>
      </div>

      <p id="xy"></p>
    </center>

  </body>

</html>


问:
Using ES6 imports to add methods to a class prototype yields errors with 'this'
Consider the following two files:

```<code>// push.js
export default (item) => {
  this.items.push(item);
};
</code>```

-

```<code>// index.js
import push from './push';

class pushy {
  constructor() {
    this.items = [];
  }
}

pushy.prototype.push = push;

export default pushy;
</code>```

The intended effect would be for the exported pushy to have a push method available, that would push to this.items. The actual result however is an error.

TypeError: Cannot read property 'items' of undefined

The errors shows that this seems to be an issue.

Now interestingly, if one were to revert back to require and module.exports everything works perfectly as expected.

```<code>// push.js
module.exports = function(item) {
  this.items.push(item);
};
</code>```

-

```<code>// index.js
function pushy() {
  this.items = [];
}

pushy.prototype.push = require('./push');

module.exports = pushy;
</code>```

As far as I can tell both versions should be the same, yet they are not. Is there a way to make this work with ES6 or will I have to resort to using old syntax?

答:
The whole point of arrow functions is that they bind the lexical this value and never let it go. Because of this, you can't use them in this case. You do have to use function expressions (or declarations) for functions in which the this value will vary.

There's nothing wrong with using function expressions. They may not look as nice (in my opinion) but they're really just another tool.

Body:
Consider the following two files:

// push.js
export default (item) => {
  this.items.push(item);
};

-

// index.js
import push from './push';

class pushy {
  constructor() {
    this.items = [];
  }
}

pushy.prototype.push = push;

export default pushy;

The intended effect would be for the exported pushy to have a push method available, that would push to this.items. The actual result however is an error.

TypeError: Cannot read property 'items' of undefined

The errors shows that this seems to be an issue.

Now interestingly, if one were to revert back to require and module.exports everything works perfectly as expected.

// push.js
module.exports = function(item) {
  this.items.push(item);
};

-

// index.js
function pushy() {
  this.items = [];
}

pushy.prototype.push = require('./push');

module.exports = pushy;

As far as I can tell both versions should be the same, yet they are not. Is there a way to make this work with ES6 or will I have to resort to using old syntax?


问:
How to override css containing '!important' using jquery?
I want to apply height for specific div using jquery but not able to override the '!important' keyword using jquery.

Here is markup:

```<code><div id="divL1" class="myclass">sometext here</div>
<div id="divL2" class="myclass">sometext here</div>
<div id="divL3" class="myclass">sometext here</div>
<div id="divL4" class="myclass">sometext here</div>
</code>```

css:

```<code>.myclass{
 height:50px !important;
}
</code>```

Here i want to find the class "myclass" where divid equals "divL3"

I have Tried with:

```<code>$('#divL3.myclass').css('height', '0px');
</code>```

but wont work! so, how to override '!important' css using jquery.

Help appreciated!

答:
I was running into a problem where we allow the users to define their own font size for Kendo Grids, however after setting the value, and then manipulating the grid in any way, it'd reset the font size. So we actually defined an ID for the style tag and changed the html with the proper CSS each time.

At the top of our main page, we set the font-size by what is saved in their PHP Session Variable, or from the database.

```<code>echo "<style id='grid-style'>table { font-size: $Grid_Font_Size !important; }</style>";
</code>```

Then in order to change it, we do the following jquery where font_size is the new size

```<code>$( "#grid-style" ).html( "table { font-size: " + font_size + "px !important; }" );
</code>```

Body:
I want to apply height for specific div using jquery but not able to override the '!important' keyword using jquery.

Here is markup:

sometext here

sometext here

sometext here

sometext here

css:

.myclass{
 height:50px !important;
}

Here i want to find the class "myclass" where divid equals "divL3"

I have Tried with:

$('#divL3.myclass').css('height', '0px');

but wont work! so, how to override '!important' css using jquery.

Help appreciated!

Body:
I was running into a problem where we allow the users to define their own font size for Kendo Grids, however after setting the value, and then manipulating the grid in any way, it'd reset the font size. So we actually defined an ID for the style tag and changed the html with the proper CSS each time.

At the top of our main page, we set the font-size by what is saved in their PHP Session Variable, or from the database.

echo "<style id='grid-style'>table { font-size: $Grid_Font_Size !important; }</style>";

Then in order to change it, we do the following jquery where font_size is the new size

$( "#grid-style" ).html( "table { font-size: " + font_size + "px !important; }" );


问:
What is the time complexity of iterating through a deque in Python?
What is the time complexity of iterating, or more precisely each iteration through a deque from the collections library in Python?

An example is this:

```<code>elements = deque([1,2,3,4])
for element in elements:
  print(element)
</code>```

Is each iteration a constant O(1) operation? or does it do a linear O(n) operation to get to the element in each iteration?

There are many resources online for time complexity with all of the other deque methods like appendleft, append, popleft, pop. There doesn't seem to be any time complexity information about the iteration of a deque.

Thanks!

答:
If your construction is something like:

```<code>elements = deque([1,2,3,4])
for i in range(len(elements)):
    print(elements[i])
</code>```

You are not iterating over the deque, you are iterating over the range object, and then indexing into the deque. This makes the iteration polynomial time, since each indexing operation, elements[i] is O(n). However, actually iterating over the deque is linear time.

```<code>for x in elements:
    print(x)
</code>```

Here's a quick, empirical test:

```<code>import timeit
import pandas as pd
from collections import deque

def build_deque(n):
    return deque(range(n))

def iter_index(d):
    for i in range(len(d)):
        d[i]

def iter_it(d):
    for x in d:
        x

r = range(100, 10001, 100)

index_runs = [timeit.timeit('iter_index(d)', 'from __main__ import build_deque, iter_index, iter_it; d = build_deque({})'.format(n), number=1000) for n in r]
it_runs = [timeit.timeit('iter_it(d)', 'from __main__ import build_deque, iter_index, iter_it; d = build_deque({})'.format(n), number=1000) for n in r]

df = pd.DataFrame({'index':index_runs, 'iter':it_runs}, index=r)
df.plot()
</code>```

And the resulting plot:

Now, we can actually see how the iterator protocol is implemented for deque objects in CPython source code:

First, the deque object itself:

typedef struct BLOCK {
    struct BLOCK *leftlink;
    PyObject *data[BLOCKLEN];
    struct BLOCK *rightlink;
} block;

typedef struct {
    PyObject_VAR_HEAD
    block *leftblock;
    block *rightblock;
    Py_ssize_t leftindex;       /* 0 <= leftindex < BLOCKLEN */
    Py_ssize_t rightindex;      /* 0 <= rightindex < BLOCKLEN */
    size_t state;               /* incremented whenever the indices move */
    Py_ssize_t maxlen;
    PyObject *weakreflist;
} dequeobject;
```
<p>So, as stated in the comments, a <code>deque</code> is a  doubly-linked list of "block" nodes, where a block is essentially an array of python object pointers. Now for the iterator protocol:</p>
<pre class="lang-c prettyprint-override"><code>typedef struct {
    PyObject_HEAD
    block *b;
    Py_ssize_t index;
    dequeobject *deque;
    size_t state;          /* state when the iterator is created */
    Py_ssize_t counter;    /* number of items remaining for iteration */
} dequeiterobject;

static PyTypeObject dequeiter_type;

static PyObject *
deque_iter(dequeobject *deque)
{
    dequeiterobject *it;

    it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
    if (it == NULL)
        return NULL;
    it->b = deque->leftblock;
    it->index = deque->leftindex;
    Py_INCREF(deque);
    it->deque = deque;
    it->state = deque->state;
    it->counter = Py_SIZE(deque);
    PyObject_GC_Track(it);
    return (PyObject *)it;
}

// ...

static PyObject *
dequeiter_next(dequeiterobject *it)
{
    PyObject *item;

    if (it->deque->state != it->state) {
        it->counter = 0;
        PyErr_SetString(PyExc_RuntimeError,
                        "deque mutated during iteration");
        return NULL;
    }
    if (it->counter == 0)
        return NULL;
    assert (!(it->b == it->deque->rightblock &&
              it->index > it->deque->rightindex));

    item = it->b->data[it->index];
    it->index++;
    it->counter--;
    if (it->index == BLOCKLEN && it->counter > 0) {
        CHECK_NOT_END(it->b->rightlink);
        it->b = it->b->rightlink;
        it->index = 0;
    }
    Py_INCREF(item);
    return item;
}
</code>```

As you can see, the iterator essentially keeps track of a block index, a pointer to a block, and a counter of total items in the deque. It stops iterating if the counter reaches zero, if not, it grabs the element at the current index, increments the index, decrements the counter, and tales care of checking whether to move to the next block or not. In other words, A deque could be represented as a list-of-lists in Python, e.g. d = [[1,2,3],[4,5,6]], and it iterates

```<code>for block in d:
    for x in block:
        ...
</code>```

Body:
What is the time complexity of iterating, or more precisely each iteration through a deque from the collections library in Python?

An example is this:

elements = deque([1,2,3,4])
for element in elements:
  print(element)

Is each iteration a constant O(1) operation? or does it do a linear O(n) operation to get to the element in each iteration?

There are many resources online for time complexity with all of the other deque methods like appendleft, append, popleft, pop. There doesn't seem to be any time complexity information about the iteration of a deque.

Thanks!

Body:
If your construction is something like:

elements = deque([1,2,3,4])
for i in range(len(elements)):
    print(elements[i])

You are not iterating over the deque, you are iterating over the range object, and then indexing into the deque. This makes the iteration polynomial time, since each indexing operation, elements[i] is O(n). However, actually iterating over the deque is linear time.

for x in elements:
    print(x)

Here's a quick, empirical test:

import timeit
import pandas as pd
from collections import deque

def build_deque(n):
    return deque(range(n))

def iter_index(d):
    for i in range(len(d)):
        d[i]

def iter_it(d):
    for x in d:
        x

r = range(100, 10001, 100)

index_runs = [timeit.timeit('iter_index(d)', 'from __main__ import build_deque, iter_index, iter_it; d = build_deque({})'.format(n), number=1000) for n in r]
it_runs = [timeit.timeit('iter_it(d)', 'from __main__ import build_deque, iter_index, iter_it; d = build_deque({})'.format(n), number=1000) for n in r]

df = pd.DataFrame({'index':index_runs, 'iter':it_runs}, index=r)
df.plot()

And the resulting plot:

Now, we can actually see how the iterator protocol is implemented for deque objects in CPython source code:

First, the deque object itself:

typedef struct BLOCK {
    struct BLOCK *leftlink;
    PyObject *data[BLOCKLEN];
    struct BLOCK *rightlink;
} block;

typedef struct {
    PyObject_VAR_HEAD
    block *leftblock;
    block *rightblock;
    Py_ssize_t leftindex;       /* 0 <= leftindex < BLOCKLEN */
    Py_ssize_t rightindex;      /* 0 <= rightindex < BLOCKLEN */
    size_t state;               /* incremented whenever the indices move */
    Py_ssize_t maxlen;
    PyObject *weakreflist;
} dequeobject;

So, as stated in the comments, a deque is a  doubly-linked list of "block" nodes, where a block is essentially an array of python object pointers. Now for the iterator protocol:

typedef struct {
    PyObject_HEAD
    block *b;
    Py_ssize_t index;
    dequeobject *deque;
    size_t state;          /* state when the iterator is created */
    Py_ssize_t counter;    /* number of items remaining for iteration */
} dequeiterobject;

static PyTypeObject dequeiter_type;

static PyObject *
deque_iter(dequeobject *deque)
{
    dequeiterobject *it;

    it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
    if (it == NULL)
        return NULL;
    it->b = deque->leftblock;
    it->index = deque->leftindex;
    Py_INCREF(deque);
    it->deque = deque;
    it->state = deque->state;
    it->counter = Py_SIZE(deque);
    PyObject_GC_Track(it);
    return (PyObject *)it;
}

// ...

static PyObject *
dequeiter_next(dequeiterobject *it)
{
    PyObject *item;

    if (it->deque->state != it->state) {
        it->counter = 0;
        PyErr_SetString(PyExc_RuntimeError,
                        "deque mutated during iteration");
        return NULL;
    }
    if (it->counter == 0)
        return NULL;
    assert (!(it->b == it->deque->rightblock &&
              it->index > it->deque->rightindex));

    item = it->b->data[it->index];
    it->index++;
    it->counter--;
    if (it->index == BLOCKLEN && it->counter > 0) {
        CHECK_NOT_END(it->b->rightlink);
        it->b = it->b->rightlink;
        it->index = 0;
    }
    Py_INCREF(item);
    return item;
}

As you can see, the iterator essentially keeps track of a block index, a pointer to a block, and a counter of total items in the deque. It stops iterating if the counter reaches zero, if not, it grabs the element at the current index, increments the index, decrements the counter, and tales care of checking whether to move to the next block or not. In other words, A deque could be represented as a list-of-lists in Python, e.g. d = [[1,2,3],[4,5,6]], and it iterates

for block in d:
    for x in block:
        ...