问:
How to programmatically animate an ImageView
I am trying to animate an ImageView when the said image view is clicked.

Specifically I want the size of the ImageView gets bigger (say .20 bigger) and the immediately shrink back to its original size).

So far I have been experimenting with this code with no luck.

```<code>// thumbLike is the imageView I would like to animate.
button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        ScaleAnimation scaleAnim = new ScaleAnimation(1.0f, 2.5f, 1.0f, 2.5f,
                                    Animation.RELATIVE_TO_SELF, 0.5f,
                                    Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnim.setInterpolator(new LinearInterpolator());
        scaleAnim.setDuration(1500);
        thumbLike.startAnimation(scaleAnim);
        thumbLike.setAnimation(null);
    }
});
</code>```

Can anyone suggest me with a possible solution?

Edit #1

It is working through XML as answered by Hardik4560:

```<code>// finally i use this code to execute the animation
Animation animationScaleUp = AnimationUtils.loadAnimation(this, R.anim.scale_up);
Animation animationScaleDown = AnimationUtils.loadAnimation(this, R.anim.scale_down);

AnimationSet growShrink = new AnimationSet(true);
growShrink.addAnimation(animationScaleUp);
growShrink.addAnimation(animationScaleDown);
thumbLike.startAnimation(growShrink);
</code>```

and the XML

```<code>SCALE_UP
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.0"
        android:toXScale="1.5"
        android:fromYScale="1.0"
        android:toYScale="1.5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000" />
</set>

SCALE_DOWN
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.5"
        android:toXScale="1.0"
        android:fromYScale="1.5"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000" />
</set>
</code>```

ps: this is awkward, since I already accepted an answer. I am trying to combine between @tharkbad and @Hardik4560 's answers yet now the way it animates does not look smooth.

during the scale_up animation, it kinda look like being "skip" to the end of animation and then immediately starting scale_down animation. I guess I have to play around with it a bit.

答:
I created the same animation using kotlin:

Repo: https://github.com/David-Hackro/Bounce-Animation

You need create your element and extend of anything (ImageView,Button etc)
in my case y created a class named BounceWidget

Add element in xml

```<code><hackro.tutorials.com.bounceWidget.widget.BounceWidget
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Add element programmatically

```<code>val xpp = resources.getXml(R.xml.bouncewidget)
val attr = Xml.asAttributeSet(xpp)
val layout : LinearLayout = findViewById(R.id.layout)
val octocat1 : BounceWidget = BounceWidget(this,attr)

//you can change this values and have default values

//octocat1.id_resource(R.mipmap.bounceimage) // change image --> default : R.mipmap.ic_launcher
//octocat1.positionX = 1 //position X starting --> default : 0
//octocat1.positionY = 1 //position Y starting--> default : 0
//octocat1.velocityX = 1 //Velocity X --> default : 20
//octocat1.velocityY = 1 //Velocity Y --> default : 15

octocat1.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

layout.addView(octocat1)
</code>```

Body:
I am trying to animate an ImageView when the said image view is clicked.

Specifically I want the size of the ImageView gets bigger (say .20 bigger) and the immediately shrink back to its original size).

So far I have been experimenting with this code with no luck.

// thumbLike is the imageView I would like to animate.
button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        ScaleAnimation scaleAnim = new ScaleAnimation(1.0f, 2.5f, 1.0f, 2.5f,
                                    Animation.RELATIVE_TO_SELF, 0.5f,
                                    Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnim.setInterpolator(new LinearInterpolator());
        scaleAnim.setDuration(1500);
        thumbLike.startAnimation(scaleAnim);
        thumbLike.setAnimation(null);
    }
});

Can anyone suggest me with a possible solution?

Edit #1

It is working through XML as answered by Hardik4560:

// finally i use this code to execute the animation
Animation animationScaleUp = AnimationUtils.loadAnimation(this, R.anim.scale_up);
Animation animationScaleDown = AnimationUtils.loadAnimation(this, R.anim.scale_down);

AnimationSet growShrink = new AnimationSet(true);
growShrink.addAnimation(animationScaleUp);
growShrink.addAnimation(animationScaleDown);
thumbLike.startAnimation(growShrink);

and the XML

SCALE_UP
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.0"
        android:toXScale="1.5"
        android:fromYScale="1.0"
        android:toYScale="1.5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000" />
</set>

SCALE_DOWN
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.5"
        android:toXScale="1.0"
        android:fromYScale="1.5"
        android:toYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="1000" />
</set>

ps: this is awkward, since I already accepted an answer. I am trying to combine between @tharkbad and @Hardik4560 's answers yet now the way it animates does not look smooth.

during the scale_up animation, it kinda look like being "skip" to the end of animation and then immediately starting scale_down animation. I guess I have to play around with it a bit.

Body:
I created the same animation using kotlin:

Repo: https://github.com/David-Hackro/Bounce-Animation

You need create your element and extend of anything (ImageView,Button etc)
in my case y created a class named BounceWidget

Add element in xml

<hackro.tutorials.com.bounceWidget.widget.BounceWidget
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Add element programmatically

val xpp = resources.getXml(R.xml.bouncewidget)
val attr = Xml.asAttributeSet(xpp)
val layout : LinearLayout = findViewById(R.id.layout)
val octocat1 : BounceWidget = BounceWidget(this,attr)

//you can change this values and have default values

//octocat1.id_resource(R.mipmap.bounceimage) // change image --> default : R.mipmap.ic_launcher
//octocat1.positionX = 1 //position X starting --> default : 0
//octocat1.positionY = 1 //position Y starting--> default : 0
//octocat1.velocityX = 1 //Velocity X --> default : 20
//octocat1.velocityY = 1 //Velocity Y --> default : 15

octocat1.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

layout.addView(octocat1)


来源: stackexchange

问:
Kotlin File in Native iOS Project with Kotlin/Native
I would like to include a Kotlin file that only performs data processing and network operations in an existing iOS project, while keeping native iOS UI code.

While I thought that this may be achievable with Kotlin/Native, the iOS samples (1,2) that I found that use Kotlin/Native seem to take over the iOS UI code as well.

Is including a Kotlin file for data transfer in iOS possible with Kotlin/Native without touching the UI code, and if so, what are the steps to do so?

答:
Yes, it is possible in a cross-platform project to transfer data between Kotlin and native iOS UI Code by using Kotlin/Native. This allows to have a common code base for the data model based on Kotlin, while e.g. continuing to use native UI code for iOS.

The original proof:

The project https://github.com/justMaku/Kotlin-Native-with-Swift pointed me in the right direction, since it shows the essential steps to do so:

In a Swift UIViewController, it calls a wrapper function that shall receive a string from a Kotlin function. The call is mediated through a C++ layer, which itself starts the Kotlin runtime, passes the request to a Kotlin function, receives the string from it, and passes it back to the Swift UIViewController, which then displays it.

On the technical level, the project contains a script that compiles the Kotlin, C++, and Kotlin/Native part into a static library, which then can be called from the native iOS project.

To get the code to run, I had (after cloning from git) to perform a "git submodule sync" before running "./setup.sh".

To transfer data with a data model based on Kotlin, I would like to have a generic function, that can pass data to Kotlin, modify that data, and return the result back to the native iOS code. As a proof of principle, that such a function can be build, I extended the project to not only receive a string from Kotlin, but send one to Kotlin, append it, and send the result back.

Extension of the project:

Since there were some roadblocks in this seemingly simple extension, I lay out the steps for anybody interested. If you follow along, you should get the following displayed:

<img src="https://i.stack.imgur.com/7fWdz.jpg" alt="Kotlin <-> Swift">

The text may be stupid, but it tells you, what happens.
The changes in ViewController.swift in the function viewDidAppear are:

```<code>    let swiftMessage: String = "Hello Kotlin, this is Swift!"
    let cStr = swiftMessage.cString(using: String.Encoding.utf8)
    if let retVal = kotlin_wrapper(cStr) {
        let string = String(cString: retVal)
        ...
    }
</code>```

You see the text that Swift sends to Kotlin in the wrapper function (in the end, the resulting 'string' variable will be displayed). One could directly pass the Swift String to the wrapper, but I wanted to highlight that the wrapper will consider the input and output as c-strings. Indeed, the file Kotlin Native-Bridging-Header.h inside the native iOS project now becomes:

```<code>extern const char* kotlin_wrapper(const char* swiftMessage);
</code>```

On it goes to the file Launcher.cpp. Since the original file used a KString as result value of kotlin_main, I tried for some time to convert const char* to KString and pass that to kotlin_main. In the end I found, that it is much simpler to directly transfer the const char* variables to Kotlin, and do the transformation there with the functions that are given to us by Kotlin/Native.

My Launcher.cpp then became more compact than the original. Here is the complete file:

```<code>#include "Memory.h"
#include "Natives.h"
#include "Runtime.h"
#include "KString.h"
#include <stdlib.h>
#include <string>

extern "C" const char* kotlin_main(const char* swiftMessageChar);

extern "C" const char* kotlin_wrapper(const char* swiftMessageChar) {
    RuntimeState* state = InitRuntime();
    if (state == nullptr) {
        return "Failed to initialize the kotlin runtime";
    }
    const char* exitMessage = kotlin_main(swiftMessageChar);
    DeinitRuntime(state);
    return exitMessage;
}
</code>```

You see how the wrapper first starts the Kotlin runtime and then calls the function kotlin_main, which resides in the file kotlin.kt:

```<code>import konan.internal.ExportForCppRuntime
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.cstr
import kotlinx.cinterop.nativeHeap
import kotlinx.cinterop.toKString

@ExportForCppRuntime

