问:
Data to save in Yii not working
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

```<code>public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}
</code>```

This is the code to save the new record:

```<code>public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}
</code>```

UPDATE:

I change the code like Yupik adviced to dump the error like below :

```<code>public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}
</code>```

But when I try to print $object->getErrors() in junk file, it displayed Array

答:
are u trying to save $object? if yes, wheres the syntax $object->save()?

```<code>public function actionEventReg()
{
    ....
        $object->date_added = time();
        $object->date_modified = time();
        **$object->save();**

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
       ...
    }
}
</code>```

try to put that $object->save();

Title: Data to save in Yii not working

Body:
I tried to save these test data into the database if the record haven't exist yet. But when I try to create new record, it returns fail. I'm not sure what's wrong.

This is the code to check whether the registration id exist or not:

public static function getEventRegistration($registration_code)
{
    $model = EventRegistration::model()->findByAttributes(array('registration_code'=>$registration_code));
        if($model!==null)
        return $model;
}

This is the code to save the new record:

public function actionEventReg()
{
    $tmps = HUB::getEventRegistration('999881');
    if(empty($tmps)){
        // echo 'record does not exist';

        //create new registration
        $object = new EventRegistration;
        $object->event_code = '206218';
        $object->event_vendor_code = 'bizzabo';
        $object->registration_code = '0123456';
        $object->full_name = 'test rifff';
        $object->first_name = 'test';
        $object->last_name = 'rifff';
        $object->email = 'rifhan@mymagic.my';
        $object->phone = '';
        $object->organization = '';
        $object->gender = '';
        $object->age_group = '';
        $object->where_found = '';
        $object->persona = '';
        $object->paid_fee = '';
        $object->is_attended = '';
        $object->date_registered = '';
        $object->date_payment = '';
        $object->json_original = '';
        $object->date_added = time();
        $object->date_modified = time();

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationNotExist-'.time();
        $junk->content = sprintf('successfully insert data: %s or (%s). With first name is %s and last name is %s', $success, $fail, $object->first_name, $object->last_name);
        $junk->save();
    }else{
        // echo 'record exist';

        //create junk
        $junk = new Junk;
        $junk->code = 'test-getRegistrationExist-'.time();
        $junk->content = sprintf('called on: %s with first name is %s and last name is %s', Yii::app()->params['masterDomain'], $tmps->first_name, $tmps->last_name);
        $junk->save();
    }
}

UPDATE:

I change the code like Yupik adviced to dump the error like below :

public function actionBizzaboCallback()
{
    $junk = new Junk;
    $junk->code = 'bizzabo-bizzaboCallback-'.time();

    $junk->content .= serialize($_POST);

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $objects = json_decode($json);

        // expecting valid json
        if (json_last_error() !== JSON_ERROR_NONE) {
            die(header('HTTP/1.0 415 Unsupported Media Type'));
        } else {
            // check if registration exist
            $tmps = HUB::getEventRegistrationByID($objects->details->items[0]->ticketId);

                if(empty($tmps)){
                    //1. echo 'record does not exist';

                    //2. create new registration
                    $object = new EventRegistration;
                    $object->event_code = $objects->eventId;
                    $object->event_vendor_code = 'bizzabo';
                    $object->registration_code = $objects->details->items[0]->ticketId;

                    $object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);

                    $object->first_name = $objects->details->items[0]->registrationForm->firstName;
                    $object->last_name = $objects->details->items[0]->registrationForm->lastName;
                    $object->email = $objects->details->items[0]->registrationForm->email;

                    $object->phone = 'null';
                    // $object->phone = $objects->details->items[0]->registrationForm->mobileNumber;
                    $object->organization = 'null';
                    //$object->organization = $objects->details->items[0]->registrationForm->organisation__instit;

                    $object->gender = 'unknown';
                     if(isset($objects->details->items[0]->registrationForm->gender))
                     {
                        if(stristr($objects->details->items[0]->registrationForm->gender, 'female'))
                        {
                            $gender = 'female';
                        }
                        else
                        {
                            if(stristr($objects->details->items[0]->registrationForm->gender, 'male'))
                            {
                                $gender = 'male';
                            }
                        }
                    }

                    $object->age_group = $objects->details->items[0]->registrationForm->age_group;

                    $object->where_found = $objects->details->items[0]->registrationForm->how_did_you_hear_abo;

                    $object->persona = $objects->details->items[0]->registrationForm->type_of_person;

                    $object->paid_fee = $objects->details->items[0]->registrationForm->ticketPaid;

                    $object->date_registered = $objects->details->items[0]->registrationForm->created;

                    $object->date_payment = $objects->details->items[0]->registrationForm->created;

                    $object->json_original = $json;

                    $object->date_added = time();
                    $object->date_modified = time();

                    if($object->save()){
                        $success = 'success';
                    }else{
                        var_dump($object->getErrors());
                        $fail = 'fail';
                    }

                    //3. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
                    $junk->content = sprintf('ticket id: %s does not exist. %s into database.', $objects->details->items[0]->ticketId, $fail);

                }else{
                    //1. echo 'record exist';

                    //2. create junk
                    $junk = new Junk;
                    $junk->code = 'bizzabo-getBizzaboRegistrationExisted-'.time();
                    $junk->content = sprintf('ticket id: %s does exist. Did not update into database.',$objects->details->items[0]->ticketId);
                }
            $junk->content .= sprintf('Get error : %s ', $object->getErrors());
        }
    }
    $junk->save();
}

But when I try to print $object->getErrors() in junk file, it displayed Array

Body:
are u trying to save $object? if yes, wheres the syntax $object->save()?

public function actionEventReg()
{
    ....
        $object->date_added = time();
        $object->date_modified = time();
        **$object->save();**

        if($object->save()){
            $success = 'success';
        }else{
            $fail = 'fail';
        }
       ...
    }
}

try to put that $object->save();


来源: stackexchange

问:
error: package com.google.android.gcm does not exist - After migrating to Gradle
I have a problem with an old project which was developed in IntelliJ without Gradle. I wanted to migrate it to Android Studio and Gradle, but I am experiencing a lot of problems. Since the project was quite old, the old Google Play Services version was used. In Intellij I had just added libproject of the old gps to dependencies (google_play_services_5089000_r19) and everything worked fine. In Android Studio I managed to add other libraries by adding it as a library module and adding compile project(':segmentedradios') as a gradle dependency, but I just can't make gps library work. I've tried to add it as a module, but Android Studio says that "no module selected" after pointing to libroject library's directory. I also tried to add it as a gradle dependency, but I am keep getting errors like these:

```<code>error: package com.google.android.gcm does not exist
error: package com.google.android.maps does not exist
error: cannot find symbol variable GCMRegistrar
</code>```

Despite I tried ~10 different solutions, the project still does not work. How to fix it?

Gradle:

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

