问:
Python GUI tkinter Scientific Calculator
"Why the sin is not working it is giving me a syntax error?
I am coding a scientific calculator in python 3.6

```<code>from tkinter import *
from tkinter import ttk
from math import*

class Calculator:
    calc_value = 0.0
    div_trigger = False
    mult_trigger = False
    add_trigger = False
    sub_trigger = False
    asin_trigger = False

    def button_press(self, value):
        entry_val = self.number_entry.get()
        entry_val += value
        self.number_entry.delete(0, "end")
        self.number_entry.insert(0, entry_val)

    def isfloat(self, str_val):
        try:
            float(str_val)
            return True
        except ValueError:
            return False

    def math_button_press(self, value):
        if self.isfloat(str(self.number_entry.get())):
            self.add_trigger = False
            self.sub_trigger = False
            self.mult_trigger = False
            self.div_trigger = False
            self.asin_trigger = False
            self.calc_value = float(self.entry_value.get())
            if value == "/":
                print("/ Pressed")
                self.div_trigger = True
            elif value == "*":
                print("* Pressed")
                self.mult_trigger = True
            elif value == "+":
                print("+ Pressed")
                self.add_trigger = True
            elif value == "sin":
                print("sin Pressed")
                self.asin_trigger = True
            else:
                print("- Pressed")
                self.sub_trigger = True
            self.number_entry.delete(0, "end")

    def equal_button_press(self):
        if self.add_trigger or self.sub_trigger or self.mult_trigger or self.div_trigger or self.asin_trigger:

            if self.add_trigger:
                solution = self.calc_value + float(self.entry_value.get())
            elif self.sub_trigger:
                solution = self.calc_value - float(self.entry_value.get())
            elif self.mult_trigger:
                solution = self.calc_value * float(self.entry_value.get())
            elif self.asin_trigger:
                solution = self.calc_value sin float(self.entry_value.get())
            else:
                solution = self.calc_value / float(self.entry_value.get())

            print(self.calc_value, " ", float(self.entry_value.get()),
                                            " ", solution)

            #
            self.number_entry.delete(0, "end")

            self.number_entry.insert(0, solution)

    def __init__(self, root):
        self.entry_value = StringVar(root, value="")
        root.title("Calculator")
        root.geometry("860x440")
        root.resizable(width=False, height=False)
        style = ttk.Style()
        style.configure("TButton",
                        font="Serif 15",
                        padding=10)

        style.configure("TEntry",
                        font="Serif 18",
                        padding=10)

        # Create the text entry box
        self.number_entry = ttk.Entry(root,
                        textvariable=self.entry_value, width=50)
        self.number_entry.grid(row=0, columnspan=4)

        # ----- 1st Row -----

        self.button7 = ttk.Button(root, text="7", command=lambda: self.button_press('7')).grid(row=1, column=0)

        self.button8 = ttk.Button(root, text="8", command=lambda: self.button_press('8')).grid(row=1, column=1)

        self.button9 = ttk.Button(root, text="9", command=lambda: self.button_press('9')).grid(row=1, column=2)

        self.button_div = ttk.Button(root, text="/", command=lambda: self.math_button_press('/')).grid(row=1, column=3)

        # ----- 2nd Row -----

        self.button4 = ttk.Button(root, text="4", command=lambda: self.button_press('4')).grid(row=2, column=0)

        self.button5 = ttk.Button(root, text="5", command=lambda: self.button_press('5')).grid(row=2, column=1)

        self.button6 = ttk.Button(root, text="6", command=lambda: self.button_press('6')).grid(row=2, column=2)

        self.button_mult = ttk.Button(root, text="*", command=lambda: self.math_button_press('*')).grid(row=2, column=3)

        # ----- 3rd Row -----

        self.button1 = ttk.Button(root, text="1", command=lambda: self.button_press('1')).grid(row=3, column=0)

        self.button2 = ttk.Button(root, text="2", command=lambda: self.button_press('2')).grid(row=3, column=1)

        self.button3 = ttk.Button(root, text="3", command=lambda: self.button_press('3')).grid(row=3, column=2)

        self.button_add = ttk.Button(root, text="+", command=lambda: self.math_button_press('+')).grid(row=3, column=3)

        # ----- 4th Row -----

        self.button_clear = ttk.Button(root, text="AC", command=lambda: self.button_press('AC')).grid(row=4, column=0)

        self.button0 = ttk.Button(root, text="0", command=lambda: self.button_press('0')).grid(row=4, column=1)

        self.button_equal = ttk.Button(root, text="=", command=lambda: self.equal_button_press()).grid(row=4, column=2)

        self.button_sub = ttk.Button(root, text="-", command=lambda: self.math_button_press('-')).grid(row=4, column=3)

        #------- 5th Row -------
        self.button_asin = ttk.Button(root, text="sin", command=lambda: self.math_button_press('sin')).grid(row=5, column=0)

root = Tk()

calc = Calculator(root)

root.mainloop()
</code>```

答:
In your equal_button_press function, write:

```<code>elif self.asin_trigger:
    solution = sin(float(self.calc_value))   # the sine of x is given by sin(x)
</code>```

and then:

```<code># remove float() to prevent crashing when the Entry box is empty
print(self.calc_value, " ", self.entry_value.get(), " ", solution)
</code>```

Body:
"Why the sin is not working it is giving me a syntax error?
I am coding a scientific calculator in python 3.6

from tkinter import *
from tkinter import ttk
from math import*

class Calculator:
    calc_value = 0.0
    div_trigger = False
    mult_trigger = False
    add_trigger = False
    sub_trigger = False
    asin_trigger = False

    def button_press(self, value):
        entry_val = self.number_entry.get()
        entry_val += value
        self.number_entry.delete(0, "end")
        self.number_entry.insert(0, entry_val)

    def isfloat(self, str_val):
        try:
            float(str_val)
            return True
        except ValueError:
            return False

    def math_button_press(self, value):
        if self.isfloat(str(self.number_entry.get())):
            self.add_trigger = False
            self.sub_trigger = False
            self.mult_trigger = False
            self.div_trigger = False
            self.asin_trigger = False
            self.calc_value = float(self.entry_value.get())
            if value == "/":
                print("/ Pressed")
                self.div_trigger = True
            elif value == "*":
                print("* Pressed")
                self.mult_trigger = True
            elif value == "+":
                print("+ Pressed")
                self.add_trigger = True
            elif value == "sin":
                print("sin Pressed")
                self.asin_trigger = True
            else:
                print("- Pressed")
                self.sub_trigger = True
            self.number_entry.delete(0, "end")

    def equal_button_press(self):
        if self.add_trigger or self.sub_trigger or self.mult_trigger or self.div_trigger or self.asin_trigger:

            if self.add_trigger:
                solution = self.calc_value + float(self.entry_value.get())
            elif self.sub_trigger:
                solution = self.calc_value - float(self.entry_value.get())
            elif self.mult_trigger:
                solution = self.calc_value * float(self.entry_value.get())
            elif self.asin_trigger:
                solution = self.calc_value sin float(self.entry_value.get())
            else:
                solution = self.calc_value / float(self.entry_value.get())

            print(self.calc_value, " ", float(self.entry_value.get()),
                                            " ", solution)

            #
            self.number_entry.delete(0, "end")

            self.number_entry.insert(0, solution)

    def __init__(self, root):
        self.entry_value = StringVar(root, value="")
        root.title("Calculator")
        root.geometry("860x440")
        root.resizable(width=False, height=False)
        style = ttk.Style()
        style.configure("TButton",
                        font="Serif 15",
                        padding=10)

        style.configure("TEntry",
                        font="Serif 18",
                        padding=10)

        # Create the text entry box
        self.number_entry = ttk.Entry(root,
                        textvariable=self.entry_value, width=50)
        self.number_entry.grid(row=0, columnspan=4)

        # ----- 1st Row -----

        self.button7 = ttk.Button(root, text="7", command=lambda: self.button_press('7')).grid(row=1, column=0)

        self.button8 = ttk.Button(root, text="8", command=lambda: self.button_press('8')).grid(row=1, column=1)

        self.button9 = ttk.Button(root, text="9", command=lambda: self.button_press('9')).grid(row=1, column=2)

        self.button_div = ttk.Button(root, text="/", command=lambda: self.math_button_press('/')).grid(row=1, column=3)

        # ----- 2nd Row -----

        self.button4 = ttk.Button(root, text="4", command=lambda: self.button_press('4')).grid(row=2, column=0)

        self.button5 = ttk.Button(root, text="5", command=lambda: self.button_press('5')).grid(row=2, column=1)

        self.button6 = ttk.Button(root, text="6", command=lambda: self.button_press('6')).grid(row=2, column=2)

        self.button_mult = ttk.Button(root, text="*", command=lambda: self.math_button_press('*')).grid(row=2, column=3)

        # ----- 3rd Row -----

        self.button1 = ttk.Button(root, text="1", command=lambda: self.button_press('1')).grid(row=3, column=0)

        self.button2 = ttk.Button(root, text="2", command=lambda: self.button_press('2')).grid(row=3, column=1)

        self.button3 = ttk.Button(root, text="3", command=lambda: self.button_press('3')).grid(row=3, column=2)

        self.button_add = ttk.Button(root, text="+", command=lambda: self.math_button_press('+')).grid(row=3, column=3)

        # ----- 4th Row -----

        self.button_clear = ttk.Button(root, text="AC", command=lambda: self.button_press('AC')).grid(row=4, column=0)

        self.button0 = ttk.Button(root, text="0", command=lambda: self.button_press('0')).grid(row=4, column=1)

        self.button_equal = ttk.Button(root, text="=", command=lambda: self.equal_button_press()).grid(row=4, column=2)

        self.button_sub = ttk.Button(root, text="-", command=lambda: self.math_button_press('-')).grid(row=4, column=3)

        #------- 5th Row -------
        self.button_asin = ttk.Button(root, text="sin", command=lambda: self.math_button_press('sin')).grid(row=5, column=0)