fun kotlin_main(cPtr: CPointer<ByteVar>): CPointer<ByteVar> {
    val swiftMessage = cPtr.toKString()
    val kotlinMessage = "Hello Swift, I got your message: '$swiftMessage'."
    val returnPtr = kotlinMessage.cstr.getPointer(nativeHeap)
    return returnPtr
}
</code>```

The pointer is converted to a Kotlin String, and then used in the creation of the kotlinMessage (the example of a data transformation). The result message is then transformed back to a pointer, and passed through the wrapper back to the Swift UIViewController.

Where to go from here?

In principle, one could use this framework without touching the C++ layer again. Just define pack and unpack functions, that pack arbitrary data types into a string and unpack the string to the respective data type on the other side. Such pack and unpack functions have to be written only once per language, and can be reused for different projects, if done sufficiently generic. In practice, I probably would first rewrite the above code to pass binary data, and then write the pack and unpack functions to transform arbitrary data types to and from binary data.

ContentLicense: CC BY-SA 3.0

Body:
Yes, it is possible in a cross-platform project to transfer data between Kotlin and native iOS UI Code by using Kotlin/Native. This allows to have a common code base for the data model based on Kotlin, while e.g. continuing to use native UI code for iOS.

The original proof:

The project https://github.com/justMaku/Kotlin-Native-with-Swift pointed me in the right direction, since it shows the essential steps to do so:

In a Swift UIViewController, it calls a wrapper function that shall receive a string from a Kotlin function. The call is mediated through a C++ layer, which itself starts the Kotlin runtime, passes the request to a Kotlin function, receives the string from it, and passes it back to the Swift UIViewController, which then displays it.

On the technical level, the project contains a script that compiles the Kotlin, C++, and Kotlin/Native part into a static library, which then can be called from the native iOS project.

To get the code to run, I had (after cloning from git) to perform a "git submodule sync" before running "./setup.sh".

To transfer data with a data model based on Kotlin, I would like to have a generic function, that can pass data to Kotlin, modify that data, and return the result back to the native iOS code. As a proof of principle, that such a function can be build, I extended the project to not only receive a string from Kotlin, but send one to Kotlin, append it, and send the result back.

Extension of the project:

Since there were some roadblocks in this seemingly simple extension, I lay out the steps for anybody interested. If you follow along, you should get the following displayed:

The text may be stupid, but it tells you, what happens.
The changes in ViewController.swift in the function viewDidAppear are:

    let swiftMessage: String = "Hello Kotlin, this is Swift!"
    let cStr = swiftMessage.cString(using: String.Encoding.utf8)
    if let retVal = kotlin_wrapper(cStr) {
        let string = String(cString: retVal)
        ...
    }

You see the text that Swift sends to Kotlin in the wrapper function (in the end, the resulting 'string' variable will be displayed). One could directly pass the Swift String to the wrapper, but I wanted to highlight that the wrapper will consider the input and output as c-strings. Indeed, the file Kotlin Native-Bridging-Header.h inside the native iOS project now becomes:

extern const char* kotlin_wrapper(const char* swiftMessage);

On it goes to the file Launcher.cpp. Since the original file used a KString as result value of kotlin_main, I tried for some time to convert const char* to KString and pass that to kotlin_main. In the end I found, that it is much simpler to directly transfer the const char* variables to Kotlin, and do the transformation there with the functions that are given to us by Kotlin/Native.

My Launcher.cpp then became more compact than the original. Here is the complete file:

#include "Memory.h"
#include "Natives.h"
#include "Runtime.h"
#include "KString.h"
#include <stdlib.h>
#include <string>

extern "C" const char* kotlin_main(const char* swiftMessageChar);

extern "C" const char* kotlin_wrapper(const char* swiftMessageChar) {
    RuntimeState* state = InitRuntime();
    if (state == nullptr) {
        return "Failed to initialize the kotlin runtime";
    }
    const char* exitMessage = kotlin_main(swiftMessageChar);
    DeinitRuntime(state);
    return exitMessage;
}

You see how the wrapper first starts the Kotlin runtime and then calls the function kotlin_main, which resides in the file kotlin.kt:

import konan.internal.ExportForCppRuntime
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.cstr
import kotlinx.cinterop.nativeHeap
import kotlinx.cinterop.toKString

@ExportForCppRuntime

fun kotlin_main(cPtr: CPointer<ByteVar>): CPointer<ByteVar> {
    val swiftMessage = cPtr.toKString()
    val kotlinMessage = "Hello Swift, I got your message: '$swiftMessage'."
    val returnPtr = kotlinMessage.cstr.getPointer(nativeHeap)
    return returnPtr
}

The pointer is converted to a Kotlin String, and then used in the creation of the kotlinMessage (the example of a data transformation). The result message is then transformed back to a pointer, and passed through the wrapper back to the Swift UIViewController.

Where to go from here?

In principle, one could use this framework without touching the C++ layer again. Just define pack and unpack functions, that pack arbitrary data types into a string and unpack the string to the respective data type on the other side. Such pack and unpack functions have to be written only once per language, and can be reused for different projects, if done sufficiently generic. In practice, I probably would first rewrite the above code to pass binary data, and then write the pack and unpack functions to transform arbitrary data types to and from binary data.


问:
Spring Boot tomcat threadpool configuration
We are using Spring Boot version - spring-boot-starter-tomcat-1.4.3.RELEASE.

We are trying to find the max-threads configuration for the embedded tomcat, but in vain.

We could not find any server.xml inside the Spring Boot jar file. Neither could we print the max-threads property - which always returns null.

How can I find out the max-threads configured in the embedded tomcat for Spring Boot 1.4.3? How can I set the max-threads?
Does Spring Boot 1.4.3 use NIO?

答:
for configuring that you will change application config in (application.yml or prop)
like this</p>

```<code>server.tomcat.max-threads=12
</code>```

Body:
for configuring that you will change application config in (application.yml or prop)
like this

server.tomcat.max-threads=12


问:
How to set a custom font to the title in toolbar android
I am doing this:

```<code>toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle("hello");
</code>```

I want to set a custom font for the text here in the title "hello". How to do that?

答:
If you are using google fonts (ie. Open Sans) you can add TextView as a child of your Toolbar like this

```<code><android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:fontFamily="@font/open_sans"/>

</android.support.v7.widget.Toolbar>
</code>```

and then just set fontFamily property for your TextView in Attributes menu (More Fonts option at the end of the dropdown list)

```<code>android:fontFamily="@font/open_sans
</code>```

Body:
I am doing this:

toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle("hello");

I want to set a custom font for the text here in the title "hello". How to do that?

Body:
If you are using google fonts (ie. Open Sans) you can add TextView as a child of your Toolbar like this

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:fontFamily="@font/open_sans"/>

</android.support.v7.widget.Toolbar>

and then just set fontFamily property for your TextView in Attributes menu (More Fonts option at the end of the dropdown list)

android:fontFamily="@font/open_sans


问:
Finding two matches with the same string in regex
Is there a way in regex to find a string if it occurs twice in given structures (i.e. like in XML parsing)?
This code obviously does not work as it finds the first tag and then the last closing tag:

```<code>re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
</code>```

So is there a way to tell regex that the third match should be the same as the first?

Full code:

```<code>import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
for match in matches:
    print(match)
</code>```

Result should be all the tags with the contents:

```<code>    [('a1', '\n    <a2>\n        1\n    </a2>\n    <b2>\n        52\n    </b2>\n    <c2>\n        <a3>\n            Abc\n        </a3>\n    </c2>\n'),
     ('a2', '\n        1\n    '),
      ...]
</code>```

Note: I am not looking for a complete xml parsing package. The question is specificly about solving the given problem with regex.

答:
I wouldn't do this because the recursive structures are difficult to parse with regexes. Python's re module doesn't support this. The alternative regex module does. However, I wouldn't do it.

A backreference can only bring you this far:

```<code>import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</\1>', s) # mind the \1
for match in matches:
    print(match)
</code>```

It will give you two matches: 1. the <a1> ... </a1> and <b1> ... </b1>.

Now imagine that some of your tags are having attributes. What if a tag can span more than one line? What about tags that close themselves? What about accidental spaces?

A html / xml parser can deal with all of this.

Body:
Is there a way in regex to find a string if it occurs twice in given structures (i.e. like in XML parsing)?
This code obviously does not work as it finds the first tag and then the last closing tag:

re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)

So is there a way to tell regex that the third match should be the same as the first?

Full code:

import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</(.+)>', s)
for match in matches:
    print(match)

Result should be all the tags with the contents:

    [('a1', '\n    <a2>\n        1\n    </a2>\n    <b2>\n        52\n    </b2>\n    <c2>\n        <a3>\n            Abc\n        </a3>\n    </c2>\n'),
     ('a2', '\n        1\n    '),
      ...]

Note: I am not looking for a complete xml parsing package. The question is specificly about solving the given problem with regex.

Body:
I wouldn't do this because the recursive structures are difficult to parse with regexes. Python's re module doesn't support this. The alternative regex module does. However, I wouldn't do it.

A backreference can only bring you this far:

import re

s = '''<a1>
    <a2>
        1
    </a2>
    <b2>
        52
    </b2>
    <c2>
        <a3>
            Abc
        </a3>
    </c2>
</a1>
<b1>
    21
</b1>'''

matches = re.findall(r'<(.+)>([\s\S]*)</\1>', s) # mind the \1
for match in matches:
    print(match)

It will give you two matches: 1. the <a1> ... </a1> and <b1> ... </b1>.

Now imagine that some of your tags are having attributes. What if a tag can span more than one line? What about tags that close themselves? What about accidental spaces?

A html / xml parser can deal with all of this.


答:
The default value for max-threads is 200. From the tomcat docs

You can set it using the property

```<code>server.tomcat.max-threads=<your value> # Maximum amount of worker threads.
</code>```

From the spring-boot docs

Title: Spring Boot tomcat threadpool configuration

Body:
We are using Spring Boot version - spring-boot-starter-tomcat-1.4.3.RELEASE.

We are trying to find the max-threads configuration for the embedded tomcat, but in vain.

We could not find any server.xml inside the Spring Boot jar file. Neither could we print the max-threads property - which always returns null.

How can I find out the max-threads configured in the embedded tomcat for Spring Boot 1.4.3? How can I set the max-threads?
Does Spring Boot 1.4.3 use NIO?

Body:
The default value for max-threads is 200. From the tomcat docs

You can set it using the property

server.tomcat.max-threads=<your value> # Maximum amount of worker threads.

From the spring-boot docs


问:
how to disable a BUTTON after first click?
This might be a simple question.but,does any one know how to disable a button after clicking it in Odoo? Thanks for all your help.</p>

答:
Most of Odoo module use state for this kind of problem. the general idea of it that you must have a field and the button is displayed based on the value of that field.

Ex:

  # in you model
  bool_field = fields.Boolean('Same text', default=False)
```