android {
    compileSdkVersion "Google Inc.:Google APIs:18"
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "my_package.app_name"
        minSdkVersion 14
        targetSdkVersion 18
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
    compile project(':segmentedradios')
    compile 'com.google.android.gms:play-services:5.0.89'
}
</code>```

答:
You can download gcm.jar by this path

http://www.java2s.com/Code/Jar/g/Downloadgcmjar.htm

or this

http://www.java2s.com/Code/JarDownload/gcm/gcm.jar.zip

After you download it, unzip it, it should have extention .jar not .jar.zip

Then copy and paste it to libs dir in your project

Then right click on gcm.jar and click on add as lib

That is it

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with an old project which was developed in IntelliJ without Gradle. I wanted to migrate it to Android Studio and Gradle, but I am experiencing a lot of problems. Since the project was quite old, the old Google Play Services version was used. In Intellij I had just added libproject of the old gps to dependencies (google_play_services_5089000_r19) and everything worked fine. In Android Studio I managed to add other libraries by adding it as a library module and adding compile project(':segmentedradios') as a gradle dependency, but I just can't make gps library work. I've tried to add it as a module, but Android Studio says that "no module selected" after pointing to libroject library's directory. I also tried to add it as a gradle dependency, but I am keep getting errors like these:

error: package com.google.android.gcm does not exist
error: package com.google.android.maps does not exist
error: cannot find symbol variable GCMRegistrar

Despite I tried ~10 different solutions, the project still does not work. How to fix it?

Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion "Google Inc.:Google APIs:18"
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "my_package.app_name"
        minSdkVersion 14
        targetSdkVersion 18
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
    compile files('libs/libGoogleAnalyticsV2.jar')
    compile project(':segmentedradios')
    compile 'com.google.android.gms:play-services:5.0.89'
}


问:
Kaa sandbox building failed with binary demo application
I try download binary demo application from Kaa sandbox.

Eventually, I am faced with: BUILD FAILED

This is a "build exception" from Kaa sandbox:

Is this problem fixed with the Kaa 1.0.0 Banana Beach ?!

Thanks, Kaa IoT team.

答:
This is because the normal kaa deployment in AWS uses a t12 micro instance. This limits the kaa usage.  Once the limit is crossed this error will occur.

Creating a new instance will solve the problem. I was finding that the same thing was happening for me until I did so.


问:
import pyodbc not working in eclipse -python
as a continue to this

import pyodbc not working in eclipse

can any one please explain to me how the pyodbc import should look like ?
when i do

```<code>pip install pyodbc
</code>```

or

```<code> python -m pip install pyodbc-4.0.21-cp36-cp36m-win_amd64.whl
</code>```

all i get is a folder

```<code>pyodbc-4.0.21.dist-info
</code>```

which does not have any python files in it ...this is the content of the lib
lib content

is this is the right content? or there should be python files that need to be created some how

my problem is that eclipse does not recognize the import pyodbc

(getting Unresolved import: pyodbc )

UPDATE

when i open the consule from eclipse and writing

```<code>import pyodbc
</code>```

i am not getting any errors
just when doing import from the .py file (in the eclipse) i am getting the error
pleeeeeeeeese help

答:
just to update (if some else might need it... ) after spending alot of time on this ... the error is just a displayed error !! the code is running even with this error , this is very wierd but this is the case...
also it is possible to press cntl + 1  and in the pop up screen choose "UnresolvedImport"

or just add at the end of the import - this will remove the red error and will do the import...

```<code>import pyodbc  # @UnresolvedImport
</code>```

Body:
as a continue to this

import pyodbc not working in eclipse

can any one please explain to me how the pyodbc import should look like ?
when i do

pip install pyodbc

or

 python -m pip install pyodbc-4.0.21-cp36-cp36m-win_amd64.whl

all i get is a folder

pyodbc-4.0.21.dist-info

which does not have any python files in it ...this is the content of the lib
lib content

is this is the right content? or there should be python files that need to be created some how

my problem is that eclipse does not recognize the import pyodbc

(getting Unresolved import: pyodbc )

UPDATE

when i open the consule from eclipse and writing

import pyodbc

i am not getting any errors
just when doing import from the .py file (in the eclipse) i am getting the error
pleeeeeeeeese help

Body:
just to update (if some else might need it... ) after spending alot of time on this ... the error is just a displayed error !! the code is running even with this error , this is very wierd but this is the case...
also it is possible to press cntl + 1  and in the pop up screen choose "UnresolvedImport"

or just add at the end of the import - this will remove the red error and will do the import...

import pyodbc  # @UnresolvedImport


问:
FirebaseListAdapter<> Not Working
I am following this tutorial to create a chat app. This is my displayChatMessages() method:

ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessages>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessages model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView)v.findViewById(R.id.message_text);
            TextView messageTime = (TextView)v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageBody());
            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);
```

<p>But I get a red underline at this part: </p>

<pre class="lang-java prettyprint-override"><code>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference())
</code>```

Android Studio says

Firebaselistadapter() in Firebaselistadapter cannot be applied to...

UPDATE: This is the error message:

Error:(76, 19) error: constructor FirebaseListAdapter in class FirebaseListAdapter cannot be applied to given types;
  required: FirebaseListOptions
  found: MainActivity,Class,int,DatabaseReference
  reason: actual and formal argument lists differ in length
  where T is a type-variable:
  T extends Object declared in class FirebaseListAdapter

答:
Thanks for complete error message - this helps greatly.
Based on that, I think this is what you need to do.

```<code>//Suppose you want to retrieve "chats" in your Firebase DB:
Query query = FirebaseDatabase.getInstance().getReference().child("chats");
//The error said the constructor expected FirebaseListOptions - here you create them:
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
                    .setQuery(query, ChatMessages.class)
                     .setLayout(android.R.layout.message)
                    .build();
    //Finally you pass them to the constructor here:
 adapter = new FirebaseListAdapter<ChatMessages>(options){
    @Override
    protected void populateView(View v, ChatMessages model, int position) {
        // Get references to the views of message.xml
        TextView messageText = (TextView)v.findViewById(R.id.message_text);
        TextView messageTime = (TextView)v.findViewById(R.id.message_time);

        // Set their text
        messageText.setText(model.getMessageBody());
        // Format the date before showing it
        messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
    }
 };
</code>```

Here is an article where the same issue was encountered.

Title: FirebaseListAdapter<> Not Working

Body:
I am following this tutorial to create a chat app. This is my displayChatMessages() method:

ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessages>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessages model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView)v.findViewById(R.id.message_text);
            TextView messageTime = (TextView)v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageBody());
            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);

But I get a red underline at this part:

(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference())

Android Studio says

Firebaselistadapter() in Firebaselistadapter cannot be applied to...

UPDATE: This is the error message:

Error:(76, 19) error: constructor FirebaseListAdapter in class FirebaseListAdapter cannot be applied to given types;
  required: FirebaseListOptions
  found: MainActivity,Class,int,DatabaseReference
  reason: actual and formal argument lists differ in length
  where T is a type-variable:
  T extends Object declared in class FirebaseListAdapter

Body:
Thanks for complete error message - this helps greatly.
Based on that, I think this is what you need to do.

//Suppose you want to retrieve "chats" in your Firebase DB:
Query query = FirebaseDatabase.getInstance().getReference().child("chats");
//The error said the constructor expected FirebaseListOptions - here you create them:
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
                    .setQuery(query, ChatMessages.class)
                     .setLayout(android.R.layout.message)
                    .build();
    //Finally you pass them to the constructor here:
 adapter = new FirebaseListAdapter<ChatMessages>(options){
    @Override
    protected void populateView(View v, ChatMessages model, int position) {
        // Get references to the views of message.xml
        TextView messageText = (TextView)v.findViewById(R.id.message_text);
        TextView messageTime = (TextView)v.findViewById(R.id.message_time);

        // Set their text
        messageText.setText(model.getMessageBody());
        // Format the date before showing it
        messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
    }
 };

Here is an article where the same issue was encountered.


问:
How to develop compiler without compiler writing tools
My teacher gave this question ( how to develop compilers without compiler writing tools ). I searched for it but I did not find anything. So, If anyone have any idea about this please help me. I found so many information about developing compiler with writing tools but I found nothing when I searched for without compiler writing tools.

Thank you in advance.

答:
A compiler is basically a filter/converter. It reads text files and outputs data that happens to be identical to the instructions the given CPU understands.

So you need to find out:

what assembler code your source language‘s commands are equivalent to

what byte sequences each of these assembler commands are equivalent to

Then you can read the source file and output compiled code.


问:
Formatter issue when language changed in device
I'm trying to get float number from amount string with out currency symbol like "100.00". Its working properly in English language. When language changed to German in device, its behaviour is getting changed. How can I achieve float value with out affecting by language change in device.

```<code>func getFloatNumberFromString(_ str: String) -> Float {
        guard let number = NumberFormatter().number(from: str) else {
            return 0.0
        }

        return number.floatValue
    }
</code>```

another piece of below code to deal with it:

```<code>    func removeFormatAmount() -> Double {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self) as! Double? ?? 0
   }
</code>```

When I use second method then the output is coming as 0.

Please let me know what am I missing or suggest me to deal with it.
Thanks in advance

答:
In many European countries the decimal separator is a comma rather than a dot.

You could set the Locale of the formatter to a fixed value.

```<code>func float(from str: String) -> Float {
    let formatter = NumberFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    guard let number = formatter.number(from: str) else {
        return 0.0
    }

    return number.floatValue
}
</code>```

PS: I changed the signature to fit the Swift 3+ style

Body:
I'm trying to get float number from amount string with out currency symbol like "100.00". Its working properly in English language. When language changed to German in device, its behaviour is getting changed. How can I achieve float value with out affecting by language change in device.

func getFloatNumberFromString(_ str: String) -> Float {
        guard let number = NumberFormatter().number(from: str) else {
            return 0.0
        }

        return number.floatValue
    }

another piece of below code to deal with it:

    func removeFormatAmount() -> Double {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self) as! Double? ?? 0
   }

When I use second method then the output is coming as 0.

Please let me know what am I missing or suggest me to deal with it.
Thanks in advance

Body:
In many European countries the decimal separator is a comma rather than a dot.

You could set the Locale of the formatter to a fixed value.

func float(from str: String) -> Float {
    let formatter = NumberFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    guard let number = formatter.number(from: str) else {
        return 0.0
    }

    return number.floatValue
}

PS: I changed the signature to fit the Swift 3+ style


问:
lagom-javadsl-api not found in SBT project
I'm new to Lagom and SBT and I'm trying to execute my first project using IntelliJ.

The structure of my project is:

My SBT version is:

```<code>sbt.version = 0.13.16
</code>```

The plugins.sbt file contains:

```<code>// The Lagom plugin
addSbtPlugin("com.lightbend.lagom" % "lagom-sbt-plugin" % "1.3.10")
// Needed for importing the project into Eclipse
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.1.0")
</code>```

And the build.sbt file contains:

```<code>name := "testsbt"