root = Tk()

calc = Calculator(root)

root.mainloop()

Body:
In your equal_button_press function, write:

elif self.asin_trigger:
    solution = sin(float(self.calc_value))   # the sine of x is given by sin(x)

and then:

# remove float() to prevent crashing when the Entry box is empty
print(self.calc_value, " ", self.entry_value.get(), " ", solution)


来源: stackexchange

问:
Save file info that already uploaded with Meteor files
I am using https://github.com/VeliovGroup/Meteor-Files, This package provide a collection of uploaded files via Meteor-Files.

How can I insert a document about the file that is already uploaded and not via Meteor-Files? I want to use Meteor-Files to save file info only not uploading. Because I need to get a generated download link for the file. This is provided by Meteor-Files.

Anyone can help me guide how to solve this problem?

答: I used addFile() function provided by FilesCollection class. </p>

ContentLicense: CC BY-SA 3.0


问:
How to cancel the binding of option key in OSX?
I know that OXS bind special keys on option key, such as option+y=¥,option+t=þ... But now, I want to cancel all these bindings, and use option+character as the shortcuts in JetBrains IDEs and other apps.

I have searched for hours and still haven't found a useful way.Can anyone share a tool or the correct way?I used the way to add Library/KeyBindings/DefaultKeyBinding.dict file, but it only canceled some key-bindings, not work for all.

It is my DefaultKeyBinding.dict file below :

```<code>{
"~d" = "deleteWordForward:";
"^w" = "deleteWordBackward:";
"~f" = "moveWordForward:";
"~b" = "moveWordBackward:";
"~u" = "pageUp:";
}
</code>```

Now ,option+f/b can used as my jetbrains IDEs shortcut,but option+u still print special character.

答: I have found a way: if I select Unicode Hex Input as my input source from System preferences->keyBoard->Input Sources, all bindings now disappeared!

Body:
I know that OXS bind special keys on option key, such as option+y=¥,option+t=þ... But now, I want to cancel all these bindings, and use option+character as the shortcuts in JetBrains IDEs and other apps.

I have searched for hours and still haven't found a useful way.Can anyone share a tool or the correct way?I used the way to add Library/KeyBindings/DefaultKeyBinding.dict file, but it only canceled some key-bindings, not work for all.

It is my DefaultKeyBinding.dict file below :

{
"~d" = "deleteWordForward:";
"^w" = "deleteWordBackward:";
"~f" = "moveWordForward:";
"~b" = "moveWordBackward:";
"~u" = "pageUp:";
}

Now ,option+f/b can used as my jetbrains IDEs shortcut,but option+u still print special character.


问:
can't build android project it shows error
project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

App Gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

答:
write these gradles..</p>

```<code>compile 'com.android.support:appcompat-v7:25.0.2'
compile 'com.android.support:design:25.0.2'
classpath 'com.android.tools.build:gradle:2.2.3'
</code>```

Body:
project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

Body:
write these gradles..

compile 'com.android.support:appcompat-v7:25.0.2'
compile 'com.android.support:design:25.0.2'
classpath 'com.android.tools.build:gradle:2.2.3'


问:
Octave - Variable point symbol in plot
I'm plotting two vectors against one another.  I would like to vary the symbol used to plot each point based on the corresponding value in a third vector.

In other words, if I'm plotting X and Y, I know I can make each plot point display as '*' like so:

```<code>plot (X, Y, "*")
</code>```

But how can I involve a third vector Z such that '*' is displayed for some values of Z, and '+' is displayed for others?