<p>In your view:</p>

<pre class="lang-xml prettyprint-override"><code> <button name="some_method"......... attrs="{'invisible': [('bool_field', '=', True)]}" />
 ...
 ...
 ...
 <!-- keep the field invisible because i don't need the user to see
      it, the value of this field is for technical purpuse -->
 <field name="bool_field" invisible="1"/>
</code>```

In your model:

 @api.multi
 def some_method(self):
    # in this method i will make sure to change the value of the
    # field to True so the button is not visible any more for user
    self.bool_field = True
    ...
    ...
    ...
```

So if you all ready have a field that the button change it's value you can use it directly
or create a special field for this purpose.

Body:
Most of Odoo module use state for this kind of problem. the general idea of it that you must have a field and the button is displayed based on the value of that field.

Ex:

  # in you model
  bool_field = fields.Boolean('Same text', default=False)

In your view:

 <button name="some_method"......... attrs="{'invisible': [('bool_field', '=', True)]}" />
 ...
 ...
 ...
 <!-- keep the field invisible because i don't need the user to see
      it, the value of this field is for technical purpuse -->
 <field name="bool_field" invisible="1"/>

In your model:

 @api.multi
 def some_method(self):
    # in this method i will make sure to change the value of the
    # field to True so the button is not visible any more for user
    self.bool_field = True
    ...
    ...
    ...

So if you all ready have a field that the button change it's value you can use it directly
or create a special field for this purpose.


问:
Ordering and binding in for loop r
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

```<code>##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories
</code>```

Hope you guys can help me out!

答:
As you can see in the links, I have made screenshots of my dataframes to give you an illustration of my data.

Main dataframe

Dataset for calculations

Averages as output

Title: Ordering and binding in for loop r

Body:
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories

Hope you guys can help me out!


问:
SQL Server 2012: Select results not equal to string
I have users and roles.  And this is a part of my query:

```<code>(select R.RoleName from [dbo].[aspnet_Roles] as R
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
    where U.UserName = 'User1') <> 'Doctor'
</code>```

But because a user can have multiple roles (in this case User1 is Doctor and Client) I get this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

How I can make it work so the query will return the roles of the users that neither of their roles are Doctor

答:
You are doing it wrong way. Try this</p>

```<code> ; WITH CTE AS
(
    select DISTINCT U.UserName, R.RoleName from [dbo].[aspnet_Roles] as R
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
)
SELECT * FROM CTE
WHERE NOT EXISTS (SELECT 1 FROM CTE CIN WHERE CIN.UserName = CTE.UserName AND CIN.RoleName = 'Doctor')
</code>```

Body:
I have users and roles.  And this is a part of my query:

(select R.RoleName from [dbo].[aspnet_Roles] as R
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
    where U.UserName = 'User1') <> 'Doctor'

But because a user can have multiple roles (in this case User1 is Doctor and Client) I get this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

How I can make it work so the query will return the roles of the users that neither of their roles are Doctor

Body:
You are doing it wrong way. Try this

 ; WITH CTE AS
(
    select DISTINCT U.UserName, R.RoleName from [dbo].[aspnet_Roles] as R
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
)
SELECT * FROM CTE
WHERE NOT EXISTS (SELECT 1 FROM CTE CIN WHERE CIN.UserName = CTE.UserName AND CIN.RoleName = 'Doctor')


问:
Overlay divs on scroll
Instead of scrolling down the page to view a bunch of divs, I would like them to overlay in the same place-- one stacked on top the next -- when you scroll. So, you would scroll down, but the page would not go down. Instead, the next div would overlay the first and so on and so forth. Not sure how to do this? Here is what I have:

UPDATE

```<code>.container {
    width:100%;
    height:100%;
    position:relative;

}

.container1 {
    display:block;
    position:fixed;
    margin-top:690px;
    width:100%;
    height:500px;
    z-index:1;
    background:#333;

  }

.container2 {
    display:block;
    position:absolute;
    margin-top:1190px;
    width:100%;
    height:500px;
    z-index:2;
    background:#F00;
}

<div class="container">

<div class="container1">
info
</div>

<div class="container2">
info
</div>
</div>
</code>```

This adjustment is working, but the bottom div (container1) is not 500px, but set to the size of the screen. I'm sure this is a simple adjustment to the code, but I am stumped.

Thanks for any help!

答:
In order to achieve the parallax effect with CSS only, all you need to do is use the CSS background-attachment property and set it to fixed and also add min-height

```<code>.parallax {
    /* The image used */
    background-image: url("img_parallax.jpg");

    /* Set a specific height */
    min-height: 500px;

    /* Create the parallax scrolling effect */
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
   }
</code>```

Check out this link:

https://www.w3schools.com/howto/tryhow_css_parallax_demo.htm

Title: Overlay divs on scroll

Body:
Instead of scrolling down the page to view a bunch of divs, I would like them to overlay in the same place-- one stacked on top the next -- when you scroll. So, you would scroll down, but the page would not go down. Instead, the next div would overlay the first and so on and so forth. Not sure how to do this? Here is what I have:

UPDATE

.container {
    width:100%;
    height:100%;
    position:relative;

}

.container1 {
    display:block;
    position:fixed;
    margin-top:690px;
    width:100%;
    height:500px;
    z-index:1;
    background:#333;

  }

.container2 {
    display:block;
    position:absolute;
    margin-top:1190px;
    width:100%;
    height:500px;
    z-index:2;
    background:#F00;
}

info

info

This adjustment is working, but the bottom div (container1) is not 500px, but set to the size of the screen. I'm sure this is a simple adjustment to the code, but I am stumped.

Thanks for any help!

Body:
In order to achieve the parallax effect with CSS only, all you need to do is use the CSS background-attachment property and set it to fixed and also add min-height

.parallax {
    /* The image used */
    background-image: url("img_parallax.jpg");

    /* Set a specific height */
    min-height: 500px;

    /* Create the parallax scrolling effect */
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
   }

Check out this link:

https://www.w3schools.com/howto/tryhow_css_parallax_demo.htm

ContentLicense: CC BY-SA 4.0


问:
Right click not working in Excel2013
Right click is not working for me in excel 2013. I am unable to add or delete sheets plus the formatting menu. Please help</p>

答:
All - I've been struggling with this in Excel 2010 ever since I ran some old VBA from a 2003 Excel file.  In that file, the code was written such that all right-clicking was disabled but never turned back on before exiting the file!

I've written a bit of VBA that should fix all command bar issues.  I'd appreciate any feedback on this - it worked well for me and I've only tested it on my system with Excel 2010 (that's my disclaimer).

```<code>Dim i As Integer

For i = 1 To Application.CommandBars.Count

    On Error Resume Next

    With Application.CommandBars(i)
        .Reset
        .Enabled = True
    End With

Next i
</code>```

Title: Right click not working in Excel2013

Body:
All - I've been struggling with this in Excel 2010 ever since I ran some old VBA from a 2003 Excel file.  In that file, the code was written such that all right-clicking was disabled but never turned back on before exiting the file!

I've written a bit of VBA that should fix all command bar issues.  I'd appreciate any feedback on this - it worked well for me and I've only tested it on my system with Excel 2010 (that's my disclaimer).

Dim i As Integer

For i = 1 To Application.CommandBars.Count

    On Error Resume Next

    With Application.CommandBars(i)
        .Reset
        .Enabled = True
    End With

Next i


问:
modify the following with function lambda and filter python2 code into python 3
I need to convert the following python2.7 code into python3.5, while getting errors</p>

```<code> for filename in sorted(glob.glob(self.path + '/test*.bmp'),
                               key=lambda f: int(filter(lambda x: x.isdigit(), f))):

Error:
Traceback (most recent call last):
  File "/Users/ImageSegmentation/preprocess.py", line 53, in get_gland
    key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
  File "/Users/ImageSegmentation/preprocess.py", line 53, in <lambda>
    key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'
</code>```

答:
In Python 2, when passed a string in input, filter  used to return a string, which was convenient.

Now filter returns a filter object, which needs to be iterated upon to get the results.

So you have to use "".join() on the result to force iteration & convert to string.

Also note that lambda x: x.isdigit() is overkill and underperformant, use str.isdigit directly.