version := "1.0-SNAPSHOT"

scalaVersion := "2.12.3"

lazy val `hello-lagom` = (project in file("."))
  .aggregate(`user-api`, `user-impl`)

lazy val `user-api` = (project in file("user-api"))
  .settings(
    libraryDependencies += lagomJavadslApi
  )

lazy val `user-impl` = (project in file("user-impl"))
  .enablePlugins(LagomJava)
  .dependsOn(`user-api`)
</code>```

The problem is when I tried to build the project I got this error:

sbt.ResolveException: unresolved dependency:
com.lightbend.lagom#lagom-javadsl-api_2.10;1.3.10: not found

[error] (user-api/*:update) sbt.ResolveException: unresolved dependency:
com.lightbend.lagom#lagom-javadsl-api_2.10;1.3.10: not found

I also had some warnings like:

[info] Done updating.

[warn] Found version conflict(s) in librarydependencies; some are suspected to be binary incompatible:

[warn]    * org.jboss.logging:jboss-logging:3.3.0.Final is selected over
3.2.1.Final

[warn]        +- com.lightbend.lagom:lagom-javadsl-api_2.11:1.3.10
(depends on 3.2.1.Final)

[warn]        +- org.hibernate:hibernate-validator:5.2.4.Final

(depends on  3.2.1.Final)

[warn]   * io.netty:netty-codec-http:4.0.51.Final is selected over
4.0.41.Final

[warn]        +- com.lightbend.lagom:lagom-service-locator_2.11:1.3.10
(depends on 4.0.51.Final)

[warn]        +- com.lightbend.lagom:lagom-client_2.11:1.3.10

(depends on 4.0.51.Final)

[warn]        +- org.asynchttpclient:async-http-client:2.0.36

(depends on 4.0.51.Final)

[warn]        +- com.typesafe.netty:netty-reactive-streams-http:1.0.8
(depends on 4.0.41.Final)

I can't undresting why sbt can't find lagom-javadsl-api dependency. Did I miss something ?

Thanks for helping.

答:
You need to set:

```<code>scalaVersion in ThisBuild := "2.11.12"
</code>```

This ensures that it gets set for the entire build, rather than just being set for the root project. If it's just set for the root project, then you get the default Scala version, which for sbt 0.13 is 2.10. Also, Lagom 1.3 is not cross built against Scala 2.12, so you have to use 2.11.

Body:
I'm new to Lagom and SBT and I'm trying to execute my first project using IntelliJ.

The structure of my project is:

My SBT version is:

sbt.version = 0.13.16

The plugins.sbt file contains:

// The Lagom plugin
addSbtPlugin("com.lightbend.lagom" % "lagom-sbt-plugin" % "1.3.10")
// Needed for importing the project into Eclipse
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.1.0")

And the build.sbt file contains:

name := "testsbt"

version := "1.0-SNAPSHOT"

scalaVersion := "2.12.3"

lazy val `hello-lagom` = (project in file("."))
  .aggregate(`user-api`, `user-impl`)

lazy val `user-api` = (project in file("user-api"))
  .settings(
    libraryDependencies += lagomJavadslApi
  )

lazy val `user-impl` = (project in file("user-impl"))
  .enablePlugins(LagomJava)
  .dependsOn(`user-api`)

The problem is when I tried to build the project I got this error:

sbt.ResolveException: unresolved dependency:
com.lightbend.lagom#lagom-javadsl-api_2.10;1.3.10: not found

[error] (user-api/*:update) sbt.ResolveException: unresolved dependency:
com.lightbend.lagom#lagom-javadsl-api_2.10;1.3.10: not found

I also had some warnings like:

[info] Done updating.

[warn] Found version conflict(s) in librarydependencies; some are suspected to be binary incompatible:

[warn]    * org.jboss.logging:jboss-logging:3.3.0.Final is selected over
3.2.1.Final

[warn]        +- com.lightbend.lagom:lagom-javadsl-api_2.11:1.3.10
(depends on 3.2.1.Final)

[warn]        +- org.hibernate:hibernate-validator:5.2.4.Final

(depends on  3.2.1.Final)

[warn]   * io.netty:netty-codec-http:4.0.51.Final is selected over
4.0.41.Final

[warn]        +- com.lightbend.lagom:lagom-service-locator_2.11:1.3.10
(depends on 4.0.51.Final)

[warn]        +- com.lightbend.lagom:lagom-client_2.11:1.3.10

(depends on 4.0.51.Final)

[warn]        +- org.asynchttpclient:async-http-client:2.0.36

(depends on 4.0.51.Final)

[warn]        +- com.typesafe.netty:netty-reactive-streams-http:1.0.8
(depends on 4.0.41.Final)

I can't undresting why sbt can't find lagom-javadsl-api dependency. Did I miss something ?

Thanks for helping.

Body:
You need to set:

scalaVersion in ThisBuild := "2.11.12"

This ensures that it gets set for the entire build, rather than just being set for the root project. If it's just set for the root project, then you get the default Scala version, which for sbt 0.13 is 2.10. Also, Lagom 1.3 is not cross built against Scala 2.12, so you have to use 2.11.


问:
Can't open database-Android
I'm developing a simple Android application with SQL.
I followed the following guides -
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

I get an error when trying to open the database.
Here is my DataBaseHelp.Java Class-

```<code>public class DataBaseHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/and.testDB/databases/";

private static String DB_NAME = "MyData";

private SQLiteDatabase myDataBase;

private final Context myContext;
public DataBaseHelper(Context context) {

 super(context, DB_NAME, null, 1);
    this.myContext = context;
}
public void createDataBase() throws IOException{

 boolean dbExist = checkDataBase();

 if(dbExist){
  //do nothing - database already exist
 }else{
     this.getReadableDatabase();

     try {

   copyDataBase();

  } catch (IOException e) {

      throw new Error("Error copying database");

     }
 }

}

private boolean checkDataBase(){

 SQLiteDatabase checkDB = null;

 try{
  String myPath = DB_PATH + DB_NAME;
  checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

 }catch(SQLiteException e){

  //database does't exist yet.

 }

 if(checkDB != null){

  checkDB.close();

 }

 return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{

 //Open your local db as the input stream
 InputStream myInput = myContext.getAssets().open(DB_NAME);

 // Path to the just created empty db
 String outFileName = DB_PATH + DB_NAME;

 //Open the empty db as the output stream
 OutputStream myOutput = new FileOutputStream(outFileName);

 //transfer bytes from the inputfile to the outputfile
 byte[] buffer = new byte[1024];
 int length;
 while ((length = myInput.read(buffer))>0){
  myOutput.write(buffer, 0, length);
 }

 //Close the streams
 myOutput.flush();
 myOutput.close();
 myInput.close();

}

public void openDataBase() {

 //Open the database
    String myPath = DB_PATH + DB_NAME;
 myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
 public synchronized void close() {
         if(myDataBase != null)
          myDataBase.close();
         super.close();
 }
 @Override
 public void onCreate(SQLiteDatabase db) {
 }
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}
</code>```

And this is my testDB.Java class-

```<code>public class testDB extends Activity {
SQLiteDatabase myDataBase;
public String[] gur = new String[4];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DataBaseHelper myDbHelper = new DataBaseHelper(this);
    myDbHelper = new DataBaseHelper(this);

    try {

        myDbHelper.createDataBase();

} catch (IOException ioe) {

    throw new Error("Unable to create database");

}

try {

    myDbHelper.openDataBase();
// Here is the problem-Can't open the database/
}catch(SQLException sqle){

    throw sqle;

}
    myDataBase = myDbHelper.getWritableDatabase();

    Cursor c = myDataBase.rawQuery("SELECT * FROM beer", null);

if (c != null ) {
    if  (c.moveToFirst()) {
          for(int x=0;x< 1;x++)
          {

              gur[x] = (c.getString(c.getColumnIndex("name")));
              c.moveToNext();
          }
}
    Toast.makeText(this,gur[0],Toast.LENGTH_LONG).show();
}

        }
    }