答:
Can also be done by getting the indices of elements of Z for which +/* are to printed in 2 separate arrays using find method.

Considering that you want to print (+) for positive values of Z and (*) for negative values, the following code will do it:

```<code>    pos = find(Z > 0); neg = find(Z <= 0);
    plot(X(pos), Y(pos), 'k+', X(neg), Y(neg), 'k*');
</code>```

Title: Octave - Variable point symbol in plot

Body:
I'm plotting two vectors against one another.  I would like to vary the symbol used to plot each point based on the corresponding value in a third vector.

In other words, if I'm plotting X and Y, I know I can make each plot point display as '*' like so:

plot (X, Y, "*")

But how can I involve a third vector Z such that '*' is displayed for some values of Z, and '+' is displayed for others?

Body:
Can also be done by getting the indices of elements of Z for which +/* are to printed in 2 separate arrays using find method.

Considering that you want to print (+) for positive values of Z and (*) for negative values, the following code will do it:

    pos = find(Z > 0); neg = find(Z <= 0);
    plot(X(pos), Y(pos), 'k+', X(neg), Y(neg), 'k*');


问:
Are utility classes evil?
I saw this question: If a "Utilities" class is evil, where do I put my generic code?

And I thought, why are utility classes evil?

Let’s say I have a domain model that is dozens of classes deep.  I need to be able to xml-ify instances.  Do I make a toXml method on the parent?  Do I make a MyDomainXmlUtility.toXml helper class?  This is a case where the business need spans the entire domain model -- does it really belong as an instance method?  What about if there are a bunch of auxiliary methods on the XML functionality of the application?

答:
Rule of thumb

You can look at this problem from two perspectives:

Overall *Util methods are often a suggestion of bad code design or lazy naming convention.

It is legitimate design solution for reusable cross-domain stateless functionalities. Please note that for almost all common problems there are existing solutions.

Example 1. Correct usage of util classes/modules. External library example

Let's assume you are writing application which manages loans and credit cards. Data from these modules is exposed through web services in json format.
In theory you can manually convert objects to strings which will be in json, but that would reinvent the wheel. Correct solution would be to include in both modules external library used to convert java objects to desired format. (in example image I have shown gson)

Example 2. Correct usage of util classes/modules. Writing your own util without excuses to other team members

As a use case assume that we need to perform some calculations in two modules of application, but both of them need to know when there are public holidays in Poland. In theory you can make these calculations inside modules, but it would be better to extract this functionality to separate module.

Here is small, but important detail. Class/module you have written is not called HolidayUtil, but PolishHolidayCalculator. Functionally it is a util class, but we have managed to avoid generic word.

ContentLicense: CC BY-SA 4.0

Title: Are utility classes evil?


问:
String.Format() to add commas in thousands place for a number not working
String.Format to add commas in thousands place just add space without comma.

I tried:

```<code> var total = string.Format("{0:n0}", 12345);
 // expect: total = 12,345
 // actual: total = 12 345
</code>```

Anything I'm missing?

答:
This seems to be your regional settings on you PC:

The DEMO works fine

Body:
String.Format to add commas in thousands place just add space without comma.

I tried:

 var total = string.Format("{0:n0}", 12345);
 // expect: total = 12,345
 // actual: total = 12 345

Anything I'm missing?


问:
Find if two strings are same in an array?
I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?</p>

答:
I would add it to a set of strings from your title
then compare the count of both, if count is equal then there are no duplicates, if set count less that mean there are two titles that equal</p>


问:
Create an array of primitives or objects in Java

Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

```<code>public void myMethod(Object[] a) {...}
</code>```

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

```<code>public void myMethod(Object[] a) {
     Object something = a[0];
     }
</code>```

答:
```<code>import java.lang.reflect.Array;

public void myMethod(Object[] a)
{
    Array.get(a, 0);
 }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

public void myMethod(Object[] a) {...}

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

public void myMethod(Object[] a) {
     Object something = a[0];
     }


问:
The "table" in sqlContext.table
I'm working my way through a book on Spark and I'm on a section dealing with the join method for dataframes. In this example, the "trips" table is being joined with the "stations" table:

```<code>trips = sqlContext.table("trips")
stations = sqlContext.table("stations")
joined = trips.join(stations, trips.start_terminal == stations.station_id)
joined.printSchema()
</code>```

The data is supposed to come from two spreadsheets, trips.csv and stations.csv, but I don't know how Spark is supposed to figure that out. It seems to me that there should be a line indicating where "trips" and "stations" are supposed to come from.

If I try something like

```<code>trips = sqlContext.table('/home/l_preamble/Documents/trips.csv')
</code>```

it doesn't like it "pyspark.sql.utils.ParseException: u"\nextraneous input '/' expecting {'SELECT', 'FROM', 'ADD'..."

So how can I point it in the direction of the data? Any help would be appreciated.

答:
In order to join two dataframes in pyspark, you should try this:-</p>

```<code>df1=sqlContext.registerTempTable("trips")
df2=sqlContext.registerTempTable("stations")

df2.join(df1,['column_name'],outer)
</code>```

Title: The "table" in sqlContext.table

Body:
I'm working my way through a book on Spark and I'm on a section dealing with the join method for dataframes. In this example, the "trips" table is being joined with the "stations" table:

trips = sqlContext.table("trips")
stations = sqlContext.table("stations")
joined = trips.join(stations, trips.start_terminal == stations.station_id)
joined.printSchema()

The data is supposed to come from two spreadsheets, trips.csv and stations.csv, but I don't know how Spark is supposed to figure that out. It seems to me that there should be a line indicating where "trips" and "stations" are supposed to come from.

If I try something like

trips = sqlContext.table('/home/l_preamble/Documents/trips.csv')

it doesn't like it "pyspark.sql.utils.ParseException: u"\nextraneous input '/' expecting {'SELECT', 'FROM', 'ADD'..."

So how can I point it in the direction of the data? Any help would be appreciated.

Body:
In order to join two dataframes in pyspark, you should try this:-

df1=sqlContext.registerTempTable("trips")
df2=sqlContext.registerTempTable("stations")

df2.join(df1,['column_name'],outer)


问:
How to do subtraction between two fields in a Table using an SQL query
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |
</code>```

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |
</code>```

Thanks!

答:
```<code>SELECT
    id
    ,subject
    ,Time1
    ,Time2
    ,Time2-Time1 as Time3
FROM tbl
</code>```

Body:
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |

Thanks!


问:
Data Tables and Firebase Web
i have some problem when i code my web

here's the Html

```<code><table id="user_data" class="display" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Nama</th>
                            <th>Email</th>
                            <th>No.Hp</th>
                            <th>Status</th>
                        </tr>
                    </thead>

                    <tbody id="table-body-pengguna">

                    </tbody>
                </table>
</code>```

And here's the Script

```<code>$('#user_data').DataTable({
    dom: 'Bfrtip',
    buttons: [
        'csv'
    ]
});
var rootRef = firebase.database().ref().child("users");

rootRef.on("child_added", snap => {
    var name = snap.child("name").val();
    var email = snap.child("email").val();
    var noHP = snap.child("noHp").val();
    var status = snap.child("status").val();

    $("#table-body-pengguna").append("<tr><td>" + name + "</td><td>" + email +
        "</td><td>" + noHP + "</td><td>" + status + "</td></tr>");
})
</code>```

And here's the output

https://ibb.co/bYzpOv

Why the Datatables not displaying properly? Thanks for your time.

答:
This should work perfectly      </p>

```<code>    rootRef.on("child_added", snap => {
         var dataSet = [snap.child("name").val(), snap.child("email").val(), snap.child("blood").val(), snap.child("Phone").val(), snap.child("Location").val()];
    table.rows.add([dataSet]).draw();
</code>```

Title: Data Tables and Firebase Web

Body:
i have some problem when i code my web

here's the Html

                            Nama
                            Email
                            No.Hp
                            Status

And here's the Script

$('#user_data').DataTable({
    dom: 'Bfrtip',
    buttons: [
        'csv'
    ]
});
var rootRef = firebase.database().ref().child("users");

rootRef.on("child_added", snap => {
    var name = snap.child("name").val();
    var email = snap.child("email").val();
    var noHP = snap.child("noHp").val();
    var status = snap.child("status").val();

    $("#table-body-pengguna").append("
" + name + "	" + email +
        "	" + noHP + "	" + status + "
");
})

And here's the output

https://ibb.co/bYzpOv

Why the Datatables not displaying properly? Thanks for your time.

Body:
This should work perfectly

    rootRef.on("child_added", snap => {
         var dataSet = [snap.child("name").val(), snap.child("email").val(), snap.child("blood").val(), snap.child("Phone").val(), snap.child("Location").val()];
    table.rows.add([dataSet]).draw();


问:
Flexbox grid 1col 1row 3boxes
How can I make this grid without creating 2 columns?

答:
Here is my flex box as you want ..

.vert_flex {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    border: 1px solid black;
}

.hor_flex {
    display: flex;
    flex-direction: row;
    height: 100%;
    width: 100%;
    border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hor_flex">
  <div style="flex : 2; height: 300px">width 66.6%</div>
<div class="vert_flex" style="flex : 1; height: 300px">
  <div class="hor_flex" style="flex : 1">width 33.3%</div>
  <div class="hor_flex" style="flex : 1">width 33.3%</div>
</div>
</div></code>```

Title: Flexbox grid 1col 1row 3boxes

Body:
Here is my flex box as you want ..

.vert_flex {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    border: 1px solid black;
}

.hor_flex {
    display: flex;
    flex-direction: row;
    height: 100%;
    width: 100%;
    border: 1px solid black;
}

<div class="hor_flex">
  <div style="flex : 2; height: 300px">width 66.6%</div>
<div class="vert_flex" style="flex : 1; height: 300px">
  <div class="hor_flex" style="flex : 1">width 33.3%</div>
  <div class="hor_flex" style="flex : 1">width 33.3%</div>
</div>
</div>


问:
Encoding Unicode in the Dictionary Key to Japanese
I just started working on text clustering in Japanese through Python2. However, when I created the dictionary based on these Japanese words/terms, the dictionary keys become unicode instead of Japanese. The codes are as follows:

```<code># load data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

## create dictionary
dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()
X_transform = X[:, freqrank < 1000].transpose().toarray()
</code>```

The results of allWrdMat10.columns are still Japanese as follows:

```<code>Index([u'?', u'．', u'・', u'％', u'０', u'１', u'１０月', u'１１月', u'１２
月', u'１つ',
...
u'瀋陽', u'疆', u'盧', u'籠', u'絆', u'胚', u'諫早', u'趙', u'鉉', u'鎔
基'],dtype='object', length=8655)
</code>```

However, the results of dict_index.keys() are as:

```<code>[u'\u77ed\u9283',
 u'\u5efa\u3066',
 u'\u4f0a',
 u'\u5e73\u5b89',
 u'\u6025\u9a30',
 u'\u897f\u65e5\u672c',
 u'\u5e03\u9663',
 ...]
</code>```

Is there any way I can keep the Japanese words/terms in the dictionary keys? Or is there any way I can convert the unicodes back to Japanese words/terms? Thanks.

答:
You did not prefix the string with u, which is needed in Python 2. Even better,
unicode_literals
   import unicode_literals

Body:
I just started working on text clustering in Japanese through Python2. However, when I created the dictionary based on these Japanese words/terms, the dictionary keys become unicode instead of Japanese. The codes are as follows:

# load data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

## create dictionary
dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()
X_transform = X[:, freqrank < 1000].transpose().toarray()

The results of allWrdMat10.columns are still Japanese as follows:

Index([u'?', u'．', u'・', u'％', u'０', u'１', u'１０月', u'１１月', u'１２
月', u'１つ',
...
u'瀋陽', u'疆', u'盧', u'籠', u'絆', u'胚', u'諫早', u'趙', u'鉉', u'鎔
基'],dtype='object', length=8655)

However, the results of dict_index.keys() are as:

[u'\u77ed\u9283',
 u'\u5efa\u3066',
 u'\u4f0a',
 u'\u5e73\u5b89',
 u'\u6025\u9a30',
 u'\u897f\u65e5\u672c',
 u'\u5e03\u9663',
 ...]

Is there any way I can keep the Japanese words/terms in the dictionary keys? Or is there any way I can convert the unicodes back to Japanese words/terms? Thanks.


答:
Assuming Time1 and Time2 are Number columns, you can use a simple subtraction:

```<code>select id, subject, Time1, Time3, Time2 - Time1 as Time3 from myTable
</code>```

Title: How to do subtraction between two fields in a Table using an SQL query

Body:
Assuming Time1 and Time2 are Number columns, you can use a simple subtraction:

select id, subject, Time1, Time3, Time2 - Time1 as Time3 from myTable


问:
What's the difference between the lang attribute and the <meta http-equiv="Content-Language" content="en-US"> tag?
I was wondering what's the significance of using the "lang" attribute and how that differs from using the meta "Content-Language" tag?

Consider the following code:

```<code><html lang="en">
    <head>
        <meta http-equiv="Content-Language" content="en-US">
    </head>...
</code>```

My assumption is that the browser is reading the meta tag's value, but the DOM is concerned with the "lang" attribute. Is this correct? Are there any nuances I'm unaware of?

答:
The lang attribute (on the HTML element) specifies the language for the document (unless overridden with another lang attribute which can change the language for a section of the document).

The Content-Language HTTP header specifies the language of the intended audience. This is not the same as the language the document is actually written in. For example, part of a French language course could consist of a page written in French, but Content-Language would be en as it was intended for English speakers learning French.

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

Meta HTTP-equiv is the poor man's HTTP header. It has all the meaning of the real HTTP header, but less respect (and support).

As a rule of thumb, Content-Language is of more interest to search engines and the lang attribute is of more interest to screen readers.

Body:
I was wondering what's the significance of using the "lang" attribute and how that differs from using the meta "Content-Language" tag?

Consider the following code:

        <meta http-equiv="Content-Language" content="en-US">
    ...

My assumption is that the browser is reading the meta tag's value, but the DOM is concerned with the "lang" attribute. Is this correct? Are there any nuances I'm unaware of?


问:
Mapbox Callout Accessory
I was wondering if Mapbox had any other callout buttons rather than just the seven provided? </p>

```<code>let button = UIButton(type: .detailDisclosure)
</code>```

<p>Or if there was a quick fix to converting these UIButtons into UIImages in order to create my own buttons. </p>

答:
Yes, you can use the methods func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? and func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? to create your own. Set the button type to .custom

For example:

```<code>func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
    // We're not concerned with the user annotation.
    guard annotation is CameraAnnotation || annotation is NoteAnnotation else {
        return nil
    }
    // Callout height is fixed; width expands to fit its content.
    let deleteButton = UIButton(type: .custom)
    deleteButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    deleteButton.setImage(UIImage(named: "delete"), for: .normal)
    deleteButton.tag = 100
    return deleteButton
}
</code>```

Title: Mapbox Callout Accessory

Body:
I was wondering if Mapbox had any other callout buttons rather than just the seven provided?

let button = UIButton(type: .detailDisclosure)

Or if there was a quick fix to converting these UIButtons into UIImages in order to create my own buttons.

Body:
Yes, you can use the methods func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? and func mapView(_ mapView: MGLMapView, rightCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? to create your own. Set the button type to .custom

For example:

func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {
    // We're not concerned with the user annotation.
    guard annotation is CameraAnnotation || annotation is NoteAnnotation else {
        return nil
    }
    // Callout height is fixed; width expands to fit its content.
    let deleteButton = UIButton(type: .custom)
    deleteButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    deleteButton.setImage(UIImage(named: "delete"), for: .normal)
    deleteButton.tag = 100
    return deleteButton
}


问:
Label Encoding of multiple columns without using pandas
Is there a simple way to label encode without using pandas for multiple columns?

Like using only numpy and sklearn's preprocessing.LabelEncoder()

答:
One solution would be to loop through the columns, converting them to numeric values, using LabelEncoder:

```<code>le = LabelEncoder()

cols_2_encode = [1,3,5]

for col in cols_2_encode:
    X[:, col] = le.fit_tramsform(X[:, col])
</code>```

Body:
One solution would be to loop through the columns, converting them to numeric values, using LabelEncoder:

le = LabelEncoder()

cols_2_encode = [1,3,5]

for col in cols_2_encode:
    X[:, col] = le.fit_tramsform(X[:, col])


答:
just try this</p>

```<code>select id, subject, Time1, Time2, Time2-Time1 as Time3  from mytable
</code>```

Body:
just try this

select id, subject, Time1, Time2, Time2-Time1 as Time3  from mytable


问:
Using __arglist with a varying set of named parameters
in my application I have 2 layers. The first layer is a C legacy exposing cdecl functions that use the "..." syntax for a varying parameter list. The only way I found to call these functions from my .Net layer (the second one) is using the DllImport technics. For example the C function below:

```<code>int myFunc(char* name, ...);
</code>```

looks like that in C#:

```<code>[DllImport("MyDll.dll"),
 CharSet = CharSet.Ansi,
 CallingConvention = CallingConvention.Cdecl]
int myFunc(string name, __arglist);
</code>```

My problem is that sometimes I want to call this function with 2 extra parameters but if one of them is NULL it won't be included in the argument list (my legacy code fails on NULL values). For example I want this call:

```<code>int foo(string name, string a, string b)
{
     myFunc(name, __arglist(a, b));
}

{
     foo("john", "arg1", null);
}
</code>```

to be interpreted by C as

```<code>myFunc("john", "arg1");
</code>```

Unfortunately doing something like that:

```<code>int foo(string name, string a, string b)
{
     List<string> args = new List<string>();
     if(a != null) args.Add(a);
     if(b != null) args.Add(b);
     myFunc(name, __arglist(args));
}
{
     foo("john", "arg1", null);
}
</code>```

is interpreted by C like that:

```<code>myFunc(name, args);
</code>```

and not:

```<code>myFunc(name, args[0]);
</code>```

Does anybody have any idea?

答:
How does the C function know which one is the last parameter? It cannot know a priori how many parameters there are. It needs additional information. One common way for functions get the information they need is by parsing the included string parameter to count format specifiers, as in printf. In that case, if the format string only indicates that there is one extra parameter, then the function doesn't know the difference between a call that really had just one extra parameter and a call that had two or a call that had 20. The function should have the self-discipline to only read one parameter, since that's all the format string said there was. Reading more would lead to undefined behavior.

If what I've described is not the way your function works, then there's not much you can do on the calling end to solve it. But if it is how your function works, then there's nothing to do on  the calling end, because there's no problem.

Another option, since you indicate that your "legacy code fails on null values," is to fix your legacy code so it doesn't fail anymore.

A third option is to simply write all four possibilities:

```<code> if (a != null) {
   if (b != null)
     return myFunc(name, a, b);
   else
     return myFunc(name, a);
 } else {
   if (b != null)
     return myFunc(names, b);
   else
     return myFunc(names);
 }
</code>```

More than two optional parameters, though, and the code starts getting unwieldy.

OwnerDisplayName: Moshe

Body:
in my application I have 2 layers. The first layer is a C legacy exposing cdecl functions that use the "..." syntax for a varying parameter list. The only way I found to call these functions from my .Net layer (the second one) is using the DllImport technics. For example the C function below:

int myFunc(char* name, ...);

looks like that in C#:

[DllImport("MyDll.dll"),
 CharSet = CharSet.Ansi,
 CallingConvention = CallingConvention.Cdecl]
int myFunc(string name, __arglist);

My problem is that sometimes I want to call this function with 2 extra parameters but if one of them is NULL it won't be included in the argument list (my legacy code fails on NULL values). For example I want this call:

int foo(string name, string a, string b)
{
     myFunc(name, __arglist(a, b));
}

{
     foo("john", "arg1", null);
}

to be interpreted by C as

myFunc("john", "arg1");

Unfortunately doing something like that:

int foo(string name, string a, string b)
{
     List<string> args = new List<string>();
     if(a != null) args.Add(a);
     if(b != null) args.Add(b);
     myFunc(name, __arglist(args));
}
{
     foo("john", "arg1", null);
}

is interpreted by C like that:

myFunc(name, args);

and not:

myFunc(name, args[0]);

Does anybody have any idea?

Body:
How does the C function know which one is the last parameter? It cannot know a priori how many parameters there are. It needs additional information. One common way for functions get the information they need is by parsing the included string parameter to count format specifiers, as in printf. In that case, if the format string only indicates that there is one extra parameter, then the function doesn't know the difference between a call that really had just one extra parameter and a call that had two or a call that had 20. The function should have the self-discipline to only read one parameter, since that's all the format string said there was. Reading more would lead to undefined behavior.

If what I've described is not the way your function works, then there's not much you can do on the calling end to solve it. But if it is how your function works, then there's nothing to do on  the calling end, because there's no problem.

Another option, since you indicate that your "legacy code fails on null values," is to fix your legacy code so it doesn't fail anymore.

A third option is to simply write all four possibilities:

 if (a != null) {
   if (b != null)
     return myFunc(name, a, b);
   else
     return myFunc(name, a);
 } else {
   if (b != null)
     return myFunc(names, b);
   else
     return myFunc(names);
 }

More than two optional parameters, though, and the code starts getting unwieldy.

OwnerDisplayName: Rob Kennedy


问:
Iframe resize resizing to content
I was trying to implement some js my own, but in the end i needed to set height manually.

https://sklepdruku.pl/project/wizytowki-klasyczne/

What type of script i need to use here to make it work?

答:
If you want to set the height of an iframe according to the height of its content, and the iframe content is on the same domain than the parent, this is your answer:

Adjust width height of iframe to fit with content in it

If the iframe content isn't on the same domain, and if you can't edit the iframe content directly from the source, maybe you can:

make an ajax request to an internal php with the iframe url in request parameters

in the php file create (or empty if already created) a file in wich you will put the height value

download (with curl or file_get_contents) the content of the iframe and save it in a html file

edit the downloaded page and put in some js to get the document height

edit the downloaded page and put in some js to make a ajax request to a
second php file, put the document height in the ajax request
parameters

make a request from the current php file to the edited html file, this will execute the ajax request wich will call the second php file

in the second php file get the height parameter and put it in the file that you created in the n.2

from the first php file open and read the file in wich the height
has been saved and return the value to your first ajax request.

set the iframe height value with the ajax response value

I don't try, but it can work. Maybe you had to set an infinite loop before returning the height to your first ajax request. The loop will break only when the file with the height value won't be empty, or if the timeout expired(set a short timeout for the execution of php).

Title: Iframe resize resizing to content


问:
onLocationChanged never called in FusedLocationApi
There are some other questions on SO about the same problem, but I guess that the answers a bit old and maybe not applicable to my scenario. In the code below, the method onLocationChanged is never called. I also tried to send new Locations from the android emulator, but it's just never called. Any idea what is going wrong here?

```<code>public class MyActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
  GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleApiClient apiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myview);

        apiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        apiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        System.out.println("yeah, this works");

        // I also tried to set some properties on the location request like interval, etc. but they have no effect
        LocationRequest request = new LocationRequest();
        LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, request, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        System.out.println("this is never shown");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        System.out.println("this is never shown");
    }

    @Override
    public void onLocationChanged(Location location) {
        System.out.println("this line is never called ");
    }
}
</code>```

答:
I found that I had gradle warnings about "all com.android.support libraries must use the exact same version specification". In my case I changed

```<code>compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.google.android.gms:play-services:9.8.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
</code>```

to

```<code>compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:animated-vector-drawable:25.2.0'
compile 'com.android.support:support-core-ui:25.2.0'
compile 'com.android.support:mediarouter-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services:9.8.0'
</code>```

With the new dependencies list, gradle is happy and the example just works. Hope this can help someone.

Body:
There are some other questions on SO about the same problem, but I guess that the answers a bit old and maybe not applicable to my scenario. In the code below, the method onLocationChanged is never called. I also tried to send new Locations from the android emulator, but it's just never called. Any idea what is going wrong here?

public class MyActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
  GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleApiClient apiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myview);

        apiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        apiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        System.out.println("yeah, this works");

        // I also tried to set some properties on the location request like interval, etc. but they have no effect
        LocationRequest request = new LocationRequest();
        LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, request, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        System.out.println("this is never shown");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        System.out.println("this is never shown");
    }

    @Override
    public void onLocationChanged(Location location) {
        System.out.println("this line is never called ");
    }
}

Body:
I found that I had gradle warnings about "all com.android.support libraries must use the exact same version specification". In my case I changed

compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.google.android.gms:play-services:9.8.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'

to

compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:animated-vector-drawable:25.2.0'
compile 'com.android.support:support-core-ui:25.2.0'
compile 'com.android.support:mediarouter-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services:9.8.0'

With the new dependencies list, gradle is happy and the example just works. Hope this can help someone.


问:
What is the best way to generate a unique and short file name in Java
I don't necessarily want to use UUIDs since they are fairly long.

The file just needs to be unique within its directory.

One thought which comes to mind is to use File.createTempFile(String prefix, String suffix), but that seems wrong because the file is not temporary.

The case of two files created in the same millisecond needs to be handled.

答:
This also works</p>

```<code>String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

logFileName = "loggerFile_" + logFileName;
</code>```

Body:
This also works

String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

logFileName = "loggerFile_" + logFileName;


问:
How can I render a POSIXlt in R Markdown?
In RStudio Version 1.0.143, with the following R Markdown, I get an HTML with the POSIXlt not properly rendered.

This is the markdown source:

```<code>---
title: "Untitled"
author: "Alessandro"
date: "05 giugno 2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
filename <- '61170604140000.txt'

get_timestamp <- function(filename)
{
  dt <- substr(filename,3,14)
  strptime(dt,"%y%m%d%H%M%S",tz="UTC")
}
```

## R Markdown

Timestamp is: `r get_timestamp(filename)`
</code>```

And this is the result I get with "Knit to HTML" command:

```<code>Timestamp is: 0, 0, 14, 4, 5, 117, 0, 154, 0
</code>```

While I would have expected:

```<code>Timestamp is: 2017-06-04 14:00:00 UTC
</code>```

My sessionInfo:

```<code>> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.4.0  backports_1.0.5 magrittr_1.5    rprojroot_1.2   htmltools_0.3.6 tools_3.4.0     yaml_2.1.14
 [8] Rcpp_0.12.10    stringi_1.1.5   rmarkdown_1.5   knitr_1.15.1    stringr_1.2.0   digest_0.6.12   evaluate_0.10
</code>```

答:
As a work around, you can use as.character in your function:

```<code>get_timestamp <- function(filename)
{
  dt <- substr(filename,3,14)
  as.character(strptime(dt,"%y%m%d%H%M%S",tz="UTC"))
}
</code>```

The Markdown parser must be using the internal representation of the object rather than the output format.

```<code>> str(strptime(substr(filename,3,14),"%y%m%d%H%M%S",tz="UTC"))
 POSIXlt[1:1], format: "2017-06-04 14:00:00"
> str(as.character(strptime(substr(filename,3,14),"%y%m%d%H%M%S",tz="UTC")))
 chr "2017-06-04 14:00:00"
</code>```

Body:
In RStudio Version 1.0.143, with the following R Markdown, I get an HTML with the POSIXlt not properly rendered.

This is the markdown source:

---
title: "Untitled"
author: "Alessandro"
date: "05 giugno 2017"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
filename <- '61170604140000.txt'

get_timestamp <- function(filename)
{
  dt <- substr(filename,3,14)
  strptime(dt,"%y%m%d%H%M%S",tz="UTC")
}
```

## R Markdown

Timestamp is: `r get_timestamp(filename)`

And this is the result I get with "Knit to HTML" command:

Timestamp is: 0, 0, 14, 4, 5, 117, 0, 154, 0

While I would have expected:

Timestamp is: 2017-06-04 14:00:00 UTC

My sessionInfo:

> sessionInfo()
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252    LC_MONETARY=Italian_Italy.1252
[4] LC_NUMERIC=C                   LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] compiler_3.4.0  backports_1.0.5 magrittr_1.5    rprojroot_1.2   htmltools_0.3.6 tools_3.4.0     yaml_2.1.14
 [8] Rcpp_0.12.10    stringi_1.1.5   rmarkdown_1.5   knitr_1.15.1    stringr_1.2.0   digest_0.6.12   evaluate_0.10

Body:
As a work around, you can use as.character in your function:

get_timestamp <- function(filename)
{
  dt <- substr(filename,3,14)
  as.character(strptime(dt,"%y%m%d%H%M%S",tz="UTC"))
}

The Markdown parser must be using the internal representation of the object rather than the output format.

> str(strptime(substr(filename,3,14),"%y%m%d%H%M%S",tz="UTC"))
 POSIXlt[1:1], format: "2017-06-04 14:00:00"
> str(as.character(strptime(substr(filename,3,14),"%y%m%d%H%M%S",tz="UTC")))
 chr "2017-06-04 14:00:00"


问:
Pass additional parameters to method
I am using Devexpress file upload control. I am making using of the following overload in the UploadControlExtension class:

```<code>public static UploadedFile[] GetUploadedFiles(string name, UploadControlValidationSettings validationSettings, EventHandler<FileUploadCompleteEventArgs> fileUploadCompleteDelegate);
</code>```

My complete event method signature looks like:

```<code>public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e)
</code>```

What I am trying to do is pass in additional parameter to my AttachmentUploadedCompleteEvent() method. So I want the signature to change to

```<code>public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e, bool isAdmin)
</code>```

But of course if I change to the above then I get an error:

cannot convert from 'method group' to 'out string[]'

My knowledge on Delegates is not the best so I was hoping someone could point me to the right direction on how to achieve this.

Thanks in advance for your help.

答:
It is required to provide a method that is compatible with the signature of the delegate. Which means, the 3rd parameter to GetUploadedFiles must be a method which takes an object and a FileUploadCompleteEventArgs as parameters, and returns void.

You could pass a lambda to "curry" your function:

```<code>GetUploadedFiles(name, validationSettings, (s, e)=> { AttachmentUploadedCompleteEvent(s, e, isAdmin); }
</code>```

The lambda expression is an anonymous method that MATCHES the signature of the required delegate, and yet you can pass another parameter to your original method.

Title: Pass additional parameters to method

Body:
I am using Devexpress file upload control. I am making using of the following overload in the UploadControlExtension class:

public static UploadedFile[] GetUploadedFiles(string name, UploadControlValidationSettings validationSettings, EventHandler<FileUploadCompleteEventArgs> fileUploadCompleteDelegate);

My complete event method signature looks like:

public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e)

What I am trying to do is pass in additional parameter to my AttachmentUploadedCompleteEvent() method. So I want the signature to change to

public static void AttachmentUploadedCompleteEvent(object sender, FileUploadCompleteEventArgs e, bool isAdmin)

But of course if I change to the above then I get an error:

cannot convert from 'method group' to 'out string[]'

My knowledge on Delegates is not the best so I was hoping someone could point me to the right direction on how to achieve this.

Thanks in advance for your help.

Body:
It is required to provide a method that is compatible with the signature of the delegate. Which means, the 3rd parameter to GetUploadedFiles must be a method which takes an object and a FileUploadCompleteEventArgs as parameters, and returns void.

You could pass a lambda to "curry" your function:

GetUploadedFiles(name, validationSettings, (s, e)=> { AttachmentUploadedCompleteEvent(s, e, isAdmin); }

The lambda expression is an anonymous method that MATCHES the signature of the required delegate, and yet you can pass another parameter to your original method.


问:
Linux shell temporary DNS
In a linux shell script, I want to change the dns address temporarily.
To do this, I can insert temprary dns address into resolv.conf right after the shell run and remove it before the script ends. That's it.

But the problem is, all every other scripts also hit the address while the script is running.
This is not what I expected.
Isn't there another way that can changes the dns temporarily in a shell without affecting the others ?

答:
Unshare able to help you. Unshare help to run program with some namespaces unshared from parent. Using unshare you can able to use your custom resolv.conf limited to your script session & will not affect to other system users and queries.</p>

```<code>  sudo unshare --mount bash -s <<'EOF'
  mount --bind custom_resolv.conf /etc/resolv.conf
  sudo -u username run_command
  EOF
</code>```

Title: Linux shell temporary DNS

Body:
Unshare able to help you. Unshare help to run program with some namespaces unshared from parent. Using unshare you can able to use your custom resolv.conf limited to your script session & will not affect to other system users and queries.

  sudo unshare --mount bash -s <<'EOF'
  mount --bind custom_resolv.conf /etc/resolv.conf
  sudo -u username run_command
  EOF


问:
correct way to implement item touch helper on recyclerview in android
i followed a tutorial here on how to implement onItemTouchHelper and callback methods when i run my code it works to the point that i can long press and pick up the item but the moment i move it past one of the other items in the list my app will force close with an index out of bounds exception can anybody here help me?

here is my code but it is identical to the code in the tutorial,

Simple Item Touch Helper Callback

```<code>public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback
{

private final predictsCardAdapter mAdapter;

public SimpleItemTouchHelperCallback(predictsCardAdapter adapter){
    mAdapter = adapter;
}

@Override
public boolean isLongPressDragEnabled(){
    return true;
}
@Override
public boolean isItemViewSwipeEnabled(){
    return false;
}

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
    int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;

    return makeMovementFlags(dragFlags,swipeFlags);
}

@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mAdapter.onItemMove(viewHolder.getAdapterPosition(),
    target.getAdapterPosition());
    //mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(),
    //target.getAdapterPosition());
    return true;
}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
</code>```

heres my adapter

```<code>public class predictsCardAdapter extends
RecyclerView.Adapter<predictsCardAdapter.MyViewHolder> implements
ItemTouchHelperAdapter{
private List<addNewCard> cardMakerList;

@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (fromPosition < toPosition){
        for (int i = fromPosition; i < toPosition; i++){
            Collections.swap(cardMakerList,i,i+1);
        }
    }else{
        for (int i = fromPosition; i > toPosition; i--){
            Collections.swap(cardMakerList,i,i-1);
        }
    }
    notifyItemMoved(fromPosition,toPosition);
    return true;
}

@Override
public void onItemDismiss(int position) {
cardMakerList.remove(position);
    notifyItemRemoved(position);
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView cardText, speechText;
    public ImageView cardImage;
    public ContentLoadingProgressBar progress;

    public MyViewHolder(View view){
        super(view);
        cardText = (TextView) view.findViewById(R.id.predictscardText);
        speechText = (TextView) view.findViewById(R.id.predictsspeechText);
        cardImage = (ImageView) view.findViewById(R.id.predictscardimage);
        progress = (ContentLoadingProgressBar)
        view.findViewById(R.id.predictsprogress);
    }

}
public predictsCardAdapter(List<addNewCard> cardMakerList){
    this.cardMakerList = cardMakerList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.predicted_card, parent, false);
    return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder
(final MyViewHolder predicts_holder, int position) {
    addNewCard cardmaker = cardMakerList.get(position);
    predicts_holder.cardText.setText(cardmaker.getCardName());
    predicts_holder.speechText.setText(cardmaker.getCardName());
    //Drawable d = new
    BitmapDrawable(Utility.getPhoto(cardmaker.getCardIcon()));

    String url = cardmaker.getCardIcon();
    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options = new
    DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisc(true).resetViewBeforeLoading(true)
            .showImageForEmptyUri(R.drawable.loading_image)
            .showImageOnFail(R.drawable.broken_image).build();

    imageLoader.displayImage
    (url, predicts_holder.cardImage, options, new
    SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            predicts_holder.progress.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed
        (String imageUri, View view, FailReason failReason) {
            predicts_holder.progress.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingComplete
    (String imageUri, View view, Bitmap loadedImage) {
            predicts_holder.progress.setVisibility(View.GONE);
        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
predicts_holder.cardText.setTextAppearance
(android.R.style.TextAppearance_Material_Small);
    }
    else{
        predicts_holder.cardText.setTextAppearance
(predicts_holder.cardImage.getContext(    ),
android.R.style.TextAppearance_Material_Small);
    }
    predicts_holder.cardText.setTextSize(10);
}
@Override
public int getItemCount(){
    return cardMakerList.size();
}
}
</code>```

i also have a ItemTouchHelperAdapter

```<code>public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}
</code>```

and i use it in my activity like this

```<code> ItemTouchHelper.Callback callback = new
 SimpleItemTouchHelperCallback(predicts_card_adapter);
    ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
    touchHelper.attachToRecyclerView(recyclerView);
</code>```

the error i get is

```<code>java.lang.IndexOutOfBoundsException

at java.util.Collections.swap(Collections.java:1937)

at

ss.sealstudios.com.socialstories.predictsCardAdapter.
onItemMove(predictsCardAdapter.java:33)

at ss.sealstudios.com.socialstories.SimpleItemTouchHelperCallback
.onMove(SimpleItemTouchHelperCallback.java:36)
</code>```

in the onMove methods if i uncomment the

```<code>mAdapter.onItemMove(viewHolder.getAdapterPosition(),
target.getAdapterPosition());
</code>```

the drag and drop half works so i can drag it but not drop it and the views dont move to accomodate it
which makes me think its my cardMaker list but that is just a list from a database, can anybody see something i cant?

答:
I edit the onItemMove method of  your adapter ,this can avoid the Exception and get the right ordered list,see below code:</p>

```<code>@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (cardMakerList == null || cardMakerList.size() == 0) {
        return;
    }
    if (fromPosition < 0 || fromPosition >= cardMakerList.size()) {
        return;
    }
    if (toPosition < 0 || toPosition >= cardMakerList.size()) {
        return;
    }
    if (fromPosition == toPosition) {
        return;
    }
    T toMoveE = cardMakerList.get(fromPosition);
    if (fromPosition > toPosition) {
        for (int i = fromPosition; i > toPosition; i--) {
            cardMakerList.set(i, cardMakerList.get(i - 1));
        }
    } else {
        for (int i = fromPosition; i < toPosition; i++) {
            cardMakerList.set(i, cardMakerList.get(i + 1));
        }
    }
    cardMakerList.set(toPosition, toMoveE);
    notifyItemMoved(fromPosition, toPosition);
    return true;
}
</code>```

Body:
i followed a tutorial here on how to implement onItemTouchHelper and callback methods when i run my code it works to the point that i can long press and pick up the item but the moment i move it past one of the other items in the list my app will force close with an index out of bounds exception can anybody here help me?

here is my code but it is identical to the code in the tutorial,

Simple Item Touch Helper Callback

public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback
{

private final predictsCardAdapter mAdapter;

public SimpleItemTouchHelperCallback(predictsCardAdapter adapter){
    mAdapter = adapter;
}

@Override
public boolean isLongPressDragEnabled(){
    return true;
}
@Override
public boolean isItemViewSwipeEnabled(){
    return false;
}

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
    int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;

    return makeMovementFlags(dragFlags,swipeFlags);
}

@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mAdapter.onItemMove(viewHolder.getAdapterPosition(),
    target.getAdapterPosition());
    //mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(),
    //target.getAdapterPosition());
    return true;
}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}

heres my adapter

public class predictsCardAdapter extends
RecyclerView.Adapter<predictsCardAdapter.MyViewHolder> implements
ItemTouchHelperAdapter{
private List<addNewCard> cardMakerList;

@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (fromPosition < toPosition){
        for (int i = fromPosition; i < toPosition; i++){
            Collections.swap(cardMakerList,i,i+1);
        }
    }else{
        for (int i = fromPosition; i > toPosition; i--){
            Collections.swap(cardMakerList,i,i-1);
        }
    }
    notifyItemMoved(fromPosition,toPosition);
    return true;
}

@Override
public void onItemDismiss(int position) {
cardMakerList.remove(position);
    notifyItemRemoved(position);
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView cardText, speechText;
    public ImageView cardImage;
    public ContentLoadingProgressBar progress;

    public MyViewHolder(View view){
        super(view);
        cardText = (TextView) view.findViewById(R.id.predictscardText);
        speechText = (TextView) view.findViewById(R.id.predictsspeechText);
        cardImage = (ImageView) view.findViewById(R.id.predictscardimage);
        progress = (ContentLoadingProgressBar)
        view.findViewById(R.id.predictsprogress);
    }

}
public predictsCardAdapter(List<addNewCard> cardMakerList){
    this.cardMakerList = cardMakerList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.predicted_card, parent, false);
    return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder
(final MyViewHolder predicts_holder, int position) {
    addNewCard cardmaker = cardMakerList.get(position);
    predicts_holder.cardText.setText(cardmaker.getCardName());
    predicts_holder.speechText.setText(cardmaker.getCardName());
    //Drawable d = new
    BitmapDrawable(Utility.getPhoto(cardmaker.getCardIcon()));

    String url = cardmaker.getCardIcon();
    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options = new
    DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisc(true).resetViewBeforeLoading(true)
            .showImageForEmptyUri(R.drawable.loading_image)
            .showImageOnFail(R.drawable.broken_image).build();

    imageLoader.displayImage
    (url, predicts_holder.cardImage, options, new
    SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            predicts_holder.progress.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed
        (String imageUri, View view, FailReason failReason) {
            predicts_holder.progress.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingComplete
    (String imageUri, View view, Bitmap loadedImage) {
            predicts_holder.progress.setVisibility(View.GONE);
        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
predicts_holder.cardText.setTextAppearance
(android.R.style.TextAppearance_Material_Small);
    }
    else{
        predicts_holder.cardText.setTextAppearance
(predicts_holder.cardImage.getContext(    ),
android.R.style.TextAppearance_Material_Small);
    }
    predicts_holder.cardText.setTextSize(10);
}
@Override
public int getItemCount(){
    return cardMakerList.size();
}
}

i also have a ItemTouchHelperAdapter

public interface ItemTouchHelperAdapter {
boolean onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}

and i use it in my activity like this

 ItemTouchHelper.Callback callback = new
 SimpleItemTouchHelperCallback(predicts_card_adapter);
    ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
    touchHelper.attachToRecyclerView(recyclerView);

the error i get is

java.lang.IndexOutOfBoundsException

at java.util.Collections.swap(Collections.java:1937)

at

ss.sealstudios.com.socialstories.predictsCardAdapter.
onItemMove(predictsCardAdapter.java:33)

at ss.sealstudios.com.socialstories.SimpleItemTouchHelperCallback
.onMove(SimpleItemTouchHelperCallback.java:36)

in the onMove methods if i uncomment the

mAdapter.onItemMove(viewHolder.getAdapterPosition(),
target.getAdapterPosition());

the drag and drop half works so i can drag it but not drop it and the views dont move to accomodate it
which makes me think its my cardMaker list but that is just a list from a database, can anybody see something i cant?

Body:
I edit the onItemMove method of  your adapter ,this can avoid the Exception and get the right ordered list,see below code:

@Override
public boolean onItemMove(int fromPosition, int toPosition) {
    if (cardMakerList == null || cardMakerList.size() == 0) {
        return;
    }
    if (fromPosition < 0 || fromPosition >= cardMakerList.size()) {
        return;
    }
    if (toPosition < 0 || toPosition >= cardMakerList.size()) {
        return;
    }
    if (fromPosition == toPosition) {
        return;
    }
    T toMoveE = cardMakerList.get(fromPosition);
    if (fromPosition > toPosition) {
        for (int i = fromPosition; i > toPosition; i--) {
            cardMakerList.set(i, cardMakerList.get(i - 1));
        }
    } else {
        for (int i = fromPosition; i < toPosition; i++) {
            cardMakerList.set(i, cardMakerList.get(i + 1));
        }
    }
    cardMakerList.set(toPosition, toMoveE);
    notifyItemMoved(fromPosition, toPosition);
    return true;
}


问:
Enum error while doing check
I have an enum like this

```<code> public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }
</code>```

I need to display value if it is connected i did this check

```<code>if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}
</code>```

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this

答:
Should it not be something like</p>

```<code>if(YourObject.ConnectionState == ConnectionState.Connected)
{
    SubItems.Add(Data.value)
}
</code>```

Title: Enum error while doing check

Body:
I have an enum like this

 public enum ConnectionState : int
   {
      Unknown = 1,
      Connected = 2,
      Disconnected = 3,
   }

I need to display value if it is connected i did this check

if(ConnectionState.Connected)
{
SubItems.Add(Data.value)
}

But i am getting an error "Cannot implicitly convert type 'ConnectionState' to 'bool'".kindly suggest me how to proceed with this

Body:
Should it not be something like

if(YourObject.ConnectionState == ConnectionState.Connected)
{
    SubItems.Add(Data.value)
}


问:
Method get a string
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

```<code>class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};
</code>```

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

答:
You can use std::string like this

```<code>class Medicine {
public:
  char description[100] = "testing";
    std::string getDescription() {
    return description;
  }
};
</code>```

Title: Method get a string

Body:
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

Body:
You can use std::string like this

class Medicine {
public:
  char description[100] = "testing";
    std::string getDescription() {
    return description;
  }
};


问:
Trying to use semget() to get a semaphore set but I keep getting an EEXIST error, even after I make a new key
So I'm currently writing a server/client program that will take in three commands (HI, PID and GOODBYE) and process them accordingly. I seem to have run into some trouble with my use of semget() in my server.c code.

The error that I'm getting is "EEXIST", which according to the man pages, says that the key already exists (duh lol) - the thing is, I keep manually changing the key each time and it still gives me the error. Am I not understanding something here? It also seems to work fine for the client.c code. Do any of you guys have an idea as to why I'm experiencing this?

Sorry for the somewhat sloppy code, I've been smashing my head on my keyboard all night over this, I'll do my best to comment out my thought processes. Let me know if there's anything I can do to make it easier to read.

client.c:

```<code>#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/sem.h"
#include "signal.h"
#include "string.h"
#include <unistd.h>

#define MEM_KEY 99 // memory key
#define SEM_KEY 1337 // semaphore key
#define SEG_SIZE ( (size_t)100 ) // segment size
#define oops( m, x ) { perror(m); exit(x); } // for error checking
int seg_id, semset_id;
union semun{ int val; struct semid_ds* buf; ushort* array; }; // for wait and release functions
void wait_and_lock( int );
void release_lock( int );

int main()
{
    char c;
    key_t memKey = MEM_KEY, semKey = SEM_KEY; // not sure if this is necessary
    char *memPtr;

    if ((seg_id = shmget(memKey, SEG_SIZE, IPC_CREAT | 0777)) < 0) // get segment ID
        oops("shmget", 1);

    if ((memPtr = shmat(seg_id, NULL, 0)) == (char *) -1) // attach the memory segment
        oops("shmat", 2);

    semset_id = semget(semKey, 2, ( 0666 | IPC_CREAT | IPC_EXCL )); // for some reason I couldn't include this in an if-statement
    // but it seems to work here in the server code
    if (semset_id == -1)
        oops("semset", 2.5);

    wait_and_lock( semset_id ); // this function was something our teacher went over with us.
    // I'm still a little confused with what it's doing.
    while(1)
    {
        printf("enter: "); // get the commands, is there a better way of doing this?
        scanf("%s", memPtr);
    }

    release_lock( semset_id );

    while (*memPtr != '*') // not sure if this is necessary, left over from old code that I was experimenting with.
        sleep(1);

    shmdt( memPtr ); // detach the memory

    exit(0);
}

void wait_and_lock( int semset_id )
{
    union semun sem_info;                     // some properties
    struct sembuf actions[2];                 // action set, an array

    actions[0].sem_num = 1;                   // sem[1] is n_writers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = 0;                    // wait for 0
    actions[1].sem_num = 0;                   // sem[0] is n_readers
    actions[1].sem_flg = SEM_UNDO;            // auto cleanup
    actions[1].sem_op = 1;                    // incr n_readers

    if ( semop( semset_id, actions, 2 ) == -1 )
        oops( "semop: locking", 10 );
}

void release_lock( int semset_id )
{
    union semun sem_info;                     // some properties
    struct sembuf actions[1];                 // action set

    actions[0].sem_num = 0;                   // sem[0] is n_readers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = -1;                   // decr reader country

    if ( semop( semset_id, actions, 1 ) == -1 )
        oops( "semop: unlocking", 10 );
}
</code>```

server.c:

```<code>#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/sem.h"
#include "signal.h"
#include "string.h"
#include <unistd.h>

#define MEM_KEY 99
#define SEM_KEY 1337
#define SEG_SIZE ( (size_t)100 )
#define oops( m, x ) { perror(m); exit(x); }

union semun { int val; struct semid_ds* buf; unsigned short* array; };
int seg_id, semset_id;
void cleanup( int );
void set_sem_value( int, int, int );
void wait_and_lock( int );
void release_lock( int );

int main()
{
    int id = 0;
    char *memPtr;
    key_t memKey = MEM_KEY, semKey = SEM_KEY;

    signal( SIGINT, cleanup ); // to handle Ctrl-C

    seg_id = shmget( memKey, SEG_SIZE, 0777 ); // get segment ID
    if( seg_id == -1 )
        oops( "shmget", 1 );

    if ((memPtr = shmat(seg_id, NULL, 0)) == (char *) -1) // attach to memPtr
        oops("shmat",2);

    semset_id = semget( semKey, 2, ( 0666 | IPC_CREAT | IPC_EXCL ) );
    // this is where there seems to be an issue? This is where the code stops.
    if ( semset_id == -1 )
        oops( "semget", 3 );

    set_sem_value( semset_id, 0, 0 ); // set counters
    set_sem_value( semset_id, 1, 0 ); // both to zero

//Now read what the client put in the memory (still not sure if this works
//because the program hasn't technically gotten that far. So this while loop is more
//of a prototype).
    while(1)
    {
        wait_and_lock( semset_id );

        printf( "\tshm_ts2 update memory\n" ); // will be removed at the end
        sleep(1);
        if(strcmp(memPtr, "HI")==0) // look for HI
        {
            printf("Greetings!\n"); // print this to the server screen
            fflush(stdout);
            memPtr[0] = '\0';

        }
        else if(strcmp(memPtr, "PID")==0) // look for PID and get server's PID
        {
            id = (int)getpid();
            printf("Server pid: %i\n", id);
            fflush(stdout);
            memPtr[0] = '\0';

        }
        else if(strcmp(memPtr, "QUIT")==0){ // check for quit
            shmctl(seg_id, IPC_RMID, NULL); // mark seg to be destroyed
            shmdt(memPtr); // detach segment
            printf("GOODBYE!\n");
            exit(0);
        }
        release_lock( semset_id );
        printf( "\tshm_ts2 released lock\n" ); // will be removed at the end
    }

    *memPtr = '*'; // still not sure if this is necessary, from old code
    cleanup(0);
    return 0;

}

void cleanup( int n )
{
    shmctl( seg_id, IPC_RMID, NULL );
    semctl( semset_id, 0, IPC_RMID, NULL );
}

void set_sem_value( int semset_id, int semnum, int val )
{
    union semun initval;

    initval.val = val;

    if ( semctl( semset_id, semnum, SETVAL, initval ) == -1 )
        oops( "semctl", 4 );
}

void wait_and_lock( int semset_id )
{
    struct sembuf actions[2];                 // action set, an array

    actions[0].sem_num = 0;                   // sem[0] is n_readers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = 0;                    // wait til no readers
    actions[1].sem_num = 1;                   // sem[1] is n_writers
    actions[1].sem_flg = SEM_UNDO;            // auto cleanup
    actions[1].sem_op = 1;                    // increment number of writers

    if ( semop( semset_id, actions, 2 ) == -1 )
        oops("semop: locking", 10 );
}

// Thing 4:  build and execute a 1-element action set: decrement num_writers
void release_lock( int semset_id )
{
    struct sembuf actions[1];                 // action set, an array
    actions[0].sem_num = 1;                   // sem[0] is n_writers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = -1;                   // decrement number of writer count

    if ( semop( semset_id, actions, 1 ) == -1 )
        oops( "semop: unlocking", 10 );
}
</code>```

答: You need to make a system V IPC key using the ftok function. Than, that key should be passed as the first parameter to the shmget system call. The same applies to semaphores. Make a System V IPC key using ftok and pass it as the first parameter to semget.</p>

Body:
So I'm currently writing a server/client program that will take in three commands (HI, PID and GOODBYE) and process them accordingly. I seem to have run into some trouble with my use of semget() in my server.c code.

The error that I'm getting is "EEXIST", which according to the man pages, says that the key already exists (duh lol) - the thing is, I keep manually changing the key each time and it still gives me the error. Am I not understanding something here? It also seems to work fine for the client.c code. Do any of you guys have an idea as to why I'm experiencing this?

Sorry for the somewhat sloppy code, I've been smashing my head on my keyboard all night over this, I'll do my best to comment out my thought processes. Let me know if there's anything I can do to make it easier to read.

client.c:

#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/sem.h"
#include "signal.h"
#include "string.h"
#include <unistd.h>

#define MEM_KEY 99 // memory key
#define SEM_KEY 1337 // semaphore key
#define SEG_SIZE ( (size_t)100 ) // segment size
#define oops( m, x ) { perror(m); exit(x); } // for error checking
int seg_id, semset_id;
union semun{ int val; struct semid_ds* buf; ushort* array; }; // for wait and release functions
void wait_and_lock( int );
void release_lock( int );

int main()
{
    char c;
    key_t memKey = MEM_KEY, semKey = SEM_KEY; // not sure if this is necessary
    char *memPtr;

    if ((seg_id = shmget(memKey, SEG_SIZE, IPC_CREAT | 0777)) < 0) // get segment ID
        oops("shmget", 1);

    if ((memPtr = shmat(seg_id, NULL, 0)) == (char *) -1) // attach the memory segment
        oops("shmat", 2);

    semset_id = semget(semKey, 2, ( 0666 | IPC_CREAT | IPC_EXCL )); // for some reason I couldn't include this in an if-statement
    // but it seems to work here in the server code
    if (semset_id == -1)
        oops("semset", 2.5);

    wait_and_lock( semset_id ); // this function was something our teacher went over with us.
    // I'm still a little confused with what it's doing.
    while(1)
    {
        printf("enter: "); // get the commands, is there a better way of doing this?
        scanf("%s", memPtr);
    }

    release_lock( semset_id );

    while (*memPtr != '*') // not sure if this is necessary, left over from old code that I was experimenting with.
        sleep(1);

    shmdt( memPtr ); // detach the memory

    exit(0);
}

void wait_and_lock( int semset_id )
{
    union semun sem_info;                     // some properties
    struct sembuf actions[2];                 // action set, an array

    actions[0].sem_num = 1;                   // sem[1] is n_writers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = 0;                    // wait for 0
    actions[1].sem_num = 0;                   // sem[0] is n_readers
    actions[1].sem_flg = SEM_UNDO;            // auto cleanup
    actions[1].sem_op = 1;                    // incr n_readers

    if ( semop( semset_id, actions, 2 ) == -1 )
        oops( "semop: locking", 10 );
}

void release_lock( int semset_id )
{
    union semun sem_info;                     // some properties
    struct sembuf actions[1];                 // action set

    actions[0].sem_num = 0;                   // sem[0] is n_readers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = -1;                   // decr reader country

    if ( semop( semset_id, actions, 1 ) == -1 )
        oops( "semop: unlocking", 10 );
}

server.c:

#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/sem.h"
#include "signal.h"
#include "string.h"
#include <unistd.h>

#define MEM_KEY 99
#define SEM_KEY 1337
#define SEG_SIZE ( (size_t)100 )
#define oops( m, x ) { perror(m); exit(x); }

union semun { int val; struct semid_ds* buf; unsigned short* array; };
int seg_id, semset_id;
void cleanup( int );
void set_sem_value( int, int, int );
void wait_and_lock( int );
void release_lock( int );

int main()
{
    int id = 0;
    char *memPtr;
    key_t memKey = MEM_KEY, semKey = SEM_KEY;

    signal( SIGINT, cleanup ); // to handle Ctrl-C

    seg_id = shmget( memKey, SEG_SIZE, 0777 ); // get segment ID
    if( seg_id == -1 )
        oops( "shmget", 1 );

    if ((memPtr = shmat(seg_id, NULL, 0)) == (char *) -1) // attach to memPtr
        oops("shmat",2);

    semset_id = semget( semKey, 2, ( 0666 | IPC_CREAT | IPC_EXCL ) );
    // this is where there seems to be an issue? This is where the code stops.
    if ( semset_id == -1 )
        oops( "semget", 3 );

    set_sem_value( semset_id, 0, 0 ); // set counters
    set_sem_value( semset_id, 1, 0 ); // both to zero

//Now read what the client put in the memory (still not sure if this works
//because the program hasn't technically gotten that far. So this while loop is more
//of a prototype).
    while(1)
    {
        wait_and_lock( semset_id );

        printf( "\tshm_ts2 update memory\n" ); // will be removed at the end
        sleep(1);
        if(strcmp(memPtr, "HI")==0) // look for HI
        {
            printf("Greetings!\n"); // print this to the server screen
            fflush(stdout);
            memPtr[0] = '\0';

        }
        else if(strcmp(memPtr, "PID")==0) // look for PID and get server's PID
        {
            id = (int)getpid();
            printf("Server pid: %i\n", id);
            fflush(stdout);
            memPtr[0] = '\0';

        }
        else if(strcmp(memPtr, "QUIT")==0){ // check for quit
            shmctl(seg_id, IPC_RMID, NULL); // mark seg to be destroyed
            shmdt(memPtr); // detach segment
            printf("GOODBYE!\n");
            exit(0);
        }
        release_lock( semset_id );
        printf( "\tshm_ts2 released lock\n" ); // will be removed at the end
    }

    *memPtr = '*'; // still not sure if this is necessary, from old code
    cleanup(0);
    return 0;

}

void cleanup( int n )
{
    shmctl( seg_id, IPC_RMID, NULL );
    semctl( semset_id, 0, IPC_RMID, NULL );
}

void set_sem_value( int semset_id, int semnum, int val )
{
    union semun initval;

    initval.val = val;

    if ( semctl( semset_id, semnum, SETVAL, initval ) == -1 )
        oops( "semctl", 4 );
}

void wait_and_lock( int semset_id )
{
    struct sembuf actions[2];                 // action set, an array

    actions[0].sem_num = 0;                   // sem[0] is n_readers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = 0;                    // wait til no readers
    actions[1].sem_num = 1;                   // sem[1] is n_writers
    actions[1].sem_flg = SEM_UNDO;            // auto cleanup
    actions[1].sem_op = 1;                    // increment number of writers

    if ( semop( semset_id, actions, 2 ) == -1 )
        oops("semop: locking", 10 );
}

// Thing 4:  build and execute a 1-element action set: decrement num_writers
void release_lock( int semset_id )
{
    struct sembuf actions[1];                 // action set, an array
    actions[0].sem_num = 1;                   // sem[0] is n_writers
    actions[0].sem_flg = SEM_UNDO;            // auto cleanup
    actions[0].sem_op = -1;                   // decrement number of writer count

    if ( semop( semset_id, actions, 1 ) == -1 )
        oops( "semop: unlocking", 10 );
}