Another potential bug in your code is that f is the full path name of the file, so if there are digits in the paths, they'll be taken into account (and would be difficult to figure out), so a proper fix would be:

```<code>int("".join(filter(str.isdigit, os.path.basename(f))))
</code>```

Body:
I need to convert the following python2.7 code into python3.5, while getting errors

 for filename in sorted(glob.glob(self.path + '/test*.bmp'),
                               key=lambda f: int(filter(lambda x: x.isdigit(), f))):

Error:
Traceback (most recent call last):
  File "/Users/ImageSegmentation/preprocess.py", line 53, in get_gland
    key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
  File "/Users/ImageSegmentation/preprocess.py", line 53, in <lambda>
    key=lambda f: int((filter(lambda x: x.isdigit(), f)))):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'

Body:
In Python 2, when passed a string in input, filter  used to return a string, which was convenient.

Now filter returns a filter object, which needs to be iterated upon to get the results.

So you have to use "".join() on the result to force iteration & convert to string.

Also note that lambda x: x.isdigit() is overkill and underperformant, use str.isdigit directly.

Another potential bug in your code is that f is the full path name of the file, so if there are digits in the paths, they'll be taken into account (and would be difficult to figure out), so a proper fix would be:

int("".join(filter(str.isdigit, os.path.basename(f))))


问:
canvas is black after restart or debugg while running
When I restart my App, I mean when I press the Homebutton and start it from the Task window, or when I debug it while it is still runnning the whole screen went black!

This is my MainView:

```<code>package net.kex.toll;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class MainView extends SurfaceView implements SurfaceHolder.Callback{

public GameLoop gameLoop;
public Player player;
private int playerX = 50;
private int playerY = 50;

public MainView(final Context context) {
    super(context);
    getHolder().addCallback(this);
    player = new Player();
    this.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            playerX = playerX + 20;
            playerY = playerY + 20;
            player.play();
            return false;
        }
    }
    );
    setFocusable(true);

}

public void surfaceChanged(SurfaceHolder surfaceHolder, int foramt, int width, int height){

}
public void surfaceDestroyed(SurfaceHolder surfaceHolder){
    boolean retry = true;
    while (true) {
        try {
            gameLoop.setRunning(false);
            gameLoop.join();
        } catch (Exception e) { e.printStackTrace();}
        retry = false;
    }
}
public void surfaceCreated(SurfaceHolder surfaceHolder){
    gameLoop = new GameLoop(getHolder(), this);

    gameLoop.setRunning(true);
    gameLoop.start();
}
public void update(){
    player.update();
}
public void draw(Canvas canvas){
    if(canvas == null) {
        return;
    }
    canvas.drawColor(Color.WHITE);
    player.draw(canvas);
}
}
</code>```

This is my GameLoop:

```<code>package net.kex.toll;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class GameLoop extends Thread {
public static final int MAX_FPS = 30;
private double averageFPS;
private MainView mainView;
private SurfaceHolder surfaceHolder;
private boolean running;
public static Canvas canvas;

public void setRunning(boolean running) {
    this.running = running;
}

public GameLoop(SurfaceHolder surfaceHolder, MainView mainView) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.mainView = mainView;
}

@Override
public void run(){
    long startTime;
    long timeMillis = 1000/MAX_FPS;
    long waitTime;
    long frameCount = 0;
    long totalTime = 0;
    long targetTime = 1000/MAX_FPS;

    while (running) {
        startTime = System.nanoTime();
        canvas = null;
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                this.mainView.update();
                this.mainView.draw(canvas);
            }
        }catch (Exception e){ e.printStackTrace();}
        finally {
            if (canvas != null) {
                try {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }catch (Exception e){ e.printStackTrace();}

            }
        }
        timeMillis = (System.nanoTime() - startTime)/1000000;
        waitTime = targetTime - timeMillis;
        try {
            if (waitTime >= 0){
                this.sleep(waitTime);
            }
        }catch (Exception e){ e.printStackTrace();}

        totalTime += System.nanoTime() - startTime;
        frameCount++;

        if (frameCount == MAX_FPS) {
            averageFPS = 1000/((totalTime/frameCount)/1000000);
            frameCount = 0;
            totalTime = 0;
            Log.i("GameLoop", "averageFPS: " + Double.toString(averageFPS));
        }
    }
}
</code>```

}

I don't know what to do! If you want some other class please tell me and I will send it to you!

Please help I´m sitting here and trying to solve this problem for hours!

答: Repaint the object, it will render it again. For example in onResume add Repaint()</p>

Body:
When I restart my App, I mean when I press the Homebutton and start it from the Task window, or when I debug it while it is still runnning the whole screen went black!

This is my MainView:

package net.kex.toll;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class MainView extends SurfaceView implements SurfaceHolder.Callback{

public GameLoop gameLoop;
public Player player;
private int playerX = 50;
private int playerY = 50;

public MainView(final Context context) {
    super(context);
    getHolder().addCallback(this);
    player = new Player();
    this.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            playerX = playerX + 20;
            playerY = playerY + 20;
            player.play();
            return false;
        }
    }
    );
    setFocusable(true);

}

public void surfaceChanged(SurfaceHolder surfaceHolder, int foramt, int width, int height){

}
public void surfaceDestroyed(SurfaceHolder surfaceHolder){
    boolean retry = true;
    while (true) {
        try {
            gameLoop.setRunning(false);
            gameLoop.join();
        } catch (Exception e) { e.printStackTrace();}
        retry = false;
    }
}
public void surfaceCreated(SurfaceHolder surfaceHolder){
    gameLoop = new GameLoop(getHolder(), this);

    gameLoop.setRunning(true);
    gameLoop.start();
}
public void update(){
    player.update();
}
public void draw(Canvas canvas){
    if(canvas == null) {
        return;
    }
    canvas.drawColor(Color.WHITE);
    player.draw(canvas);
}
}

This is my GameLoop:

package net.kex.toll;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class GameLoop extends Thread {
public static final int MAX_FPS = 30;
private double averageFPS;
private MainView mainView;
private SurfaceHolder surfaceHolder;
private boolean running;
public static Canvas canvas;

public void setRunning(boolean running) {
    this.running = running;
}

public GameLoop(SurfaceHolder surfaceHolder, MainView mainView) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.mainView = mainView;
}

@Override
public void run(){
    long startTime;
    long timeMillis = 1000/MAX_FPS;
    long waitTime;
    long frameCount = 0;
    long totalTime = 0;
    long targetTime = 1000/MAX_FPS;

    while (running) {
        startTime = System.nanoTime();
        canvas = null;
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                this.mainView.update();
                this.mainView.draw(canvas);
            }
        }catch (Exception e){ e.printStackTrace();}
        finally {
            if (canvas != null) {
                try {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }catch (Exception e){ e.printStackTrace();}

            }
        }
        timeMillis = (System.nanoTime() - startTime)/1000000;
        waitTime = targetTime - timeMillis;
        try {
            if (waitTime >= 0){
                this.sleep(waitTime);
            }
        }catch (Exception e){ e.printStackTrace();}

        totalTime += System.nanoTime() - startTime;
        frameCount++;

        if (frameCount == MAX_FPS) {
            averageFPS = 1000/((totalTime/frameCount)/1000000);
            frameCount = 0;
            totalTime = 0;
            Log.i("GameLoop", "averageFPS: " + Double.toString(averageFPS));
        }
    }
}

}

I don't know what to do! If you want some other class please tell me and I will send it to you!

Please help I´m sitting here and trying to solve this problem for hours!


问:
Ajax multiple dropdown return value- php mysql
i had 4 table like this

Table

And then im going to fill this form

Form

the workflow is, when i select Item Type and Treatment, the price should be filled based on the ServicePrice Table, I can get the Price from ServicePrice, but when I check XHR on network, it shows the value of Price but its data just show for 1st time, I mean when the modal opened, it shows the first data, when the option changed, the Price value keep like the 1st time modal open. so I want whenever the Item Type or Treatment changed, I want to make the price box filled dynamically

here's my form

```<code><tr>
    <td>Item Type</td>
    <td>
        <select name="ItemTypeID"  class="form-control"  id="ItemType" >
            <option selected=""></option>
            <?php
            $sql2 = mysql_query("select * from itemtype");
            while($record = mysql_fetch_array($sql2)){
            ?>
                <option value="<?php echo $record['ID']; ?>" title="<?php echo $record['DefaultSpec']; ?>"> <?php echo $record["Name"]; ?> </option>
            <?php } ?>
        </select>
    </td>
</tr>

<tr>
    <td>Treatment</td>
    <td>
        <select name="TreatmentID" class="form-control" id="Treatment">
            <?php
            $sql2 = mysql_query("select * from treatment");
            while($record = mysql_fetch_array($sql2)){
            ?>
                <option value="<?php echo $record['ID']; ?>"> <?php echo $record["Name"]; ?> </option>
            <?php } ?>
        </select>
    </td>
</tr>
</code>```

and then my ajax

```<code>$("#ItemType, #Treatment").change(function(){
    var ItemType = $(this).val();
    var Treatment = $(this).val();
    console.log(Treatment);
    console.log(ItemType);
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "GetPrice.php",
        data: {ItemTypeID: ItemType, TreatmentID: Treatment},
        success: function(result){
        console.log(result);
        $("#Price").val(result);
    });
});
</code>```

my GetPrice.php

```<code><?php include "../Content/connection.php";

$a="SELECT * FROM ServicePrice WHERE ItemtypeID = '".$_POST["ItemTypeID"]."' AND TreatmentID = '".$_POST["TreatmentID"]."'";
$q=mysql_query($a);
while($record=mysql_fetch_array($q)){
    echo $record['Price'];
}
?>
</code>```