</code>```

I created the database using SQLite Database Browser, created a table named "beer", added 2 rows and put it in the /assests folder in my project.

Please note that i'm new to SQL, and its my first time using it. I searched all day for an answer and couldn't find one.

Thanks!

答:
You need to create the database in the onCreate method of your database helper (the extension of SQLiteOpenHelper). Your call to getReadableDatabase() won't return anything until a database has been created in the context of the application.

```<code>db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "foo TEXT, bar TEXT);");
</code>```

Something along those lines. Obviously fill in your own data scheme.

Then you can read the data from the database you have in your assets folder and insert them into the database using the sqlite commands.

Here's a tutorial that I used to get started:

http://www.devx.com/wireless/Article/40842

ContentLicense: CC BY-SA 2.5

Title: Can't open database-Android

Body:
I'm developing a simple Android application with SQL.
I followed the following guides -
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

I get an error when trying to open the database.
Here is my DataBaseHelp.Java Class-

public class DataBaseHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/and.testDB/databases/";

private static String DB_NAME = "MyData";

private SQLiteDatabase myDataBase;

private final Context myContext;
public DataBaseHelper(Context context) {

 super(context, DB_NAME, null, 1);
    this.myContext = context;
}
public void createDataBase() throws IOException{

 boolean dbExist = checkDataBase();

 if(dbExist){
  //do nothing - database already exist
 }else{
     this.getReadableDatabase();

     try {

   copyDataBase();

  } catch (IOException e) {

      throw new Error("Error copying database");

     }
 }

}

private boolean checkDataBase(){

 SQLiteDatabase checkDB = null;

 try{
  String myPath = DB_PATH + DB_NAME;
  checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

 }catch(SQLiteException e){

  //database does't exist yet.

 }

 if(checkDB != null){

  checkDB.close();

 }

 return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{

 //Open your local db as the input stream
 InputStream myInput = myContext.getAssets().open(DB_NAME);

 // Path to the just created empty db
 String outFileName = DB_PATH + DB_NAME;

 //Open the empty db as the output stream
 OutputStream myOutput = new FileOutputStream(outFileName);

 //transfer bytes from the inputfile to the outputfile
 byte[] buffer = new byte[1024];
 int length;
 while ((length = myInput.read(buffer))>0){
  myOutput.write(buffer, 0, length);
 }

 //Close the streams
 myOutput.flush();
 myOutput.close();
 myInput.close();

}

public void openDataBase() {

 //Open the database
    String myPath = DB_PATH + DB_NAME;
 myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
 public synchronized void close() {
         if(myDataBase != null)
          myDataBase.close();
         super.close();
 }
 @Override
 public void onCreate(SQLiteDatabase db) {
 }
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}

And this is my testDB.Java class-

public class testDB extends Activity {
SQLiteDatabase myDataBase;
public String[] gur = new String[4];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DataBaseHelper myDbHelper = new DataBaseHelper(this);
    myDbHelper = new DataBaseHelper(this);

    try {

        myDbHelper.createDataBase();

} catch (IOException ioe) {

    throw new Error("Unable to create database");

}

try {

    myDbHelper.openDataBase();
// Here is the problem-Can't open the database/
}catch(SQLException sqle){

    throw sqle;

}
    myDataBase = myDbHelper.getWritableDatabase();

    Cursor c = myDataBase.rawQuery("SELECT * FROM beer", null);

if (c != null ) {
    if  (c.moveToFirst()) {
          for(int x=0;x< 1;x++)
          {

              gur[x] = (c.getString(c.getColumnIndex("name")));
              c.moveToNext();
          }
}
    Toast.makeText(this,gur[0],Toast.LENGTH_LONG).show();
}

        }
    }

I created the database using SQLite Database Browser, created a table named "beer", added 2 rows and put it in the /assests folder in my project.

Please note that i'm new to SQL, and its my first time using it. I searched all day for an answer and couldn't find one.

Thanks!

Body:
You need to create the database in the onCreate method of your database helper (the extension of SQLiteOpenHelper). Your call to getReadableDatabase() won't return anything until a database has been created in the context of the application.

db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "foo TEXT, bar TEXT);");

Something along those lines. Obviously fill in your own data scheme.

Then you can read the data from the database you have in your assets folder and insert them into the database using the sqlite commands.

Here's a tutorial that I used to get started:

http://www.devx.com/wireless/Article/40842


问:
In Odoo8, how do I import a module's .py file into a custom module?
Ok, so here comes. Brace yourselves.

I'm trying to overwrite a method (get_followup_table_html) from a class (res_partner) located in a module (account_followup) in Odoo 8, by creating a custom module (account_followup_upgrade) that inherits the class and defines and redefines the method.

The changes are very small, as the method's only purpose is to create an html table to be included in emails sent to customers; I have just copied the original method and modified the html code parts.

That being said, it works, mostly. My files, in my custom module's folder, include:

__openerp__.py (not full file, just the important bit):

```<code>'depends': ['account_followup'],
</code>```

__init__.py:

```<code> # -*- coding: utf-8 -*-

import mymodule
</code>```

mymodule.py:

```<code># -*- coding: utf-8 -*-

from openerp.osv import osv

# I need to modify a method in this class
class res_partner(osv.osv):
    # So I inherit it
    _inherit = 'res.partner'

    # And define a method called the same as the original, with the same arguments
    def get_followup_table_html(self, cr, uid, ids, context=None):

        """
        Build the html tables to be included in emails send to partners,
        when reminding them their overdue invoices.
        :param ids: [id] of the partner for whom we are building the tables
        :rtype: string
        """

        try:
            from report import account_followup_print
        except ImportError:
            return 'import failed'

        # The code that follows generates an html table
        assert len(ids) == 1
        if context is None:
            context = {}
        partner = self.browse(cr, uid, ids[0], context=context).commercial_partner_id
        #copy the context to not change global context. Overwrite it because _() looks for the lang in local variable 'context'.
        #Set the language to use = the partner language
        context = dict(context, lang=partner.lang)
        followup_table = ''
        if partner.unreconciled_aml_ids:
            company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
            current_date = fields.date.context_today(self, cr, uid, context=context)
            rml_parse = account_followup_print.report_rappel(cr, uid, "followup_rml_parser")
            final_res = rml_parse._lines_get_with_partner(partner, company.id)

            for currency_dict in final_res:
                currency = currency_dict.get('line', [{'currency_id': company.currency_id}])[0]['currency_id']
                # My changes start here
                followup_table += '''
                <table border="0" width=100%>
                <tr style="background-color:#ea6153;color:White">
                    <td><b>''' + _("Invoice Date") + '''</b></td>
                    <td><b>''' + _("Description") + '''</b></td>
                    <td><b>''' + _("Due Date") + '''</b></td>
                    <td><b>''' + _("Amount") + " (%s)" % (currency.symbol) + '''</b></td>
                </tr>
                '''
                total = 0
                strbegin = "<TD>"
                strend = "</TD>"
                empty_cell = strbegin + strend
                for aml in currency_dict['line']:
                    date = aml['date_maturity'] or aml['date']
                    if date <= current_date and aml['balance'] > 0:
                        total += aml['balance']
                        followup_table +="<TR>" + strbegin + str(aml['date']) + strend + strbegin + aml['name'] + strend + strbegin + str(date) + strend + strbegin + '{0:.2f}'.format(aml['balance']) + strend + "</TR>"

                #total = reduce(lambda x, y: x+y['balance'], currency_dict['line'], 0.00)
                followup_table +='''<TR style="background-color:#e9e9e9">''' + empty_cell + empty_cell + strbegin +"<B>TOTAL</B>" + strend + strbegin + "<B>"  + '{0:.2f}'.format(total) + "</B>" + strend + "</TR>"
                followup_table +="</table>"

        return followup_table
</code>```

Now, I know the module is working as a I get 'import error' inside my emails, it is actually overwriting the original method (otherwise I would get a working, if ugly, html table). The problem is the import:

```<code>from report import account_followup_print
</code>```

This file, account_followup_print.py, is located inside the folder report, in the original account_followup module, and I don't know how to import it (or inherit it). I need it because it is called once during the html table generation...

How can I reference this file from my custom module?

I know this is a wall of text, so thank you for reading!

答:
To import it use the full path

from openerp.addons.account_followup.report import account_followup_print
```

I Think this will work but if not just change it a little bit and it will work
you need to specify the full path to the model report
take a look at this question too:

Odoo overwrite inherited method

Body:
Ok, so here comes. Brace yourselves.

I'm trying to overwrite a method (get_followup_table_html) from a class (res_partner) located in a module (account_followup) in Odoo 8, by creating a custom module (account_followup_upgrade) that inherits the class and defines and redefines the method.

The changes are very small, as the method's only purpose is to create an html table to be included in emails sent to customers; I have just copied the original method and modified the html code parts.

That being said, it works, mostly. My files, in my custom module's folder, include:

__openerp__.py (not full file, just the important bit):

'depends': ['account_followup'],

__init__.py:

 # -*- coding: utf-8 -*-

import mymodule

mymodule.py:

# -*- coding: utf-8 -*-

from openerp.osv import osv

# I need to modify a method in this class
class res_partner(osv.osv):
    # So I inherit it
    _inherit = 'res.partner'

    # And define a method called the same as the original, with the same arguments
    def get_followup_table_html(self, cr, uid, ids, context=None):

        """
        Build the html tables to be included in emails send to partners,
        when reminding them their overdue invoices.
        :param ids: [id] of the partner for whom we are building the tables
        :rtype: string
        """

        try:
            from report import account_followup_print
        except ImportError:
            return 'import failed'

        # The code that follows generates an html table
        assert len(ids) == 1
        if context is None:
            context = {}
        partner = self.browse(cr, uid, ids[0], context=context).commercial_partner_id
        #copy the context to not change global context. Overwrite it because _() looks for the lang in local variable 'context'.
        #Set the language to use = the partner language
        context = dict(context, lang=partner.lang)
        followup_table = ''
        if partner.unreconciled_aml_ids:
            company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
            current_date = fields.date.context_today(self, cr, uid, context=context)
            rml_parse = account_followup_print.report_rappel(cr, uid, "followup_rml_parser")
            final_res = rml_parse._lines_get_with_partner(partner, company.id)

            for currency_dict in final_res:
                currency = currency_dict.get('line', [{'currency_id': company.currency_id}])[0]['currency_id']
                # My changes start here
                followup_table += '''

                    ''' + _("Invoice Date") + '''
                    ''' + _("Description") + '''
                    ''' + _("Due Date") + '''
                    ''' + _("Amount") + " (%s)" % (currency.symbol) + '''

                '''
                total = 0
                strbegin = ""
                strend = "	"
                empty_cell = strbegin + strend
                for aml in currency_dict['line']:
                    date = aml['date_maturity'] or aml['date']
                    if date <= current_date and aml['balance'] > 0:
                        total += aml['balance']
                        followup_table +="
" + strbegin + str(aml['date']) + strend + strbegin + aml['name'] + strend + strbegin + str(date) + strend + strbegin + '{0:.2f}'.format(aml['balance']) + strend + "
"

                #total = reduce(lambda x, y: x+y['balance'], currency_dict['line'], 0.00)
                followup_table +='''
''' + empty_cell + empty_cell + strbegin +"TOTAL" + strend + strbegin + ""  + '{0:.2f}'.format(total) + "" + strend + "
"
                followup_table +="
"

        return followup_table

Now, I know the module is working as a I get 'import error' inside my emails, it is actually overwriting the original method (otherwise I would get a working, if ugly, html table). The problem is the import:

from report import account_followup_print

This file, account_followup_print.py, is located inside the folder report, in the original account_followup module, and I don't know how to import it (or inherit it). I need it because it is called once during the html table generation...

How can I reference this file from my custom module?

I know this is a wall of text, so thank you for reading!

Body:
To import it use the full path

from openerp.addons.account_followup.report import account_followup_print

I Think this will work but if not just change it a little bit and it will work
you need to specify the full path to the model report
take a look at this question too:

Odoo overwrite inherited method


问:
Jave - method is - parseByte(String s, int radix) - I can't understand it
This is an example the tutorial gives me. I cannot understand the answer - Parse byte value of 123 is 83 Parse byte value of -1a is -26. Please try to explain the method to me in a very simple way.</p>

```<code>import java.lang.*;

public class ByteDemo {

   public static void main(String[] args) {

      // create 2 byte primitives bt1, bt2
      byte bt1, bt2;

      // create and assign values to String's s1, s2
      String s1 = "123";
      String s2 = "-1a";

      // create and assign values to int r1, r2
      int r1 = 8;  // represents octal
      int r2 = 16; // represents hexadecimal

      /**
       *  static method is called using class name. Assign parseByte
       *  result on s1, s2 to bt1, bt2 using radix r1, r2
       */
      bt1 = Byte.parseByte(s1, r1);
      bt2 = Byte.parseByte(s2, r2);

      String str1 = "Parse byte value of " + s1 + " is " + bt1;
      String str2 = "Parse byte value of " + s2 + " is " + bt2;

      // print bt1, bt2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}
</code>```

答:
The first value, 123, is interpreted as an octal number, i.e. a number with base 8.

Now 1 * 8^2 + 2 * 8 + 3 = 64 + 16 + 3 = 83

The second value, -1a, is interpreted as a hexadecimal number, i.e. a number with base 16. Due to the fact that we only have 10 symbols for digits (0, .., 9), the symbols a,b,c,d,e,f are used to represent digits with a decimal value larger than 9. So a(16) = 10(10), b(16) = 11(10) and so on.

And - (1 * 16 + 10) = -26

Body:
This is an example the tutorial gives me. I cannot understand the answer - Parse byte value of 123 is 83 Parse byte value of -1a is -26. Please try to explain the method to me in a very simple way.

import java.lang.*;

public class ByteDemo {