EDIT :

im making it like this it give me correct answer but the Price value triggered only if treatment dropdown changed, how can i make it trigger by booth dropdown?

```<code> $("#ItemType").change(function(){
  var ItemType = $(this).val();
$("#Treatment").change(function(){
  var Treatment = $(this).val();
</code>```

答:
the $(this).val() inside the change event handler will not work to get data for both the fields,
instead fetch the data of ItemType and Treatment individually

```<code>$("#ItemType, #Treatment").on('change', function(){
    var ItemType = $("#ItemType").val();
    var Treatment = $("#Treatment").val();

    $.ajax({
        type: "POST",
        url: "GetPrice.php",
        data: {ItemTypeID: ItemType, TreatmentID: Treatment},
        success: function(result){
            $("#Price").val(result);
        }
    });
});
</code>```

Body:
i had 4 table like this

Table

And then im going to fill this form

Form

the workflow is, when i select Item Type and Treatment, the price should be filled based on the ServicePrice Table, I can get the Price from ServicePrice, but when I check XHR on network, it shows the value of Price but its data just show for 1st time, I mean when the modal opened, it shows the first data, when the option changed, the Price value keep like the 1st time modal open. so I want whenever the Item Type or Treatment changed, I want to make the price box filled dynamically

here's my form

    Item Type

        <select name="ItemTypeID"  class="form-control"  id="ItemType" >
            <option selected=""></option>
            <?php
            $sql2 = mysql_query("select * from itemtype");
            while($record = mysql_fetch_array($sql2)){
            ?>
                <option value="<?php echo $record['ID']; ?>" title="<?php echo $record['DefaultSpec']; ?>"> <?php echo $record["Name"]; ?> </option>
            <?php } ?>
        </select>

    Treatment

        <select name="TreatmentID" class="form-control" id="Treatment">
            <?php
            $sql2 = mysql_query("select * from treatment");
            while($record = mysql_fetch_array($sql2)){
            ?>
                <option value="<?php echo $record['ID']; ?>"> <?php echo $record["Name"]; ?> </option>
            <?php } ?>
        </select>

and then my ajax

$("#ItemType, #Treatment").change(function(){
    var ItemType = $(this).val();
    var Treatment = $(this).val();
    console.log(Treatment);
    console.log(ItemType);
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "GetPrice.php",
        data: {ItemTypeID: ItemType, TreatmentID: Treatment},
        success: function(result){
        console.log(result);
        $("#Price").val(result);
    });
});

my GetPrice.php

<?php include "../Content/connection.php";

$a="SELECT * FROM ServicePrice WHERE ItemtypeID = '".$_POST["ItemTypeID"]."' AND TreatmentID = '".$_POST["TreatmentID"]."'";
$q=mysql_query($a);
while($record=mysql_fetch_array($q)){
    echo $record['Price'];
}
?>

EDIT :