   public static void main(String[] args) {

      // create 2 byte primitives bt1, bt2
      byte bt1, bt2;

      // create and assign values to String's s1, s2
      String s1 = "123";
      String s2 = "-1a";

      // create and assign values to int r1, r2
      int r1 = 8;  // represents octal
      int r2 = 16; // represents hexadecimal

      /**
       *  static method is called using class name. Assign parseByte
       *  result on s1, s2 to bt1, bt2 using radix r1, r2
       */
      bt1 = Byte.parseByte(s1, r1);
      bt2 = Byte.parseByte(s2, r2);

      String str1 = "Parse byte value of " + s1 + " is " + bt1;
      String str2 = "Parse byte value of " + s2 + " is " + bt2;

      // print bt1, bt2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}


问:
jQuery to Vanilla JS - querySelector issues
I'm going through some code and working to change all of the jQuery to vanilla JS. However there is one section and I keep getting an error in my console that says either:

TypeError: document.querySelectorAll(...).toggle is not a function pr
  TypeError: document.querySelectorAll(...) is null

Below is my code, the top part you can see is where I am trying to change the jquery to vanilla js (I have commented out the jquery) :

```<code>console.log(shipmentNumbers);
            for (let i = 0; i < shipmentNumbers.length; i += 1) {
                let sNumber = shipmentNumbers[i];

                function getHistory(event) {
                    console.log(event);
                    document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
                    // $('#shipment' + sNumber + ' tr.show-history' + sNumber).toggle();
                    document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';
                    // $('.overlay-line' + sNumber).css({
                    //  "display": "table-row"
                    // });
                    if (flag == false) {
                        let shipmentNumber = event.currentTarget.id.replace('status', '');
                        console.log('shipmentNumber=', shipmentNumber);
                        callHistoryApi(clientId, shipmentNumber);
                        $(this).find('.expand' + sNumber).html("▼");
                        flag = true;
                    } else {
                        $(this).find('.expand' + sNumber).html("►");
                        $('.overlay-line' + sNumber).css({
                            "display": "none"
                        });
                        flag = false;
                    }
                }
</code>```

Can someone explain why this isn't working, and how I can get it working using vanilla js?

答:
You must add check in whenever you do this, as .querySelctor/All() is going to return "null" if no elements are found.

```<code>var myCollection = document.querySelectorAll("selector");
if (myCollection.length > 0){
   Array.prototype.forEach.call(myCollenction, function(element){
      if(typeof element.toggle === "function"){
         element.toggle();
      }
   })
}
</code>```

More or less this will help you achieve your goal. However if you don't have method "toggle" defined on your elements - nothing will happen. :)

Body:
I'm going through some code and working to change all of the jQuery to vanilla JS. However there is one section and I keep getting an error in my console that says either:

TypeError: document.querySelectorAll(...).toggle is not a function pr
  TypeError: document.querySelectorAll(...) is null

Below is my code, the top part you can see is where I am trying to change the jquery to vanilla js (I have commented out the jquery) :

console.log(shipmentNumbers);
            for (let i = 0; i < shipmentNumbers.length; i += 1) {
                let sNumber = shipmentNumbers[i];

                function getHistory(event) {
                    console.log(event);
                    document.querySelectorAll('#shipment' + sNumber + 'tr.show-history' + sNumber).toggle();
                    // $('#shipment' + sNumber + ' tr.show-history' + sNumber).toggle();
                    document.getElementsByClassName('overlay-line' + sNumber).style.display = 'table-row';
                    // $('.overlay-line' + sNumber).css({
                    //  "display": "table-row"
                    // });
                    if (flag == false) {
                        let shipmentNumber = event.currentTarget.id.replace('status', '');
                        console.log('shipmentNumber=', shipmentNumber);
                        callHistoryApi(clientId, shipmentNumber);
                        $(this).find('.expand' + sNumber).html("▼");
                        flag = true;
                    } else {
                        $(this).find('.expand' + sNumber).html("►");
                        $('.overlay-line' + sNumber).css({
                            "display": "none"
                        });
                        flag = false;
                    }
                }

Can someone explain why this isn't working, and how I can get it working using vanilla js?

Body:
You must add check in whenever you do this, as .querySelctor/All() is going to return "null" if no elements are found.

var myCollection = document.querySelectorAll("selector");
if (myCollection.length > 0){
   Array.prototype.forEach.call(myCollenction, function(element){
      if(typeof element.toggle === "function"){
         element.toggle();
      }
   })
}

More or less this will help you achieve your goal. However if you don't have method "toggle" defined on your elements - nothing will happen. :)


问:
PHP not return correct number of nodes in XML-file

I'm trying to delete certain nodes from an XML-file using PHP, for some reason it was not working properly and I came to the conclusion that that's probably the case, because PHP is not returning the correct number of nodes, that are in said XML-file.

This is the XML-File:

```<code><?xml version="1.0"?>
<Filenames>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
</Filenames>
</code>```

...and so on (the file is way longer, but I'm always using the same name for nodes etc., you get the point)

Since deleting certain nodes did not work out, I tried just getting the information from the xml-file first and I tried to check how many <newFile> (those are the nodes I want to delete) nodes PHP could find.
In order to do that, I did the following:

```<code><?php
    $doc = new DOMDocument();
    $doc->load("FilenameList.xml");

    $root = $doc->documentElement;

    $newFiles = $root->getElementsByTagName("newFile");
    echo count($newFiles);
?>
</code>```

However, that returned "1", even though, obviously, there are way more nodes.
I also tried counting the amount of <newFile>nodes using simpleXML, but again, it did not work. I'm very confused by this, as I used the same syntax in the past and it worked out perfectly.
Another thing I tried was to do this:

```<code>$newFiles = $doc->getElementsByTagName("newFile");
</code>```

Instead of $root = ...

In addition, I also tried using sizeof() instead of count().
Am I missing something or does anyone have an idea about what's going wrong?

答:
The DOMDocument::getElementsByTagName function returns a new instance of class DOMNodeList. Such class had the following signature when the question was made:

```<code>DOMNodeList implements Traversable {
    /* Properties */
    readonly public int $length ;
    /* Methods */
    DOMNode DOMNodelist::item ( int $index )
}
</code>```

The class implemented the Traversable interface (so you can foreach () it) but not the Countable interface, which would allow count() to produce something useful.

The solution is the $length property you can see in the class signature:

length

The number of nodes in the list. The range of valid child node indices
  is 0 to length - 1 inclusive.

As of PHP/7.2.0 the Countable interface was finally implemented:

DOM:

Implemented FR #74837 (Implement Countable for DomNodeList and
  DOMNamedNodeMap).

Current version of the documentation is this:

```<code>DOMNodeList implements Traversable , Countable {
    /* Properties */
    readonly public int $length ;
    /* Methods */
    public int count ( void )
    DOMNode item ( int $index )
}
</code>```

… and your original code should finally work.

Body:
I'm trying to delete certain nodes from an XML-file using PHP, for some reason it was not working properly and I came to the conclusion that that's probably the case, because PHP is not returning the correct number of nodes, that are in said XML-file.

This is the XML-File:

<?xml version="1.0"?>
<Filenames>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
    <newFile>
        <link>somelink</link>
        <ViewLink>someotherlink</ViewLink>
        <FileName>test</FileName>
    </newFile>
</Filenames>

...and so on (the file is way longer, but I'm always using the same name for nodes etc., you get the point)

Since deleting certain nodes did not work out, I tried just getting the information from the xml-file first and I tried to check how many <newFile> (those are the nodes I want to delete) nodes PHP could find.
In order to do that, I did the following:

<?php
    $doc = new DOMDocument();
    $doc->load("FilenameList.xml");

    $root = $doc->documentElement;

    $newFiles = $root->getElementsByTagName("newFile");
    echo count($newFiles);
?>

However, that returned "1", even though, obviously, there are way more nodes.
I also tried counting the amount of <newFile>nodes using simpleXML, but again, it did not work. I'm very confused by this, as I used the same syntax in the past and it worked out perfectly.
Another thing I tried was to do this:

$newFiles = $doc->getElementsByTagName("newFile");

Instead of $root = ...

In addition, I also tried using sizeof() instead of count().
Am I missing something or does anyone have an idea about what's going wrong?

Body:
The DOMDocument::getElementsByTagName function returns a new instance of class DOMNodeList. Such class had the following signature when the question was made:

DOMNodeList implements Traversable {
    /* Properties */
    readonly public int $length ;
    /* Methods */
    DOMNode DOMNodelist::item ( int $index )
}

The class implemented the Traversable interface (so you can foreach () it) but not the Countable interface, which would allow count() to produce something useful.

The solution is the $length property you can see in the class signature:

length

The number of nodes in the list. The range of valid child node indices
  is 0 to length - 1 inclusive.

As of PHP/7.2.0 the Countable interface was finally implemented:

DOM:

Implemented FR #74837 (Implement Countable for DomNodeList and
  DOMNamedNodeMap).

Current version of the documentation is this:

DOMNodeList implements Traversable , Countable {
    /* Properties */
    readonly public int $length ;
    /* Methods */
    public int count ( void )
    DOMNode item ( int $index )
}

… and your original code should finally work.

ContentLicense: CC BY-SA 4.0


问:
Do I need to commit the dist folder to git in order to be able to install the package using pip from git?
I want to reuse some code for my internal team at work. My plan is to create a package and then have people install the package using pip straight out of our git repo. i.e. as shown here: https://pip.pypa.io/en/latest/reference/pip_install/#git

My question is, do I commit the dist folder to git? What is pip looking for?

Or is there a better way to share / reuse code internally for a team (across many different projects)?

I used a .gitignore file from here (is that github's default Python .gitignore file?) and it ignores all the dist files:

```<code># Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
</code>```

but it seems wrong to exclude these from the repo when I'm trying to install from the repo.

答:
dist is a default name for a directory that contains the final build result: your project ready to be distributed, that is, packaged into a file which pip or other package managers know how to install:

```<code>$ python setup.py sdist --help
...
  --dist-dir (-d)   directory to put the source distribution archive(s) in
                    [default: dist]
</code>```

So it is safe to ignore the directory and all of its contents in .gitignore. If you do not plan to upload you project's installation files to PyPI and intend to install it via passing Git url, you don't even need the dist directory and can safely delete it. It will be recreated anyway once you issue any dist command (sdist, bdist, bdist_wheel, bdist_rpm etc).

Body:
I want to reuse some code for my internal team at work. My plan is to create a package and then have people install the package using pip straight out of our git repo. i.e. as shown here: https://pip.pypa.io/en/latest/reference/pip_install/#git

My question is, do I commit the dist folder to git? What is pip looking for?

Or is there a better way to share / reuse code internally for a team (across many different projects)?

I used a .gitignore file from here (is that github's default Python .gitignore file?) and it ignores all the dist files:

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

but it seems wrong to exclude these from the repo when I'm trying to install from the repo.

Body:
dist is a default name for a directory that contains the final build result: your project ready to be distributed, that is, packaged into a file which pip or other package managers know how to install:

$ python setup.py sdist --help
...
  --dist-dir (-d)   directory to put the source distribution archive(s) in
                    [default: dist]

So it is safe to ignore the directory and all of its contents in .gitignore. If you do not plan to upload you project's installation files to PyPI and intend to install it via passing Git url, you don't even need the dist directory and can safely delete it. It will be recreated anyway once you issue any dist command (sdist, bdist, bdist_wheel, bdist_rpm etc).


问:
Apache on PC doesn't start with a ServerRoot not found
i have formatted my PC (with windows 10 pro 64 bit) and reinstalled apache 2.4.17 and PHP 5.6.15. But from the line command when i give a "httpd -k install" i receive the error "httpd: Syntax error on line 37 of C:/Server/Apache/conf/httpd.conf: ServerRoot must be a valid directory"
in the line 37 of httpd.conf i put

ServerRoot "C:/Server/Apache"

so why httpd.conf don't find this directory????

答:
To fix this error, open and edit the following line in C:\local\apache\conf\httpd.conf:</p>

```<code>#ServerRoot "c:/Apache24" # original setting
ServerRoot "c:/local/apache" #according to your apache destination
</code>```

Body:
To fix this error, open and edit the following line in C:\local\apache\conf\httpd.conf:

#ServerRoot "c:/Apache24" # original setting
ServerRoot "c:/local/apache" #according to your apache destination


问:
readlink unable to take path names mentioned in a file
```<code>while
    read -r line
        do
           readlink -f $line > a.txt
done < $1
</code>```

<p>I have a file which contains 30 symbolic destination pathnames passed by $1. I want to read this file line by line and wants to save ls results of each path in a file a.txt. The problem coming is that its only taking last path name mentioned in $1. Its ignoring upper 29 lines. Why? </p>

答:
Change

```<code>readlink -f $line > a.txt
</code>```

to

```<code>readlink -f "$line" >> a.txt
</code>```

The >> appends to a file or creates the file if it doesn't exist.

The > overwrites the file if it exists or creates it if it doesn't exist.

https://serverfault.com/a/196735

Body:
while
    read -r line
        do
           readlink -f $line > a.txt
done < $1

I have a file which contains 30 symbolic destination pathnames passed by $1. I want to read this file line by line and wants to save ls results of each path in a file a.txt. The problem coming is that its only taking last path name mentioned in $1. Its ignoring upper 29 lines. Why?

Body:
Change

readlink -f $line > a.txt

to

readlink -f "$line" >> a.txt

The >> appends to a file or creates the file if it doesn't exist.

The > overwrites the file if it exists or creates it if it doesn't exist.

https://serverfault.com/a/196735


问:
Display lateral view same like google map in my application
I am developing one navigation based application in which i used google map and google direction api for route navigation but i stuck at one point, i need to show same google map lateral view which is open when we start the navigation.

I have R&D lots off on it but not able to do exactly same like google map lateral view.

I try with following

```<code> GMSCameraPosition *camera =[GMSCameraPosition cameraWithTarget:marker.position zoom:50.0 bearing:120 viewingAngle:90];
[[self getMapView] animateToCameraPosition:camera];
</code>```

not succeed to display same.

I need to show same google map as following when i start navigation.Can anybody help me in this point.Thanks in advance

答:
You can achieve using proper bearing between 2 location. (present  and target location)</p>

```<code>func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 }
    func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi }

    func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {

        let lat1 = degreesToRadians(degrees: point1.coordinate.latitude)
        let lon1 = degreesToRadians(degrees: point1.coordinate.longitude)

        let lat2 = degreesToRadians(degrees: point2.coordinate.latitude)
        let lon2 = degreesToRadians(degrees: point2.coordinate.longitude)

        let dLon = lon2 - lon1

        let y = sin(dLon) * cos(lat2)
        let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
        let radiansBearing = atan2(y, x)

        return radiansToDegrees(radians: radiansBearing)
    }

let bearingPoint = self.getBearingBetweenTwoPoints1(point1: location!, point2: self.featureLocation)
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 50, bearing: bearingPoint, viewingAngle: 45)

self.mapView?.animate(to: camera)
</code>```

Body:
I am developing one navigation based application in which i used google map and google direction api for route navigation but i stuck at one point, i need to show same google map lateral view which is open when we start the navigation.

I have R&D lots off on it but not able to do exactly same like google map lateral view.

I try with following

 GMSCameraPosition *camera =[GMSCameraPosition cameraWithTarget:marker.position zoom:50.0 bearing:120 viewingAngle:90];
[[self getMapView] animateToCameraPosition:camera];

not succeed to display same.

I need to show same google map as following when i start navigation.Can anybody help me in this point.Thanks in advance

Body:
You can achieve using proper bearing between 2 location. (present  and target location)

func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180.0 }
    func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / .pi }

    func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {

        let lat1 = degreesToRadians(degrees: point1.coordinate.latitude)
        let lon1 = degreesToRadians(degrees: point1.coordinate.longitude)

        let lat2 = degreesToRadians(degrees: point2.coordinate.latitude)
        let lon2 = degreesToRadians(degrees: point2.coordinate.longitude)

        let dLon = lon2 - lon1

        let y = sin(dLon) * cos(lat2)
        let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
        let radiansBearing = atan2(y, x)

        return radiansToDegrees(radians: radiansBearing)
    }

let bearingPoint = self.getBearingBetweenTwoPoints1(point1: location!, point2: self.featureLocation)
let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 50, bearing: bearingPoint, viewingAngle: 45)

self.mapView?.animate(to: camera)


问:
easy to use Date time picker
I'm looking for an easy to use date time picker. I tried to use bootstrap date time picker and I'm using bootstrap 4 alpha. It does not work for me.

Here is my code:

```<code>    <script>
    $(function() {
        $('#datetimepicker1').datetimepicker();
    });
    </script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <!-- Moment JS -->
    <script type="text/javascript" src="<?php echo $ROOT; ?>js/moment.min.js"></script>
    <!--Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" ></script>
    <!-- dateTimePicker JS -->
    <script type="text/javascript" src="<?php echo $ROOT; ?>js/bootstrap-datetimepicker.min.js"></script>
    <!--bootstrap  -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <!-- dateTimePicker CSS -->
    <link rel="stylesheet" type="text/css" href="<?php echo $ROOT; ?>css/bootstrap-datetimepicker.min.css">

    <div class = "form-group col col-md-4 col-sm-4 col-12">
        <div class='input-group date' id='datetimepicker1'>
          <input type='text' class="form-control" id="servDate"/>
          <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
          </span>
        </div>
    </div>
</code>```

答:
I suggest to use: https://tempusdominus.github.io/bootstrap-4/ which is the Bootstrap 4 version of DateTimePicker (successor of Eonasdan/bootstrap-datetimepicker).

You can find examples in the documentation: https://tempusdominus.github.io/bootstrap-4/Usage/

Github repo: https://github.com/tempusdominus/bootstrap-4

However here is a working snippet from tempusdominus docs (best view expanding snippet):

$(function () {
    $('#datetimepicker1').datetimepicker();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" crossorigin="anonymous">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment-with-locales.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/tempusdominus/bootstrap-4/master/build/js/tempusdominus-bootstrap-4.min.js"></script>
<link href="https://rawgit.com/tempusdominus/bootstrap-4/master/build/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                    <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"/>
                    <span class="input-group-addon" data-target="#datetimepicker1" data-toggle="datetimepicker">
                        <span class="fa fa-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div></code>```

Title: easy to use Date time picker

Body:
I'm looking for an easy to use date time picker. I tried to use bootstrap date time picker and I'm using bootstrap 4 alpha. It does not work for me.

Here is my code:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="<?php echo $ROOT; ?>css/bootstrap-datetimepicker.min.css">

          <input type='text' class="form-control" id="servDate"/>

Body:
I suggest to use: https://tempusdominus.github.io/bootstrap-4/ which is the Bootstrap 4 version of DateTimePicker (successor of Eonasdan/bootstrap-datetimepicker).

You can find examples in the documentation: https://tempusdominus.github.io/bootstrap-4/Usage/

Github repo: https://github.com/tempusdominus/bootstrap-4

However here is a working snippet from tempusdominus docs (best view expanding snippet):

$(function () {
    $('#datetimepicker1').datetimepicker();
});

<script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" crossorigin="anonymous">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment-with-locales.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/tempusdominus/bootstrap-4/master/build/js/tempusdominus-bootstrap-4.min.js"></script>
<link href="https://rawgit.com/tempusdominus/bootstrap-4/master/build/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
                    <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"/>
                    <span class="input-group-addon" data-target="#datetimepicker1" data-toggle="datetimepicker">
                        <span class="fa fa-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
Consider toggling between specified classes, as demonstrated in the embedded code snippet below.

jQuery .toggleClass() method:

jQuery('.triangle').on('click', function(){
  jQuery(this).toggleClass('triangle triangle-up');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    padding: 10px;
    background: black;
}

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}</code>```

```
</div>
</div>
</p>

<p>Alternatively, you could adjust the specified styles for the class <code>.triangle-up</code> to rotate the element (with a <code>transform</code> rule declared), instead of redefining borders, then only toggle this class. With the addition of a declared <code>transition</code> rule, this will allow the element in question to animate when toggling between classes.</p>

<p><strong>jQuery <code>.toggleClass()</code> method (transition animation demonstration):</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery('.triangle').on('click', function(){
  jQuery(this).toggleClass('triangle-up');
});</code>```

body {
    padding: 10px;
    background: black;
}

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s; /* required for animation effect */
}

.triangle-up {
    transform: rotate(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=triangle></div></code>```

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
Consider toggling between specified classes, as demonstrated in the embedded code snippet below.

jQuery .toggleClass() method:

jQuery('.triangle').on('click', function(){
  jQuery(this).toggleClass('triangle triangle-up');
});

body {
    padding: 10px;
    background: black;
}

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=triangle></div>

Alternatively, you could adjust the specified styles for the class .triangle-up to rotate the element (with a transform rule declared), instead of redefining borders, then only toggle this class. With the addition of a declared transition rule, this will allow the element in question to animate when toggling between classes.

jQuery .toggleClass() method (transition animation demonstration):

jQuery('.triangle').on('click', function(){
  jQuery(this).toggleClass('triangle-up');
});

body {
    padding: 10px;
    background: black;
}

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s; /* required for animation effect */
}

.triangle-up {
    transform: rotate(180deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=triangle></div>


答:
In your first example you take 123 and interpret it as a number in octal representation, that means the first digit is not 100 but only 64 (8*8). So 123 is interpreted as 8*8*1+8*2+3 = 83.
In the second example 1a is interpreted as in hexadecimal representation. So -1a = -(16*1+10) = -26.</p>

Title: Jave - method is - parseByte(String s, int radix) - I can't understand it


问:
Adding elements in a list
I have a list named p. It contains some elements like this.

```<code>p = [['mon', '1006'], ['mon', '769']].
</code>```

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

答:
You can use reduce,

```<code>l = [['mon', '1006'], ['mon', '769']]
print reduce(lambda item1, item2: int(item1[1])+int(item2[1]), l)

#output 1775
</code>```

Title: Adding elements in a list

Body:
I have a list named p. It contains some elements like this.

p = [['mon', '1006'], ['mon', '769']].

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

Body:
You can use reduce,

l = [['mon', '1006'], ['mon', '769']]
print reduce(lambda item1, item2: int(item1[1])+int(item2[1]), l)

#output 1775


问:
jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
planning to read a file over a Windows from Ubuntu in Java using jcifs.Tried a simple approach using:

```<code>String user = "mydomain;myuser:mypassword";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
SmbFile remotefile = new SmbFile("smb://myserver/myfolder/myfile.jar",auth);
</code>```

Knowing that the server works and the login values are correct,all i get is a logon failure,what could be the problem here?

答:
Comment to "peterb"s answer: "...call must include the domain..."

I figured out that in my case the NtlmPasswordAuthentication( "domain", "username", "password" ) needs its inputs like this:
domain is the long domain with path to the share:\xxxx.domain.xxxx.com\path.
username is the username with domain: domain\username.
password = password.

I hope this will help some one.

BEM

Body:
planning to read a file over a Windows from Ubuntu in Java using jcifs.Tried a simple approach using:

String user = "mydomain;myuser:mypassword";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
SmbFile remotefile = new SmbFile("smb://myserver/myfolder/myfile.jar",auth);

Knowing that the server works and the login values are correct,all i get is a logon failure,what could be the problem here?


问:
Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only)

The code below is working fine but what if there are 100 inputs? any shorter way to do this?

function checkTotal() {
  var a = document.getElementById("sandwich").value;
  var b = document.getElementById("burger").value;
  var c = document.getElementById("cake").value;
  var d = document.getElementById("coffee").value;
  document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form role="form" name="listForm">
  <label>Sandwich</label>
  <input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>

  <label>Burger</label>
  <input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>

  <label>Cake</label>
  <input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>

  <label>Coffee</label>
  <input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form></code>```

    1) Here each input article has a different price.
    2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
    3) i have my code which is working fine but is the above code is the right way to do?
    4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?

答:
what if there are 100 of article inputs. is there shorter code or
  should i create variable for each one?

You can maintain a map

```<code>var idPriceMap = {
  "sandwich" : 20,
  "burger" : 10,
  "cake" : 5,
  "coffee" : 10
};
</code>```

You can iterate this and produce your value using reduce

```<code>var output = Object.keys( idPriceMap ).reduce( function(a,b){
   var value = +document.getElementById( b ).value;
   a += value * idPriceMap[ b ];
   return a;
}, 0);
document.getElementById( "total" ).value = output;
</code>```

Body:
The code below is working fine but what if there are 100 inputs? any shorter way to do this?

function checkTotal() {
  var a = document.getElementById("sandwich").value;
  var b = document.getElementById("burger").value;
  var c = document.getElementById("cake").value;
  var d = document.getElementById("coffee").value;
  document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}

<form role="form" name="listForm">
  Sandwich
  <input type="number" id="sandwich" value="0" onkeyup="checkTotal()">

  Burger
  <input type="number" id="burger" value="0" onkeyup="checkTotal()">

  Cake
  <input type="number" id="cake" value="0" onkeyup="checkTotal()">

  Coffee
  <input type="number" id="coffee" value="0" onkeyup="checkTotal()">
 Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>

    1) Here each input article has a different price.
    2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
    3) i have my code which is working fine but is the above code is the right way to do?
    4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?

Body:
what if there are 100 of article inputs. is there shorter code or
  should i create variable for each one?

You can maintain a map

var idPriceMap = {
  "sandwich" : 20,
  "burger" : 10,
  "cake" : 5,
  "coffee" : 10
};

You can iterate this and produce your value using reduce

var output = Object.keys( idPriceMap ).reduce( function(a,b){
   var value = +document.getElementById( b ).value;
   a += value * idPriceMap[ b ];
   return a;
}, 0);
document.getElementById( "total" ).value = output;


问:
Excel VBA - copy only row-range that contains specific value in column on a different workbook
I want to create a macro that copies a row-range if the cell in column DA contains a specific value.

For example:

If the column DA10 contains the value 3-incompletion, N10 contaings nothing, CI10 contains nothing - then the macro should copy the cells F10, H10 and DA10 into the workbook reportWB. I don't know how to do it.

Progression so far (thanks to Shai - I'm still to stupid to make it work):

```<code>Sub insertINCOMPLETION()

Dim dataWB As Workbook
Dim reportWB As Workbook
Dim workB As Workbook
Dim incomplRNG As Range
Dim LastRow6 As Long
Dim LastRow7 As Long

For Each workB In Application.Workbooks
    If Left(workB.Name, 5) = "15B2" Then
        Set dataWB = workB
        Exit For
    End If
Next

    If Not dataWB Is Nothing Then
        Set reportWB = ThisWorkbook

    With reportWB.Sheets("getDATA")
        LastRow6 = .Cells(.Rows.Count, "B").End(xlUp).Offset(1).Row
    End With

With dataWB.Sheets("Data")
    LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

     If InStr(.Range("DA" & LastRow7).Value2, "3-Incompletion") > 0 And _
        Trim(.Range("N" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If
End With
End If
End Sub
</code>```

Still doesn't work. Ends after checking the column DA.

答:
You need to add the code part where you compare the cell's text with "3-incompletion". You can use InStr function to achieve this.

```<code>With dataWB.Sheets("Data")
    ' === not sure why you want to look for the last row ??? ===
    'LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

    ' compare the value in row 10 (as in your post example)
    LastRow7 = 10

     If InStr(.Range("AD" & LastRow7).Value2, "3-incompletion") > 0 And _
        Trim(.Range("AD" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If
End With
</code>```

Body:
I want to create a macro that copies a row-range if the cell in column DA contains a specific value.

For example:

If the column DA10 contains the value 3-incompletion, N10 contaings nothing, CI10 contains nothing - then the macro should copy the cells F10, H10 and DA10 into the workbook reportWB. I don't know how to do it.

Progression so far (thanks to Shai - I'm still to stupid to make it work):

Sub insertINCOMPLETION()

Dim dataWB As Workbook
Dim reportWB As Workbook
Dim workB As Workbook
Dim incomplRNG As Range
Dim LastRow6 As Long
Dim LastRow7 As Long

For Each workB In Application.Workbooks
    If Left(workB.Name, 5) = "15B2" Then
        Set dataWB = workB
        Exit For
    End If
Next

    If Not dataWB Is Nothing Then
        Set reportWB = ThisWorkbook

    With reportWB.Sheets("getDATA")
        LastRow6 = .Cells(.Rows.Count, "B").End(xlUp).Offset(1).Row
    End With

With dataWB.Sheets("Data")
    LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

     If InStr(.Range("DA" & LastRow7).Value2, "3-Incompletion") > 0 And _
        Trim(.Range("N" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If
End With
End If
End Sub

Still doesn't work. Ends after checking the column DA.

Body:
You need to add the code part where you compare the cell's text with "3-incompletion". You can use InStr function to achieve this.

With dataWB.Sheets("Data")
    ' === not sure why you want to look for the last row ??? ===
    'LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

    ' compare the value in row 10 (as in your post example)
    LastRow7 = 10

     If InStr(.Range("AD" & LastRow7).Value2, "3-incompletion") > 0 And _
        Trim(.Range("AD" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If
End With