im making it like this it give me correct answer but the Price value triggered only if treatment dropdown changed, how can i make it trigger by booth dropdown?

 $("#ItemType").change(function(){
  var ItemType = $(this).val();
$("#Treatment").change(function(){
  var Treatment = $(this).val();

Body:
the $(this).val() inside the change event handler will not work to get data for both the fields,
instead fetch the data of ItemType and Treatment individually

$("#ItemType, #Treatment").on('change', function(){
    var ItemType = $("#ItemType").val();
    var Treatment = $("#Treatment").val();

    $.ajax({
        type: "POST",
        url: "GetPrice.php",
        data: {ItemTypeID: ItemType, TreatmentID: Treatment},
        success: function(result){
            $("#Price").val(result);
        }
    });
});


答:
Try NOT EXISTS:

```<code>WHERE NOT EXISTS (SELECT *
                  FROM [dbo].[aspnet_Roles] Rsq
                       JOIN [dbo].[aspnet_UsersInRoles] URsq ON Rsq.RoleId = URsq.RoleId
                       JOIN [dbo].[aspnet_Users] Usq ON UR.UserId = Usq.Userid
                  WHERE Usq.UserName = [Outside Query User ID Field]
                    AND Rsq.RoleName = 'Doctor')
</code>```

Title: SQL Server 2012: Select results not equal to string

Body:
Try NOT EXISTS:

WHERE NOT EXISTS (SELECT *
                  FROM [dbo].[aspnet_Roles] Rsq
                       JOIN [dbo].[aspnet_UsersInRoles] URsq ON Rsq.RoleId = URsq.RoleId
                       JOIN [dbo].[aspnet_Users] Usq ON UR.UserId = Usq.Userid
                  WHERE Usq.UserName = [Outside Query User ID Field]
                    AND Rsq.RoleName = 'Doctor')


问:
Heroku app crashed because of eslint faulty import
I am developing an app which uses VueJS to display the views and ExpressJS acting as the server.

Works fine locally so far, but after successfully deploying it on Heroku it does not load the app and crashes the dyno.

My folder structure is as such:

project root

client

package.json for client

server

package.json for server

package.json that tells Heroku to install dependences in both folders

This is the package.json that Heroku refers to to build the whole app:

```<code>{
    "name": "my-app",
    "version": "0.1.0",
    "scripts": {
        "postinstall": "npm install --prefix server && npm install --prefix client"
    }
}
</code>```

package.json for the server:

```<code>{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "./src/app.js",
  "scripts": {
      "start": "./node_modules/nodemon/bin/nodemon.js src/app.js --exec 'npm run lint && node'",
  "lint": "./node_modules/.bin/eslint **/*.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
  "body-parser": "^1.18.2",
  "cors": "^2.8.4",
  "eslint": "^4.12.1",
  "express": "^4.16.2",
  "morgan": "^1.9.0",
  "nodemon": "^1.12.5",
  "pg": "^7.4.0",
  "sequelize": "^4.27.0"
},
"devDependencies": {
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-node": "^5.2.1",
    "eslint-plugin-promise": "^3.6.0",
    "eslint-plugin-standard": "^3.0.1"
}
}
</code>```

I checked the logs and the issue stands in the eslint library, which Heroku cannot find in my project. Any idea on how to solve this issue?

```<code>2017-12-08T14:55:35.408127+00:00 app[web.1]: Cannot find module 'eslint-config-standard'
2017-12-08T14:55:35.408145+00:00 app[web.1]: Referenced from: /app/server/.eslintrc.js
2017-12-08T14:55:35.408945+00:00 app[web.1]: Error: Cannot find module 'eslint-config-standard'
2017-12-08T14:55:35.408947+00:00 app[web.1]: Referenced from: /app/server/.eslintrc.js
2017-12-08T14:55:35.408948+00:00 app[web.1]:     at ModuleResolver.resolve (/app/server/node_modules/eslint/lib/util/module-resolver.js:74:19)
2017-12-08T14:55:35.408949+00:00 app[web.1]:     at resolve (/app/server/node_modules/eslint/lib/config/config-file.js:471:25)
2017-12-08T14:55:35.408950+00:00 app[web.1]:     at load (/app/server/node_modules/eslint/lib/config/config-file.js:542:26)
2017-12-08T14:55:35.408951+00:00 app[web.1]:     at configExtends.reduceRight (/app/server/node_modules/eslint/lib/config/config-file.js:421:36)
2017-12-08T14:55:35.408951+00:00 app[web.1]:     at Array.reduceRight (<anonymous>)
2017-12-08T14:55:35.408952+00:00 app[web.1]:     at applyExtends (/app/server/node_modules/eslint/lib/config/config-file.js:403:28)
2017-12-08T14:55:35.408953+00:00 app[web.1]:     at loadFromDisk (/app/server/node_modules/eslint/lib/config/config-file.js:514:22)
2017-12-08T14:55:35.408953+00:00 app[web.1]:     at Object.load (/app/server/node_modules/eslint/lib/config/config-file.js:550:20)
2017-12-08T14:55:35.408954+00:00 app[web.1]:     at Config.getLocalConfigHierarchy (/app/server/node_modules/eslint/lib/config.js:228:44)
2017-12-08T14:55:35.408955+00:00 app[web.1]:     at Config.getConfigHierarchy (/app/server/node_modules/eslint/lib/config.js:180:43)
2017-12-08T14:55:35.464317+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2017-12-08T14:55:35.464681+00:00 app[web.1]: npm ERR! errno 1
2017-12-08T14:55:35.466080+00:00 app[web.1]: npm ERR! server@1.0.0 lint: `eslint **/*.js`
2017-12-08T14:55:35.466205+00:00 app[web.1]: npm ERR! Exit status 1
2017-12-08T14:55:35.466413+00:00 app[web.1]: npm ERR!
2017-12-08T14:55:35.466555+00:00 app[web.1]: npm ERR! Failed at the server@1.0.0 lint script.
2017-12-08T14:55:35.466726+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2017-12-08T14:55:35.491352+00:00 app[web.1]:
2017-12-08T14:55:35.491535+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2017-12-08T14:55:35.491648+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-08T14_55_35_468Z-debug.log
2017-12-08T14:55:35.506231+00:00 app[web.1]: [nodemon] app crashed - waiting for file changes before starting...
2017-12-08T14:56:08.700333+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/status" host=babbelbord.herokuapp.com request_id=f86a8552-14b5-477c-b79d-d575ad30bffa fwd="84.81.81.130" dyno= connect= service= status=503 bytes= protocol=https
</code>```

答:
You seem to be referencing eslint-config-standard from within /app/server/.eslintrc.js, however your package.json doesn't have any dependencies.

You will want to run npm install eslint-config-standard --save which will create a dependency entry in your package.json. Then you should be save to commit the changes and deploy to heroku again.

Because you've not declared your dependency within the package.json, your dyno will not know to install it. I suspect you've simply forgotten to add the --save flag onto your original npm install and so it's only installed into your node_modules folder without making the entry in the package.json.

Body:
I am developing an app which uses VueJS to display the views and ExpressJS acting as the server.

Works fine locally so far, but after successfully deploying it on Heroku it does not load the app and crashes the dyno.

My folder structure is as such:

project root

client

package.json for client

server

package.json for server

package.json that tells Heroku to install dependences in both folders

This is the package.json that Heroku refers to to build the whole app:

{
    "name": "my-app",
    "version": "0.1.0",
    "scripts": {
        "postinstall": "npm install --prefix server && npm install --prefix client"
    }
}

package.json for the server:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "./src/app.js",
  "scripts": {
      "start": "./node_modules/nodemon/bin/nodemon.js src/app.js --exec 'npm run lint && node'",
  "lint": "./node_modules/.bin/eslint **/*.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
  "body-parser": "^1.18.2",
  "cors": "^2.8.4",
  "eslint": "^4.12.1",
  "express": "^4.16.2",
  "morgan": "^1.9.0",
  "nodemon": "^1.12.5",
  "pg": "^7.4.0",
  "sequelize": "^4.27.0"
},
"devDependencies": {
    "eslint-config-standard": "^10.2.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-node": "^5.2.1",
    "eslint-plugin-promise": "^3.6.0",
    "eslint-plugin-standard": "^3.0.1"
}
}

I checked the logs and the issue stands in the eslint library, which Heroku cannot find in my project. Any idea on how to solve this issue?

2017-12-08T14:55:35.408127+00:00 app[web.1]: Cannot find module 'eslint-config-standard'
2017-12-08T14:55:35.408145+00:00 app[web.1]: Referenced from: /app/server/.eslintrc.js
2017-12-08T14:55:35.408945+00:00 app[web.1]: Error: Cannot find module 'eslint-config-standard'
2017-12-08T14:55:35.408947+00:00 app[web.1]: Referenced from: /app/server/.eslintrc.js
2017-12-08T14:55:35.408948+00:00 app[web.1]:     at ModuleResolver.resolve (/app/server/node_modules/eslint/lib/util/module-resolver.js:74:19)
2017-12-08T14:55:35.408949+00:00 app[web.1]:     at resolve (/app/server/node_modules/eslint/lib/config/config-file.js:471:25)
2017-12-08T14:55:35.408950+00:00 app[web.1]:     at load (/app/server/node_modules/eslint/lib/config/config-file.js:542:26)
2017-12-08T14:55:35.408951+00:00 app[web.1]:     at configExtends.reduceRight (/app/server/node_modules/eslint/lib/config/config-file.js:421:36)
2017-12-08T14:55:35.408951+00:00 app[web.1]:     at Array.reduceRight (<anonymous>)
2017-12-08T14:55:35.408952+00:00 app[web.1]:     at applyExtends (/app/server/node_modules/eslint/lib/config/config-file.js:403:28)
2017-12-08T14:55:35.408953+00:00 app[web.1]:     at loadFromDisk (/app/server/node_modules/eslint/lib/config/config-file.js:514:22)
2017-12-08T14:55:35.408953+00:00 app[web.1]:     at Object.load (/app/server/node_modules/eslint/lib/config/config-file.js:550:20)
2017-12-08T14:55:35.408954+00:00 app[web.1]:     at Config.getLocalConfigHierarchy (/app/server/node_modules/eslint/lib/config.js:228:44)
2017-12-08T14:55:35.408955+00:00 app[web.1]:     at Config.getConfigHierarchy (/app/server/node_modules/eslint/lib/config.js:180:43)
2017-12-08T14:55:35.464317+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2017-12-08T14:55:35.464681+00:00 app[web.1]: npm ERR! errno 1
2017-12-08T14:55:35.466080+00:00 app[web.1]: npm ERR! server@1.0.0 lint: `eslint **/*.js`
2017-12-08T14:55:35.466205+00:00 app[web.1]: npm ERR! Exit status 1
2017-12-08T14:55:35.466413+00:00 app[web.1]: npm ERR!
2017-12-08T14:55:35.466555+00:00 app[web.1]: npm ERR! Failed at the server@1.0.0 lint script.
2017-12-08T14:55:35.466726+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2017-12-08T14:55:35.491352+00:00 app[web.1]:
2017-12-08T14:55:35.491535+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2017-12-08T14:55:35.491648+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2017-12-08T14_55_35_468Z-debug.log
2017-12-08T14:55:35.506231+00:00 app[web.1]: [nodemon] app crashed - waiting for file changes before starting...
2017-12-08T14:56:08.700333+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/status" host=babbelbord.herokuapp.com request_id=f86a8552-14b5-477c-b79d-d575ad30bffa fwd="84.81.81.130" dyno= connect= service= status=503 bytes= protocol=https


问:
Xamarin UITest - determine if device is Phone or Tablet for Android?
Is there a way to determine if the Android device I'm running tests on is Phone or Tablet? Found various answers on this topic from an Android development perspective, but I'm just developing tests and looking for some method from Xamarin.UITest that could tell me this. For the iOS there is a built-in method like app.Device.IsPhone, but I can't seem to find something similar for the Android.

Any ideas?

答:
The way that I do it in my tests is check the size of the device see code below:</p>

```<code>public bool DeviceIsTablet()
    {
        var screen = app.Query(x => x.Id("content"));
        var height = screen.FirstOrDefault().Rect.Height;
        var width = screen.FirstOrDefault().Rect.Width;
        if (width < 1600 || height > 1850)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
</code>```

Body:
The way that I do it in my tests is check the size of the device see code below:

public bool DeviceIsTablet()
    {
        var screen = app.Query(x => x.Id("content"));
        var height = screen.FirstOrDefault().Rect.Height;
        var width = screen.FirstOrDefault().Rect.Width;
        if (width < 1600 || height > 1850)
        {
            return false;
        }
        else
        {
            return true;
        }
    }


问:
LINQ - Need to find ID of existing or created record
The query below check to see if a Folder record exist. If not, it creates a new record. Note that the Folder table has a primary key called ID that is an auto incremented. I need to find out what the ID was of the record that was created or already existed.  Need an efficient way of doing it. Currently I do am doing a long about way to find it.  </p>

```<code>// Checks to see if record exist
 var record = (from pl in db.Folders
               where pl.FolderSystem == "OP"
               && pl.OrgID == orgID
               select pl).FirstOrDefault();

// If does not exist create the record
 if (record == null)
 {
   db.Folders.Add(
             new Folders
             {
                 OrgID = orgID,
                 FolderSystem = "OP",
                 CreatedUserID = 1,
                 CreatedDate = DateTime.UtcNow,
              });

             db.SaveChanges();
 }
</code>```

<p>Now I need to find the ID of the record that existed or needed to be created.  Need Folder.ID. Is there a more efficient way to find it. I am open to restructuring the query. </p>

答:
After saveChanges, Id will be updated in your model:</p>

```<code> if (record == null)
 {
     var record =
         new Folders
         {
             OrgID = orgID,
             FolderSystem = "OP",
             CreatedUserID = 1,
             CreatedDate = DateTime.UtcNow,
          });
     db.Folders.Add(record);

     db.SaveChanges();
 }
 record.Id is the id
</code>```

Body:
The query below check to see if a Folder record exist. If not, it creates a new record. Note that the Folder table has a primary key called ID that is an auto incremented. I need to find out what the ID was of the record that was created or already existed.  Need an efficient way of doing it. Currently I do am doing a long about way to find it.

// Checks to see if record exist
 var record = (from pl in db.Folders
               where pl.FolderSystem == "OP"
               && pl.OrgID == orgID
               select pl).FirstOrDefault();

// If does not exist create the record
 if (record == null)
 {
   db.Folders.Add(
             new Folders
             {
                 OrgID = orgID,
                 FolderSystem = "OP",
                 CreatedUserID = 1,
                 CreatedDate = DateTime.UtcNow,
              });

             db.SaveChanges();
 }

Now I need to find the ID of the record that existed or needed to be created.  Need Folder.ID. Is there a more efficient way to find it. I am open to restructuring the query.

Body:
After saveChanges, Id will be updated in your model:

 if (record == null)
 {
     var record =
         new Folders
         {
             OrgID = orgID,
             FolderSystem = "OP",
             CreatedUserID = 1,
             CreatedDate = DateTime.UtcNow,
          });
     db.Folders.Add(record);

     db.SaveChanges();
 }
 record.Id is the id


问:
Django REST Framework doesn't display value in PUT form
Yesterday I posted a question and found a solution to that problem. The solution however caused another issue.

Please take a look at the question, so I don't have to duplicate the contents.

In the Browsable API the value for 'class_name' is not displayed in the PUT form.

The rendered HTML looks like this:

```<code><div class="form-group ">
  <label class="col-sm-2 control-label ">
    Class
  </label>

  <div class="col-sm-10">
    <input name="class_name" class="form-control" type="text">
  </div>
</div>
</code>```

For the other fields it displays the value properly, for example:

```<code><div class="form-group ">
  <label class="col-sm-2 control-label ">
    Order
  </label>

  <div class="col-sm-10">
    <input name="order" class="form-control" value="Carnivora" type="text">
  </div>
</div>
</code>```

Here are screenshots illustrating the problem:

You can see that the value for the key "class" is there. The name of the input element as well the field name in the model is "class_name".

I poked around the source code and found out that the form is rendered in the file renderers.py in the following order:

In the class BrowsableAPIRenderer the method get_context creates the form and calls the method get_rendered_html_form.

The method get_rendered_html_form calls the method render_form_for_serializer.

The method render_form_for_serializer calls the method render of the class HTMLFormRenderer.

But I still don't know where to interfere and what should I change.

Also I tried to implement the method to_internal_value in the serializer, but this is only for the deserialization and has nothing to do with the form rendering.

Does anyone have an idea where the problem lies and what could be done?

UPDATE

I have created GitHub repo with the code. You can clone it or fork it and try to help me.

Many thanks!

答:
I worked out another way which seemed to be working fine for me. This was to define a class field for the serializer outside the class:

```<code>class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Species
        fields = (
            'url', 'id', 'canonical_name', 'slug',  'species', 'genus',
            'subfamily', 'family', 'order','class', 'phylum',
            'ncbi_id', 'ncbi_taxonomy',
        )
        read_only_fields = ('slug',)
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name")
</code>```

After that both Raw Data and HTML Form look fine:

Body:
Yesterday I posted a question and found a solution to that problem. The solution however caused another issue.

Please take a look at the question, so I don't have to duplicate the contents.

In the Browsable API the value for 'class_name' is not displayed in the PUT form.

The rendered HTML looks like this:

    Class

    <input name="class_name" class="form-control" type="text">

For the other fields it displays the value properly, for example:

    Order

    <input name="order" class="form-control" value="Carnivora" type="text">

Here are screenshots illustrating the problem:

You can see that the value for the key "class" is there. The name of the input element as well the field name in the model is "class_name".

I poked around the source code and found out that the form is rendered in the file renderers.py in the following order:

In the class BrowsableAPIRenderer the method get_context creates the form and calls the method get_rendered_html_form.

The method get_rendered_html_form calls the method render_form_for_serializer.

The method render_form_for_serializer calls the method render of the class HTMLFormRenderer.

But I still don't know where to interfere and what should I change.

Also I tried to implement the method to_internal_value in the serializer, but this is only for the deserialization and has nothing to do with the form rendering.

Does anyone have an idea where the problem lies and what could be done?

UPDATE

I have created GitHub repo with the code. You can clone it or fork it and try to help me.

Many thanks!

Body:
I worked out another way which seemed to be working fine for me. This was to define a class field for the serializer outside the class:

class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Species
        fields = (
            'url', 'id', 'canonical_name', 'slug',  'species', 'genus',
            'subfamily', 'family', 'order','class', 'phylum',
            'ncbi_id', 'ncbi_taxonomy',
        )
        read_only_fields = ('slug',)
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name")

After that both Raw Data and HTML Form look fine:


问:
Contact phone numbers Lync SDK 2013
Hello                                                                               I'm using Lync SDK 2013, to display number phones from contact in ListBox, and use the Items (phone number) to call this number by my API.                                So i did a WPF application, that contains just a ListBox, and 2 buttons (Call - Hang up). My apllication is added as custom command in Lync, in RightClick in the contact. and it doesn't have any Lync Controls. So what i want to do is: if i Right Click on the contact, my application launches and gives me the number phone List in the ListBox.                                                                I did it with a WPF that contains the controls: ContactSearchInputBox (to search a contact) and ContactSearchResultList and it works very Well, I don't know how to do it without controls.
Any One Can Help Me !!!! :(</p>

答:
```<code>public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; ;
            try
            {
                string argsParam = "Contacts=";

                if (e.Args.Length > 1)
                {
                    if (e.Args[2].Contains(argsParam))
                    {
                        var contacts_sip_uri = e.Args[2].Split('<', '>')[1];
                        Params.contacts = contacts_sip_uri;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Reading Startup Arguments Error - " + ex.Message);
            }

        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string message = e.Exception.Message;

            if (e.Exception.InnerException != null)
            {
                message += string.Format("{0}Inner Exception: {1}", Environment.NewLine, e.Exception.InnerException.Message);
            }
            MessageBox.Show(message, "Unhandled Exception", MessageBoxButton.OK, MessageBoxImage.Error);
        }

    }
</code>```

Params is a public static class that contains just contact as public static string contacts { get; set; }

```<code>public static class ParamContact
    {
        public static string contacts { get; set; }
    }
</code>```

Title: Contact phone numbers Lync SDK 2013

Body:
public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; ;
            try
            {
                string argsParam = "Contacts=";

                if (e.Args.Length > 1)
                {
                    if (e.Args[2].Contains(argsParam))
                    {
                        var contacts_sip_uri = e.Args[2].Split('<', '>')[1];
                        Params.contacts = contacts_sip_uri;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Reading Startup Arguments Error - " + ex.Message);
            }

        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string message = e.Exception.Message;

            if (e.Exception.InnerException != null)
            {
                message += string.Format("{0}Inner Exception: {1}", Environment.NewLine, e.Exception.InnerException.Message);
            }
            MessageBox.Show(message, "Unhandled Exception", MessageBoxButton.OK, MessageBoxImage.Error);
        }

    }

Params is a public static class that contains just contact as public static string contacts { get; set; }

public static class ParamContact
    {
        public static string contacts { get; set; }
    }


问:
gitchangelog problems with release versions
I am using gitchangelog as indicated here with the reference configuration file unchanged.

I have tagged one commit with v1.0.2:

```<code>0d34763 new: added generic 400 bad request for typeerrors when creating input_data
</code>```

in addition to having one commit named as follows:

```<code>5f3d5b4 new: Added new changelog feature (1.0.1)
</code>```

The output of

```<code>gitchangelog
</code>```

nevertheless gives me

```<code>Changelog
=========

(unreleased)
------------

New
~~~
- Added generic 400 bad request for typeerrors when creating input_data.
  [user]
- Added new changelog feature (1.0.1) [user]
</code>```

Does anyone know how I get

```<code>Changelog
=========

1.0.2 (2011-04-07)
------------------

New
~~~
- Added generic 400 bad request for typeerrors when creating input_data.
  [user]

1.0.1 (2011-04-03)
------------------

New
~~~
- Added new changelog feature (1.0.1) [user]
</code>```

Instead of always (unreleased) ?

Even just one commit to be shown in gitchangelog as a release would be great.

I would really like to know how, as gitchangelog in combination with sphinx is wonderful for documentation.

Thanks for any help.

答:
Ok solved this one. Readme is a bit confusing. Tags have to be added to the commit in the format which will be recognised here:

and the version not only written into the commit message. Not obvious from the readme.

Attention: how you write your tag should match configuration in .rc file so it gets picked up by the regexp here: https://github.com/vaab/gitchangelog/blob/master/src/gitchangelog/gitchangelog.rc.reference#L153

Body:
I am using gitchangelog as indicated here with the reference configuration file unchanged.

I have tagged one commit with v1.0.2:

0d34763 new: added generic 400 bad request for typeerrors when creating input_data

in addition to having one commit named as follows:

5f3d5b4 new: Added new changelog feature (1.0.1)

The output of

gitchangelog

nevertheless gives me

Changelog
=========

(unreleased)
------------

New
~~~
- Added generic 400 bad request for typeerrors when creating input_data.
  [user]
- Added new changelog feature (1.0.1) [user]

Does anyone know how I get

Changelog
=========

1.0.2 (2011-04-07)
------------------

New
~~~
- Added generic 400 bad request for typeerrors when creating input_data.
  [user]

1.0.1 (2011-04-03)
------------------

New
~~~
- Added new changelog feature (1.0.1) [user]

Instead of always (unreleased) ?

Even just one commit to be shown in gitchangelog as a release would be great.

I would really like to know how, as gitchangelog in combination with sphinx is wonderful for documentation.

Thanks for any help.


问:
SQL Server: convert an int value into a time value
In a SQL Server query, I want to convert an int into a time.

The int is representing hours and minutes (hhmm).

For example:

```<code>1945 --> 19:45
30 --> 00:30
1 --> 00:01
</code>```

This query, after modification with your solution, should return true, true, true.

```<code>declare @int1 int = 0
declare @int2 int = 35
declare @int3 int = 1810

select
    @int1 = '00:00', @int2 = '00:35', @int3 = '18:10'
</code>```

答:
```<code>declare @int1 int = 0
declare @int2 int = 35
declare @int3 int = 1805

declare @my_integer_value int

set @my_integer_value = @int1 -- Change to @int2 or @int3 as required.

select convert(char(8),convert
    (DATETIME,cast(@my_integer_value/100 as varchar(2))+':'+cast( @my_integer_value % 100 as varchar(2))+':00'
    ,108),108)
</code>```

Body:
In a SQL Server query, I want to convert an int into a time.

The int is representing hours and minutes (hhmm).

For example:

1945 --> 19:45
30 --> 00:30
1 --> 00:01

This query, after modification with your solution, should return true, true, true.

declare @int1 int = 0
declare @int2 int = 35
declare @int3 int = 1810

select
    @int1 = '00:00', @int2 = '00:35', @int3 = '18:10'


问:
SQL query to get value from referenced table
I have two tables called mg_product and mg_product_user_property.
In mg_product there are 3 columns: id, title, price as

In mg_product_user_property table product_id corresponds with id column in mg_product table.

So my goal is to get the value of property_id of "15", which in the picture above will be "Mediatek".

This is my SQL:

```<code>$sql = "SELECT *
            FROM mg_product AS products
            INNER JOIN mg_product_user_property AS properties
            ON products.id = properties.product_id
            WHERE title LIKE '%$search%')";`
</code>```

PHP:

```<code>$resultSet = DB::query($sql);

if ($resultSet->num_rows > 0) {
    while ($rows = $resultSet->fetch_assoc()) {
        $title = $rows['title'];
        $price = $rows['price'];
    }
} else {
    $output = "No results";
}
</code>```

Now I need to assign to a php variable the value of property_id=15 so I will be able to print "Mediatek" on my website. How can I achieve that? Sorry for my English.

答:
You are pretty close to what you want, but a couple things are going to either be a mess, or unwanted. So, since there are different ways one can go with this, I will only present a very stripped example (and am INTENTIONALLY leaving out a bunch of code here).

You may not want to do a JOIN like that in the initial search, as for each property, it will also return another of the same product. So looping through that will result in dozens of the same product.

However, if _ALL_YOU_WANT_ is to show the Product Title, Price, and Property 15... you can reduce some headwork with a simpler query:

```<code>SELECT p.title, p.price, pr.value
FROM mg_product AS p
     LEFT JOIN mg_product_user_property AS pr
         ON p.id = pr.product_id AND pr.property_id = 15
WHERE p.title LIKE '%$search%'
</code>```

The LEFT JOIN means if the property doesn't exist, it will still return the product. But with an empty property value. And this should not return dozens of the same product for every other property in the table.

--

The OTHER way you could go about doing it, using the SQL query you already have (and the dozens of results of the same product it will return), you can alter your php loop like so:

```<code>$found_products = array();
while ($row = $resultSet->fetch_assoc()) {
    if ($row['property_id'] == 15) {
        $found_products[$row['product_id']] = array(
                'title' => $row['title'],
                'price' => $row['price'],
                'prop'  => $row['value']
            );
   }
}
// now you have a clean array of found products that have the property
</code>```

--

Also I am forced to point out that you should use a prepared statement here, replacing inserting $search directly into the code. But showing you all of how to do that is beyond the scope of this question/answer.

Body:
I have two tables called mg_product and mg_product_user_property.
In mg_product there are 3 columns: id, title, price as

In mg_product_user_property table product_id corresponds with id column in mg_product table.

So my goal is to get the value of property_id of "15", which in the picture above will be "Mediatek".

This is my SQL:

$sql = "SELECT *
            FROM mg_product AS products
            INNER JOIN mg_product_user_property AS properties
            ON products.id = properties.product_id
            WHERE title LIKE '%$search%')";`

PHP:

$resultSet = DB::query($sql);

if ($resultSet->num_rows > 0) {
    while ($rows = $resultSet->fetch_assoc()) {
        $title = $rows['title'];
        $price = $rows['price'];
    }
} else {
    $output = "No results";
}

Now I need to assign to a php variable the value of property_id=15 so I will be able to print "Mediatek" on my website. How can I achieve that? Sorry for my English.

Body:
You are pretty close to what you want, but a couple things are going to either be a mess, or unwanted. So, since there are different ways one can go with this, I will only present a very stripped example (and am INTENTIONALLY leaving out a bunch of code here).

You may not want to do a JOIN like that in the initial search, as for each property, it will also return another of the same product. So looping through that will result in dozens of the same product.

However, if _ALL_YOU_WANT_ is to show the Product Title, Price, and Property 15... you can reduce some headwork with a simpler query:

SELECT p.title, p.price, pr.value
FROM mg_product AS p
     LEFT JOIN mg_product_user_property AS pr
         ON p.id = pr.product_id AND pr.property_id = 15
WHERE p.title LIKE '%$search%'

The LEFT JOIN means if the property doesn't exist, it will still return the product. But with an empty property value. And this should not return dozens of the same product for every other property in the table.

--

The OTHER way you could go about doing it, using the SQL query you already have (and the dozens of results of the same product it will return), you can alter your php loop like so:

$found_products = array();
while ($row = $resultSet->fetch_assoc()) {
    if ($row['property_id'] == 15) {
        $found_products[$row['product_id']] = array(
                'title' => $row['title'],
                'price' => $row['price'],
                'prop'  => $row['value']
            );
   }
}
// now you have a clean array of found products that have the property

--

Also I am forced to point out that you should use a prepared statement here, replacing inserting $search directly into the code. But showing you all of how to do that is beyond the scope of this question/answer.


问:
powershell - struggling to reference DLL that is not in GAC
I'm trying (and failing) to load a DLL (not in GAC) into powershell.

The DLL is part of the Microsoft.Diagnostics.Runtime (ClrMD) Nuget Package
See the full documentation for Microsoft.Diagnostics.Runtime.

The reason why i cant get it into GAC is because the DLL wasn't created with a strongname (that's what gacutil says)

So i've tried all of the options below.. but can't make it work.. wondering if anyone has any tricks:

```<code>$dllpath = somepath\Microsoft.Diagnostics.Runtime.0.9.170809.03\lib\net40\Microsoft.Diagnostics.Runtime.dll"

#LoadFile (this shouldnt work according to method documentation,.. it's just for inspection)
 [System.Reflection.Assembly]::LoadFile($dllpath)

#LoadFrom
 [System.Reflection.Assembly]::LoadFrom($dllpath)

#LoadwithPartialName .. this is deprecated
 [reflection.assembly]::LoadWithPartialName( "Microsoft.Diagnostics.Runtime")

# add-type
 add-type -path $dllpath
</code>```

and also

```<code>$dllname = "Microsoft.Diagnostics.Runtime, Version=0.8.31.1, Culture=neutral, PublicKeyToken=null"
[System.Reflection.Assembly]::Load($dllname)
</code>```

the dllname i got using:

```<code>$dllpath = "somepath\Microsoft.Diagnostics.Runtime.0.9.170809.03\lib\net40\Microsoft.Diagnostics.Runtime.dll"
$dllname = [System.Reflection.AssemblyName]::GetAssemblyName($dllpath).Fullname
</code>```

Anyway.... in all of the cases above i can see that the DLL got loaded into the current appdomain within my session:

```<code>[System.AppDomain]::CurrentDomain.GetAssemblies() | where-object -Filterscript {$_.Fullname -like "*Diagnostics*"}
</code>```

but then when i try to reference it says "type not available"

e.g.

This should work.. also when i type the double-colons after it intellisense should spit out properties/methods
But it fails with "type not found"

```<code>[Microsoft.Diagnostics.Runtime]
</code>```

This should definitely work. afaik this is a static method
first variable is processID, second variable is timeout (seconds)
But it fails with "type not found"

```<code>[Microsoft.Diagnostics.Runtime]::DataTarget.AttachToProcess(7984,5000)
</code>```

It will obviously work with C# but i dont really want to learn that right now as it would delay me while i get my head around it... but maybe the necessary step...

答:
To expand on my comment, create a file:

MyModule.psd1

```<code>@{
    RequiredAssemblies = @('bin\lib.dll','bin\lib2.dll')
 }
</code>```

Your folder structure should look like so:

```<code>C:.
|---MyModule
    |---MyModule.psd1
    |---bin
        |---lib.dll
        |---lib2.dll
</code>```

Now utilize Import-Module -Name 'C:\MyModule' to load your dlls.

Body:
I'm trying (and failing) to load a DLL (not in GAC) into powershell.

The DLL is part of the Microsoft.Diagnostics.Runtime (ClrMD) Nuget Package
See the full documentation for Microsoft.Diagnostics.Runtime.

The reason why i cant get it into GAC is because the DLL wasn't created with a strongname (that's what gacutil says)

So i've tried all of the options below.. but can't make it work.. wondering if anyone has any tricks:

$dllpath = somepath\Microsoft.Diagnostics.Runtime.0.9.170809.03\lib\net40\Microsoft.Diagnostics.Runtime.dll"

#LoadFile (this shouldnt work according to method documentation,.. it's just for inspection)
 [System.Reflection.Assembly]::LoadFile($dllpath)

#LoadFrom
 [System.Reflection.Assembly]::LoadFrom($dllpath)

#LoadwithPartialName .. this is deprecated
 [reflection.assembly]::LoadWithPartialName( "Microsoft.Diagnostics.Runtime")

# add-type
 add-type -path $dllpath

and also

$dllname = "Microsoft.Diagnostics.Runtime, Version=0.8.31.1, Culture=neutral, PublicKeyToken=null"
[System.Reflection.Assembly]::Load($dllname)

the dllname i got using:

$dllpath = "somepath\Microsoft.Diagnostics.Runtime.0.9.170809.03\lib\net40\Microsoft.Diagnostics.Runtime.dll"
$dllname = [System.Reflection.AssemblyName]::GetAssemblyName($dllpath).Fullname

Anyway.... in all of the cases above i can see that the DLL got loaded into the current appdomain within my session:

[System.AppDomain]::CurrentDomain.GetAssemblies() | where-object -Filterscript {$_.Fullname -like "*Diagnostics*"}

but then when i try to reference it says "type not available"

e.g.

This should work.. also when i type the double-colons after it intellisense should spit out properties/methods
But it fails with "type not found"

[Microsoft.Diagnostics.Runtime]

This should definitely work. afaik this is a static method
first variable is processID, second variable is timeout (seconds)
But it fails with "type not found"

[Microsoft.Diagnostics.Runtime]::DataTarget.AttachToProcess(7984,5000)

It will obviously work with C# but i dont really want to learn that right now as it would delay me while i get my head around it... but maybe the necessary step...

Body:
To expand on my comment, create a file:

MyModule.psd1

@{
    RequiredAssemblies = @('bin\lib.dll','bin\lib2.dll')
 }

Your folder structure should look like so:

C:.
|---MyModule
    |---MyModule.psd1
    |---bin
        |---lib.dll
        |---lib2.dll

Now utilize Import-Module -Name 'C:\MyModule' to load your dlls.