问:
Select not null column in full join postgresql
I have 3 tables:

```<code>with current_exclusive as(
        select id_station, area_type,
    count(*) as total_entries
    from c1169.data_cashier
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date <= '2017-12-30'
    group by id_station, area_type
), current_table as(
        select id_station, area_type,
    sum(total_time) filter (where previous_status = 1) as total_time
    from c1169.data_table
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date < '2017-12-30'
    group by id_station, area_type
), current_cashier as(
        select id_station, area_type,
    sum(1) as total_transactions
    from c1169.data_cashier
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date < '2017-12-30'
    group by id_station, area_type
)
select *
from current_exclusive
full join current_table on current_exclusive.id_station = current_table.id_station and current_exclusive.area_type = current_table.area_type
full join current_cashier on current_exclusive.id_station = current_cashier.id_station and current_exclusive.area_type = current_cashier.area_type
</code>```

and the result is:

but my expected result is:

Are there any way to select * and show the expected result? Because when I do full join then id_station and area_type can be null in some tables, so it very hard to choose which column is not null.

Like: select case id_station is not null then id_station else id_station1 end, but I have up to 10 tables so can not do in select case

答:
You cannot accomplish anything if you insist on using select *, since you are getting the values from different tables.

The option you have is to include a COALESCE block which gives you the first non-null value from the list of columns.

So, you could use.

```<code>select COALESCE( current_exclusive.id_station, current_table.id_station, current_cashier.id_station ) as id_station ,
COALESCE( current_exclusive.area_type , current_table.area_type, current_cashier.area_type ) as area_type ,.....
...
from current_exclusive
full join current_table..
...
</code>```

Body:
I have 3 tables:

with current_exclusive as(
        select id_station, area_type,
    count(*) as total_entries
    from c1169.data_cashier
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date <= '2017-12-30'
    group by id_station, area_type
), current_table as(
        select id_station, area_type,
    sum(total_time) filter (where previous_status = 1) as total_time
    from c1169.data_table
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date < '2017-12-30'
    group by id_station, area_type
), current_cashier as(
        select id_station, area_type,
    sum(1) as total_transactions
    from c1169.data_cashier
    where id_station IN(2439,2441,2443,2445,2447,2449) and date >= '2017-10-30' and date < '2017-12-30'
    group by id_station, area_type
)
select *
from current_exclusive
full join current_table on current_exclusive.id_station = current_table.id_station and current_exclusive.area_type = current_table.area_type
full join current_cashier on current_exclusive.id_station = current_cashier.id_station and current_exclusive.area_type = current_cashier.area_type

and the result is:

but my expected result is:

Are there any way to select * and show the expected result? Because when I do full join then id_station and area_type can be null in some tables, so it very hard to choose which column is not null.

Like: select case id_station is not null then id_station else id_station1 end, but I have up to 10 tables so can not do in select case

Body:
You cannot accomplish anything if you insist on using select *, since you are getting the values from different tables.

The option you have is to include a COALESCE block which gives you the first non-null value from the list of columns.

So, you could use.

select COALESCE( current_exclusive.id_station, current_table.id_station, current_cashier.id_station ) as id_station ,
COALESCE( current_exclusive.area_type , current_table.area_type, current_cashier.area_type ) as area_type ,.....
...
from current_exclusive
full join current_table..
...


来源: stackexchange

问:
How do you display "%5d" in C?
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

```<code>#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}
</code>```

Any help?

答: Use double % - printf("%%5d").

ContentLicense: CC BY-SA 2.5

Title: How do you display "%5d" in C?

Body:
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}

Any help?

Body: Use double % - printf("%%5d").


问:
How to show duration popup on polyline?
I want to show route duration on Polyline as shown on the screenshot. I have done some digging on internet but couldn't find the solution.

Guide me if anyone of you have any solution.
Thanks.

答:
Use Google Direction API to get the route and draw the polyline

Add OnPolylineClickListener in Map and get the reference using getTag

```<code>    mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
        @Override
        public void onPolylineClick(Polyline polyline) {
            Log.e("Polyline position", " -- " + polyline.getTag());
            onButtonShowPopupWindowClick("  " + polyline.getTag());
        }
    });
</code>```

Set any reference in polyline using setTag method

```<code>                Polyline line = mMap.addPolyline(lineOptions);
                line.setTag("" + i);
                line.setClickable(true);
</code>```

Open PopupWindow in polyline click

```<code>public void onButtonShowPopupWindowClick(String count) {

    String[] timeDistance = count.split(",");

    // get a reference to the already created main layout
    LinearLayout mainLayout = (LinearLayout)
            findViewById(R.id.whole_layout);

    // inflate the layout of the popup window
    LayoutInflater inflater = (LayoutInflater)
            getSystemService(LAYOUT_INFLATER_SERVICE);
    View popupView = inflater.inflate(R.layout.polyline_window, null);

    ((TextView) popupView.findViewById(R.id.time)).setText("30 mins");
    ((TextView) popupView.findViewById(R.id.distance)).setText("20 km");

    // create the popup window
    int width = LinearLayout.LayoutParams.WRAP_CONTENT;
    int height = LinearLayout.LayoutParams.WRAP_CONTENT;
    boolean focusable = true; // lets taps outside the popup also dismiss it
    final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

    // show the popup window
    popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);

    // dismiss the popup window when touched
    popupView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            popupWindow.dismiss();
            return true;
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to show duration popup on polyline?

Body:
Use Google Direction API to get the route and draw the polyline

Add OnPolylineClickListener in Map and get the reference using getTag

    mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
        @Override
        public void onPolylineClick(Polyline polyline) {
            Log.e("Polyline position", " -- " + polyline.getTag());
            onButtonShowPopupWindowClick("  " + polyline.getTag());
        }
    });

Set any reference in polyline using setTag method

                Polyline line = mMap.addPolyline(lineOptions);
                line.setTag("" + i);
                line.setClickable(true);

Open PopupWindow in polyline click

public void onButtonShowPopupWindowClick(String count) {

    String[] timeDistance = count.split(",");

    // get a reference to the already created main layout
    LinearLayout mainLayout = (LinearLayout)
            findViewById(R.id.whole_layout);

    // inflate the layout of the popup window
    LayoutInflater inflater = (LayoutInflater)
            getSystemService(LAYOUT_INFLATER_SERVICE);
    View popupView = inflater.inflate(R.layout.polyline_window, null);

    ((TextView) popupView.findViewById(R.id.time)).setText("30 mins");
    ((TextView) popupView.findViewById(R.id.distance)).setText("20 km");

    // create the popup window
    int width = LinearLayout.LayoutParams.WRAP_CONTENT;
    int height = LinearLayout.LayoutParams.WRAP_CONTENT;
    boolean focusable = true; // lets taps outside the popup also dismiss it
    final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

    // show the popup window
    popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);

    // dismiss the popup window when touched
    popupView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            popupWindow.dismiss();
            return true;
        }
    });
}


问:
What different ways are there for apps to store data in iCloud and which are visible from the iCloud Manage Storage
There seem to be a few different ways for an app to store data in iCloud (iCloud Drive Documents, Core Data with iCloud Sync, CloudKit Private Databases, Key Value Pairs etc) but I'm not sure if that's all. Which of these different types of iCloud storage appear to the user in the iCloud 'Manage Storage' menu (i.e. some apps don't appear at all whereas others list 'Documents and Data' whereas others list files that can be individually removed but don't appear in iCloud Drive)? I'm trying to figure out but the documentation's a bit vague on this.</p>

答:
Aaron,

There are three "Apple owned" places you can store data for an iOS device, on the device itself, in an iCloud Drive and/or in the iCloudKit database.

The iCloudKit database has within it three more places. Two of those are databases in the true sense of the word, so structured areas you can store information within, namely key/value pairs and CloudKit. A CloudKit database itself breaks down into two more principle divisions, public and private areas.

Their accessibility is governed on a user/app basis. So you as a developer can opt to use or indeed make your files accessible on them or not. The rules governing who can access what can be confusing, especially as they can/have been changing over different iOS releases.

The iCloud Drive is the most and least flexible, you can store everything on it but you cannot share anything within it, except with yourself.

The iCloud key/pair database comes next, except it is used exclusively by an application to store application state/preferences only [it has a very limited space], again you can share it with yourself only.

The CloudKit database comes next, again something that would be used on an application by application basis. So apps do not share databases and cannot access other app databases, unless they come from the same author and sharing is a built in functionality that has been explicitly intended.

That said, the CloudKit database has two distinct areas a private and a public one. The private area can be accessed by a single user of an app, the public area can be accessed by anybody using said app on any iOS device.

CloudKit documents are an area where Apple store documents from its apps principally, so keynotes, pages and numbers; although they have opened it up somewhat in recent years. They can be shared with other users too using on of the apps designed specifically to store data within the iCloudKit documents area. It is the closest you'll get to a dropbox under iOS, short of using dropbox fof course.

Finally you can store data on your iOS device itself and opt in to share that with others on the same device too thru Apple's files app, although that that is a very recent status quo, so only available for apps designed to run under iOS 11 explicitly opted into the new status quo.

All that said, Apple counts all the places as one in the same when it comes to storage limits, be warned if you want design/build an app using cloudKit storage; if Apple deem you did so recklessly, you won't get a foot in on the app store.

As final comment Apple security policies are designed as a general rule to ensure you as a user have quite fine grained control over who accesses their data, it was/is an intentional decision on their part to protect you from yourself. As a general rule, it works well; which is why you see almost no viruses under iOS.


问:
How to run sql scripts from a pl sql procedure
I have a procedure like :

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;
</code>```

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;
</code>```

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?

答: You can't, in general, because the pl/sql is run in the database, on the server, and sqlplus is a client process. The server can't rely on even being on the same system as the client and its files, much less knowing anything about how to find the file the client is referring to. Even if the syntax were supported (and it isn't), your sql script would have to be on the server, in a location the server knew about and had access to.</p>

Body:
I have a procedure like :

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?


问:
How to get a segment URL cakephp 3
Hi I got trouble in retrieve URL segment CAkephp3 in view. I want to get the ID from current URL.

Lets say my URL is http://localhost/admin/financial_agreements/edit/50
and I want redirect to http://localhost/admin/financial_agreements/do_print/50
simply :

```<code>var urlPrint = "<?=$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', 'I NEED ID FROM CURRENT'], true)?>";
</code>```

I try debug

```<code><?=debug($this->Url->build()); die();?>
</code>```

But its produce : admin/financial_agreements/edit/50

whats called in 50 ? I need that 50 inside my "url->build" urlPrint

sorry for bad english.

Anyhelp will appreciate.
thanks.

答:
You can use the Request object to get request data (including url parameters) within views.

Try this in your view:

$this->request->getParam('pass')  //CakePHP 3.4+

$this->request->params['pass']  // CakePHP 3.3

That will return an array of all non-named parameters that were passed after the action's name in the URL. Example: /mycontroller/myaction/param1/param2. So in this example, $this->request->getParam('pass') will produce an array like: [0 => 'param1', 1 => 'param2'].

Bonus answer: you can also 'name' parameters in the URL, like: /mycontroller/myaction/some_name:some_value. To retrieve this kind of named parameters, you would do the same trick but using: $this->request->getParam('named') (Use the argument 'named' instead of 'pass').

More info:
https://book.cakephp.org/3.0/en/controllers/request-response.html
https://book.cakephp.org/3.0/en/development/routing.html#passed-arguments

Title: How to get a segment URL cakephp 3

Body:
Hi I got trouble in retrieve URL segment CAkephp3 in view. I want to get the ID from current URL.

Lets say my URL is http://localhost/admin/financial_agreements/edit/50
and I want redirect to http://localhost/admin/financial_agreements/do_print/50
simply :

var urlPrint = "<?=$this->Url->build(['controller' => 'financial_agreements', 'action' => 'do_print', 'I NEED ID FROM CURRENT'], true)?>";

I try debug

<?=debug($this->Url->build()); die();?>

But its produce : admin/financial_agreements/edit/50

whats called in 50 ? I need that 50 inside my "url->build" urlPrint

sorry for bad english.

Anyhelp will appreciate.
thanks.

ContentLicense: CC BY-SA 4.0


问:
I want to install PHP GTFS-realtime Language Bindings in laravel
I want to install PHP GTFS-realtime Language Bindings in laravel 5.5. But it Gives error</p>

```<code> Problem 1
    - Conclusion: don't install symfony/console v3.4.1
    - Conclusion: don't install laravel/framework v5.5.24
    - Conclusion: don't install laravel/framework v5.5.23
    - Conclusion: remove laravel/framework v5.5.22
    - Conclusion: don't install laravel/framework v5.5.22
    - Conclusion: don't install laravel/framework v5.5.21
    - Conclusion: don't install laravel/framework v5.5.20
    - Conclusion: don't install laravel/framework v5.5.19
    - Conclusion: don't install laravel/framework v5.5.18
    - Conclusion: don't install laravel/framework v5.5.17
    - Conclusion: don't install laravel/framework v5.5.16
    - Conclusion: don't install laravel/framework v5.5.15
    - Conclusion: don't install laravel/framework v5.5.14
    - Conclusion: don't install laravel/framework v5.5.13
    - Conclusion: don't install laravel/framework v5.5.12
    - Conclusion: don't install laravel/framework v5.5.11
    - Conclusion: don't install laravel/framework v5.5.10
    - Conclusion: don't install laravel/framework v5.5.9
    - Conclusion: don't install laravel/framework v5.5.8
    - Conclusion: don't install laravel/framework v5.5.7
    - Conclusion: don't install laravel/framework v5.5.6
    - Conclusion: don't install laravel/framework v5.5.5
    - Conclusion: don't install laravel/framework v5.5.4
    - Conclusion: don't install laravel/framework v5.5.3
    - Conclusion: don't install laravel/framework v5.5.2
    - Conclusion: don't install laravel/framework v5.5.1
    - Conclusion: don't install symfony/console v3.4.0
    - Installation request for laravel/framework 5.5.* -> satisfiable by laravel/framework[v5.5.0, v5.5.1, v5.5.10, v5.5.11, v5.5.12, v5.5.13, v5.5.14, v5.5.15, v5.5.16, v5.5.17, v5.5.18, v5.5.19, v5.5.2, v5.5.20, v5.5.21, v5.5.22, v5.5.23, v5.5.24, v5.5.3, v5.5.4, v5.5.5, v5.5.6, v5.5.7, v5.5.8, v5.5.9].

    - laravel/framework v5.5.0 requires symfony/console ~3.3 -> satisfiable by symfony/console[v3.3.13, v3.3.0, v3.3.1, v3.3.10, v3.3.11, v3.3.12, v3.3.14, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6, v3.3.7, v3.3.8, v3.3.9, v3.4.0, v3.4.1].
    - Conclusion: don't install symfony/console v3.3.14|install symfony/console v2.8.32
</code>```

答:
Use composer global update command

I have the same problem, I resolved this problem by removing composer.lock file & then run composer global update command.  I prefer this link to resolve the issues

Body:
I want to install PHP GTFS-realtime Language Bindings in laravel 5.5. But it Gives error

 Problem 1
    - Conclusion: don't install symfony/console v3.4.1
    - Conclusion: don't install laravel/framework v5.5.24
    - Conclusion: don't install laravel/framework v5.5.23
    - Conclusion: remove laravel/framework v5.5.22
    - Conclusion: don't install laravel/framework v5.5.22
    - Conclusion: don't install laravel/framework v5.5.21
    - Conclusion: don't install laravel/framework v5.5.20
    - Conclusion: don't install laravel/framework v5.5.19
    - Conclusion: don't install laravel/framework v5.5.18
    - Conclusion: don't install laravel/framework v5.5.17
    - Conclusion: don't install laravel/framework v5.5.16
    - Conclusion: don't install laravel/framework v5.5.15
    - Conclusion: don't install laravel/framework v5.5.14
    - Conclusion: don't install laravel/framework v5.5.13
    - Conclusion: don't install laravel/framework v5.5.12
    - Conclusion: don't install laravel/framework v5.5.11
    - Conclusion: don't install laravel/framework v5.5.10
    - Conclusion: don't install laravel/framework v5.5.9
    - Conclusion: don't install laravel/framework v5.5.8
    - Conclusion: don't install laravel/framework v5.5.7
    - Conclusion: don't install laravel/framework v5.5.6
    - Conclusion: don't install laravel/framework v5.5.5
    - Conclusion: don't install laravel/framework v5.5.4
    - Conclusion: don't install laravel/framework v5.5.3
    - Conclusion: don't install laravel/framework v5.5.2
    - Conclusion: don't install laravel/framework v5.5.1
    - Conclusion: don't install symfony/console v3.4.0
    - Installation request for laravel/framework 5.5.* -> satisfiable by laravel/framework[v5.5.0, v5.5.1, v5.5.10, v5.5.11, v5.5.12, v5.5.13, v5.5.14, v5.5.15, v5.5.16, v5.5.17, v5.5.18, v5.5.19, v5.5.2, v5.5.20, v5.5.21, v5.5.22, v5.5.23, v5.5.24, v5.5.3, v5.5.4, v5.5.5, v5.5.6, v5.5.7, v5.5.8, v5.5.9].

    - laravel/framework v5.5.0 requires symfony/console ~3.3 -> satisfiable by symfony/console[v3.3.13, v3.3.0, v3.3.1, v3.3.10, v3.3.11, v3.3.12, v3.3.14, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6, v3.3.7, v3.3.8, v3.3.9, v3.4.0, v3.4.1].
    - Conclusion: don't install symfony/console v3.3.14|install symfony/console v2.8.32


问:
Login & Signup iOS Swift - Core Data
I want to create login and signup functions within Swift using Core Data.

This is my code to store the data in the signupVC;

```<code>    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context:NSManagedObjectContext = appDel.managedObjectContext

    let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
    newUser.setValue(txtUsername.text, forKey: "username")
    newUser.setValue(txtPassword.text, forKey: "password")
    newUser.setValue(txtEmailAdd.text, forKey: "email")

    do {
        try context.save()
    } catch {}

    print(newUser)
    print("Object Saved.")
</code>```

This is the code in the LoginVC;

```<code>@IBAction func signinTapp(sender: UIButton) {

    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context:NSManagedObjectContext = appDel.managedObjectContext

    let request = NSFetchRequest(entityName: "Users")
    request.returnsObjectsAsFaults = false
    request.predicate = NSPredicate(format: "username = %@", "" + txtUsername.text!)

    let results:NSArray = try! context.executeFetchRequest(request)

    if(results.count > 1){
        let res = results[0] as! NSManagedObject
        txtUsername.text = res.valueForKey("username") as! String
        txtPassword.text = res.valueForKey("password") as! String

        //for res in results {
         //   print(res)

    }else{
        print("Incorrect username and password")
    }

}
</code>```

Can anyone please advise my the best way forward? - I just need to retrieve  the saved core data and check if it matches.

Here is my Core Data model:

答:
import UIKit
import CoreData

class ViewController: UIViewController, UITextFieldDelegate {

```<code>@IBOutlet var txt_username: UITextField!

@IBOutlet var txt_password: UITextField!

var result = NSArray()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Log_in(_ sender: Any)
{
    if txt_username.text == "" && txt_password.text == ""
    {
        let alert = UIAlertController(title: "Information", message: "Please enter all the fields", preferredStyle: .alert)

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)
    }
    else

    {

        self.CheckForUserNameAndPasswordMatch(username : txt_username.text! as String, password : txt_password.text! as String)

    }

}

func CheckForUserNameAndPasswordMatch( username: String, password : String)
{
    let app = UIApplication.shared.delegate as! AppDelegate

    let context = app.persistentContainer.viewContext

    let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LoginDetails")

    let predicate = NSPredicate(format: "username = %@", username)

    fetchrequest.predicate = predicate
    do
    {
        result = try context.fetch(fetchrequest) as NSArray

        if result.count>0
        {
            let objectentity = result.firstObject as! LoginDetails

            if objectentity.username == username && objectentity.password == password
            {
                print("Login Succesfully")
            }
            else
            {
                print("Wrong username or password !!!")
            }
        }
    }

    catch
    {
        let fetch_error = error as NSError
        print("error", fetch_error.localizedDescription)
    }

}
</code>```

}

Registration page
==================>

import UIKit
import CoreData

class RegistrationPage: UIViewController, UITextFieldDelegate {

```<code>@IBOutlet var txt_user: UITextField!

@IBOutlet var txt_mailid: UITextField!

@IBOutlet var txt_pwd: UITextField!

@IBOutlet var txt_cpwd: UITextField!

@IBOutlet var txt_phone: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

@IBAction func register(_ sender: Any)
{
    if txt_user.text == "" || txt_mailid.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == ""
    {
        let alert = UIAlertController(title: "Information", message: "Its Mandatort to enter all the fields", preferredStyle: .alert)

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)

    }

    else if (txt_pwd.text != txt_cpwd.text)
    {
        let alert = UIAlertController(title: "Information", message: "Password does not match", preferredStyle: .alert
        )

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)

    }

    else
    {
        let app = UIApplication.shared.delegate as! AppDelegate

        let context = app.persistentContainer.viewContext

        let new_user = NSEntityDescription.insertNewObject(forEntityName: "LoginDetails", into: context)

        new_user.setValue(txt_user.text, forKey: "username")
        new_user.setValue(txt_mailid.text, forKey: "mailid")
        new_user.setValue(txt_pwd.text, forKey: "password")
        new_user.setValue(txt_phone.text, forKey: "phone")

        do
        {
            try context.save()
            print("Registered  Sucessfully")
        }
        catch
        {
            let Fetcherror = error as NSError
            print("error", Fetcherror.localizedDescription)
        }
    }

    self.navigationController?.popViewController(animated: true)

    }
}
</code>```

Title: Login & Signup iOS Swift - Core Data

Body:
I want to create login and signup functions within Swift using Core Data.

This is my code to store the data in the signupVC;

    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context:NSManagedObjectContext = appDel.managedObjectContext

    let newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
    newUser.setValue(txtUsername.text, forKey: "username")
    newUser.setValue(txtPassword.text, forKey: "password")
    newUser.setValue(txtEmailAdd.text, forKey: "email")

    do {
        try context.save()
    } catch {}

    print(newUser)
    print("Object Saved.")

This is the code in the LoginVC;

@IBAction func signinTapp(sender: UIButton) {

    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context:NSManagedObjectContext = appDel.managedObjectContext

    let request = NSFetchRequest(entityName: "Users")
    request.returnsObjectsAsFaults = false
    request.predicate = NSPredicate(format: "username = %@", "" + txtUsername.text!)

    let results:NSArray = try! context.executeFetchRequest(request)

    if(results.count > 1){
        let res = results[0] as! NSManagedObject
        txtUsername.text = res.valueForKey("username") as! String
        txtPassword.text = res.valueForKey("password") as! String

        //for res in results {
         //   print(res)

    }else{
        print("Incorrect username and password")
    }

}

Can anyone please advise my the best way forward? - I just need to retrieve  the saved core data and check if it matches.

Here is my Core Data model:

Body:
import UIKit
import CoreData

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var txt_username: UITextField!

@IBOutlet var txt_password: UITextField!

var result = NSArray()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func Log_in(_ sender: Any)
{
    if txt_username.text == "" && txt_password.text == ""
    {
        let alert = UIAlertController(title: "Information", message: "Please enter all the fields", preferredStyle: .alert)

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)
    }
    else

    {

        self.CheckForUserNameAndPasswordMatch(username : txt_username.text! as String, password : txt_password.text! as String)

    }

}

func CheckForUserNameAndPasswordMatch( username: String, password : String)
{
    let app = UIApplication.shared.delegate as! AppDelegate

    let context = app.persistentContainer.viewContext

    let fetchrequest = NSFetchRequest<NSFetchRequestResult>(entityName: "LoginDetails")

    let predicate = NSPredicate(format: "username = %@", username)

    fetchrequest.predicate = predicate
    do
    {
        result = try context.fetch(fetchrequest) as NSArray

        if result.count>0
        {
            let objectentity = result.firstObject as! LoginDetails

            if objectentity.username == username && objectentity.password == password
            {
                print("Login Succesfully")
            }
            else
            {
                print("Wrong username or password !!!")
            }
        }
    }

    catch
    {
        let fetch_error = error as NSError
        print("error", fetch_error.localizedDescription)
    }

}

}

Registration page
==================>

import UIKit
import CoreData

class RegistrationPage: UIViewController, UITextFieldDelegate {

@IBOutlet var txt_user: UITextField!

@IBOutlet var txt_mailid: UITextField!

@IBOutlet var txt_pwd: UITextField!

@IBOutlet var txt_cpwd: UITextField!

@IBOutlet var txt_phone: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

@IBAction func register(_ sender: Any)
{
    if txt_user.text == "" || txt_mailid.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == ""
    {
        let alert = UIAlertController(title: "Information", message: "Its Mandatort to enter all the fields", preferredStyle: .alert)

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)

    }

    else if (txt_pwd.text != txt_cpwd.text)
    {
        let alert = UIAlertController(title: "Information", message: "Password does not match", preferredStyle: .alert
        )

        let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)

        alert.addAction(ok)
        alert.addAction(cancel)

        self.present(alert, animated: true, completion: nil)

    }

    else
    {
        let app = UIApplication.shared.delegate as! AppDelegate

        let context = app.persistentContainer.viewContext

        let new_user = NSEntityDescription.insertNewObject(forEntityName: "LoginDetails", into: context)

        new_user.setValue(txt_user.text, forKey: "username")
        new_user.setValue(txt_mailid.text, forKey: "mailid")
        new_user.setValue(txt_pwd.text, forKey: "password")
        new_user.setValue(txt_phone.text, forKey: "phone")

        do
        {
            try context.save()
            print("Registered  Sucessfully")
        }
        catch
        {
            let Fetcherror = error as NSError
            print("error", Fetcherror.localizedDescription)
        }
    }

    self.navigationController?.popViewController(animated: true)

    }
}


问:
How to deploy to EC2 instance , from a .zip file in s3
I have a PHP application zipped and uploaded to a S3 bucket. Now I have created a version of that zip using

```<code>aws elasticbeanstalk create-application-version --application-name <app-name>
--version-label project1 --source-bundle S3Bucket=elasticbeanstalk-
automator,S3Key=project1.zip --region ap-southeast-1
</code>```

After the version is created should I use eb cli, or how should I deploy the zip to an EC2 environment?

答:
Updating the AWS elastic beanstalk environment with environment name, application name, and version label will deploy the application:</p>

```<code>aws elasticbeanstalk update-environment --application-name <your-app-name>  --
environment-name <environment-name-to-deploy>   --version-label <version-
label-to-deploy>
</code>```

Body:
I have a PHP application zipped and uploaded to a S3 bucket. Now I have created a version of that zip using

aws elasticbeanstalk create-application-version --application-name <app-name>
--version-label project1 --source-bundle S3Bucket=elasticbeanstalk-
automator,S3Key=project1.zip --region ap-southeast-1

After the version is created should I use eb cli, or how should I deploy the zip to an EC2 environment?

Body:
Updating the AWS elastic beanstalk environment with environment name, application name, and version label will deploy the application:

aws elasticbeanstalk update-environment --application-name <your-app-name>  --
environment-name <environment-name-to-deploy>   --version-label <version-
label-to-deploy>


问:
Creating flat list from single float or list of floats
I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine:

```<code>L = [A,B,C]
F = [1,2,3]

for f, o in zip(L,F):
    # do stuff
</code>```

Sometimes the subclass has one object and one float

```<code>L = A
F = 1

for f, o in zip(L,F):
    # TypeError
</code>```

This throws an exception because F is not iterable.

If I try:

```<code>F = list(F)
</code>```

This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)).

If I try:

```<code>F = [F]
</code>```

This solves the 1 float case but now returns a nested list when there are two or more floats!

```<code>a = [1,2]
[a] = [[1,2]]
</code>```

Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?

答:
Use extend

```<code>L = []
F = []

L.extend([A])
F.extend([B])

for f,o in zip(L,F):
    # do stuff
</code>```

This should not give you problems both with one item lists and with more than one item lists (it won't be nested).

example 1 item:

```<code>L = []
F = []
A = 1
B = 1
L.extend([A])
F.extend([B])
for f,o in zip(L,F):
    print(f,o)
</code>```

otput

1 1

Example more items

```<code>L = []
F = []
A = [1,2,3]
B = [1,2,3]
L.extend([A])
F.extend([B])
for f,o in zip(L,F):
    print(f,o)
</code>```

output

```<code>1 1
2 2
3 3
</code>```

Body:
I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine:

L = [A,B,C]
F = [1,2,3]

for f, o in zip(L,F):
    # do stuff

Sometimes the subclass has one object and one float

L = A
F = 1

for f, o in zip(L,F):
    # TypeError

This throws an exception because F is not iterable.

If I try:

F = list(F)

This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)).

If I try:

F = [F]

This solves the 1 float case but now returns a nested list when there are two or more floats!

a = [1,2]
[a] = [[1,2]]

Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?

Body:
Use extend

L = []
F = []

L.extend([A])
F.extend([B])

for f,o in zip(L,F):
    # do stuff

This should not give you problems both with one item lists and with more than one item lists (it won't be nested).

example 1 item:

L = []
F = []
A = 1
B = 1
L.extend([A])
F.extend([B])
for f,o in zip(L,F):
    print(f,o)

otput

1 1

Example more items

L = []
F = []
A = [1,2,3]
B = [1,2,3]
L.extend([A])
F.extend([B])
for f,o in zip(L,F):
    print(f,o)

output

1 1
2 2
3 3


问:
RCTBridge in React Native
If my mobile app has more than one RCTRootView usage. Should I reuse the same RCTBridge or create one for each. Assuming both RCTRootView can be on the same VC or different VC. Thank you.</p>

答:
It is recommended to have only one bridge for the entire mobile app. I will be proving the code for iOS.

I will be creating the bridge in Main Application and will be using everywhere.

AppDelegate.h

```<code>    @interface AppDelegate : UIResponder<UIApplicationDelegate,RCTBridgeDelegate>
         @property (nonatomic, strong) UIWindow *window;
         @property (strong) RCTBridge *reactBridge;
    @end
</code>```

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  self.reactBridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:self.reactBridge moduleName:@"ListViewNetworking" initialProperties:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}
</code>```

You can access the bridge everywhere just like this.

```<code>  AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

   [[RCTRootView alloc] initWithBridge:appdelegate.reactBridge moduleName:@"ListViewNetworking" initialProperties:nil];
</code>```

Title: RCTBridge in React Native

Body:
It is recommended to have only one bridge for the entire mobile app. I will be proving the code for iOS.

I will be creating the bridge in Main Application and will be using everywhere.

AppDelegate.h

    @interface AppDelegate : UIResponder<UIApplicationDelegate,RCTBridgeDelegate>
         @property (nonatomic, strong) UIWindow *window;
         @property (strong) RCTBridge *reactBridge;
    @end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  self.reactBridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:self.reactBridge moduleName:@"ListViewNetworking" initialProperties:nil];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

You can access the bridge everywhere just like this.

  AppDelegate *appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

   [[RCTRootView alloc] initWithBridge:appdelegate.reactBridge moduleName:@"ListViewNetworking" initialProperties:nil];


问:
npm errors while attempting to use barcode scanner
I'm trying to use a barcode reader, because I really need it for my app, but I'm unable to start any projects that I've found.

For example, https://github.com/ideacreation/react-native-barcodescanner. Which command should I use to start this?

```<code>$ cd /c/Users/Me/Desktop/react-native-barcodescanner-master
$ npm i
$ npm i --save react-native-barcodescanner
npm ERR! Windows_NT6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Me\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "i" "--save" "react-native-barcodescanner"
npm ERR! node v6.11.3
npm ERR! npm  v3.10.10
npm ERR! code ENOSELF
npm ERR! Refusing to install react-native-barcodescanner as a dependency of itself
$ npm start npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Me\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.3 npm ERR! npm  v3.10.10
npm ERR! missing script: start
</code>```

答:
This library is deprecated with react-native v0.44, you should use react-native-camera.

The command you used npm i --save react-native-barcodescanner
 is for install this lib to your project.

If you still want to use this lib, follow this instruction:

Import:

```<code>import BarcodeScanner from 'react-native-barcodescanner';
</code>```

Then use in your Component:

```<code>render() {
    return (
      <BarcodeScanner
        onBarCodeRead={this.barcodeReceived}
        style={{ flex: 1 }}
        torchMode={this.state.torchMode}
        cameraType={this.state.cameraType}
      />
    );
  }
</code>```

Body:
I'm trying to use a barcode reader, because I really need it for my app, but I'm unable to start any projects that I've found.

For example, https://github.com/ideacreation/react-native-barcodescanner. Which command should I use to start this?

$ cd /c/Users/Me/Desktop/react-native-barcodescanner-master
$ npm i
$ npm i --save react-native-barcodescanner
npm ERR! Windows_NT6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Me\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "i" "--save" "react-native-barcodescanner"
npm ERR! node v6.11.3
npm ERR! npm  v3.10.10
npm ERR! code ENOSELF
npm ERR! Refusing to install react-native-barcodescanner as a dependency of itself
$ npm start npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Me\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.3 npm ERR! npm  v3.10.10
npm ERR! missing script: start

Body:
This library is deprecated with react-native v0.44, you should use react-native-camera.

The command you used npm i --save react-native-barcodescanner
 is for install this lib to your project.

If you still want to use this lib, follow this instruction:

Import:

import BarcodeScanner from 'react-native-barcodescanner';

Then use in your Component:

render() {
    return (
      <BarcodeScanner
        onBarCodeRead={this.barcodeReceived}
        style={{ flex: 1 }}
        torchMode={this.state.torchMode}
        cameraType={this.state.cameraType}
      />
    );
  }


答:
Use USING, per the documentation:

USING ( join_column [, ...] )

A clause of the form USING ( a, b, ... ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.

```<code>select *
from current_exclusive
full join current_table using (id_station, area_type)
full join current_cashier using (id_station, area_type)
</code>```

Title: Select not null column in full join postgresql

Body:
Use USING, per the documentation:

USING ( join_column [, ...] )

A clause of the form USING ( a, b, ... ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.

select *
from current_exclusive
full join current_table using (id_station, area_type)
full join current_cashier using (id_station, area_type)


问:
What is the pattern matching expression for KA-05-AA-0000 in html pattern attribute?
What is The Regular expression for pattern matching KA-05-AA-0000?</p>

答:
/[A-Z][A-Z]-[0-9][0-9]-[A-Z][A-Z]-[0-9][0-9][0-9][0-9]/g</p>

```<code>[A-Z] Match a single character present in the range between A (index 65) and Z (index 90) case sensitive)
- matches the character - literally (case sensitive)
[0-9] Match a single character present in the range between 0 (index 48) and 9 (index 57) (case sensitive)
g modifier: global. All matches (don't return after first match)
</code>```

Body:
/[A-Z][A-Z]-[0-9][0-9]-[A-Z][A-Z]-[0-9][0-9][0-9][0-9]/g

[A-Z] Match a single character present in the range between A (index 65) and Z (index 90) case sensitive)
- matches the character - literally (case sensitive)
[0-9] Match a single character present in the range between 0 (index 48) and 9 (index 57) (case sensitive)
g modifier: global. All matches (don't return after first match)


问:
how to call connection in class functions
I establish connection in __construct() it is proper working but when I calling this->con variable in other function of class. it is not working.
I am inserting data in database but data not inserting into database while it's printing correct query in insertUserData().

```<code>Class RP_Common {

    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '12345';
    private $_database = 'shipment';

    protected $con;

    public function __construct()
    {
        if (!isset($this->con)) {

            $this->con = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->con) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->con;
    }

    /**

    for inserting user_data
    */

    public function insertUserData($username,$usermobile,$useremail,$userpassword){

        //echo $this->con;

         echo $query="insert into user_table(user_name,user_mobile,user_email,user_password) values('$username',$usermobile,$useremail,$userpassword) ";

        $res=mysqli_query($this->con,$query);

        if($res){
            echo "data inserted successfully";
        }

    }
</code>```

答:
You need a space after user_table and values

```<code>INSERT INTO user_table (user_name,user_mobile,user_email,user_password) values ('$username',$usermobile,$useremail,$userpassword);
</code>```

To see what went wrong with the query, you can use mysqli_error($conn)

```<code>if($res){
  echo "data inserted successfully";
}else{
  echo mysqli_error($this->con);
}
</code>```

Body:
I establish connection in __construct() it is proper working but when I calling this->con variable in other function of class. it is not working.
I am inserting data in database but data not inserting into database while it's printing correct query in insertUserData().

Class RP_Common {

    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '12345';
    private $_database = 'shipment';

    protected $con;

    public function __construct()
    {
        if (!isset($this->con)) {

            $this->con = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->con) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->con;
    }

    /**

    for inserting user_data
    */

    public function insertUserData($username,$usermobile,$useremail,$userpassword){

        //echo $this->con;

         echo $query="insert into user_table(user_name,user_mobile,user_email,user_password) values('$username',$usermobile,$useremail,$userpassword) ";

        $res=mysqli_query($this->con,$query);

        if($res){
            echo "data inserted successfully";
        }

    }

Body:
You need a space after user_table and values

INSERT INTO user_table (user_name,user_mobile,user_email,user_password) values ('$username',$usermobile,$useremail,$userpassword);

To see what went wrong with the query, you can use mysqli_error($conn)

if($res){
  echo "data inserted successfully";
}else{
  echo mysqli_error($this->con);
}


问:
Deserialization of object in Class Library while accepting an interface parameter (C#, MVC)
Given the interface:

```<code>interface IObject
{
   public string Name {get;set}
}
</code>```

And the following objects:

```<code>class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}
</code>```

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

```<code>public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}
</code>```

Obviously, you can't instantiate an interface, so

```<code>result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
</code>```

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

答:
One approach I can think of, is to add an internal helper class that you deserialize to first and from there generate your A and B objects.  Something like this (Note: I am assuming your GUID is without a separator character).

```<code>internal class Helper
{
    public string _name {get;set;}
    public string _id {get;set;}

    public IObject GetAOrBObject()
    {
        if (_id.Length == 32) // Assume GUID with no separator like '-'
        {
            return new A() { Name = _name, ID = Guid.Parse(_id) };
        }
        else
        {
            return new B() { Name = _name, ID = int.Parse(_id) };
        }
    }
}
</code>```

Then you can change the code in your loop to this:

```<code>foreach(var d in data)
{
    var temp = JsonConvert.DeserializeObject<Helper>(Convert.ToString(d)));
    result.add(temp.GetAOrBObject());
}
return result;
</code>```

Body:
Given the interface:

interface IObject
{
   public string Name {get;set}
}

And the following objects:

class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}

Obviously, you can't instantiate an interface, so

result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

Body:
One approach I can think of, is to add an internal helper class that you deserialize to first and from there generate your A and B objects.  Something like this (Note: I am assuming your GUID is without a separator character).

internal class Helper
{
    public string _name {get;set;}
    public string _id {get;set;}

    public IObject GetAOrBObject()
    {
        if (_id.Length == 32) // Assume GUID with no separator like '-'
        {
            return new A() { Name = _name, ID = Guid.Parse(_id) };
        }
        else
        {
            return new B() { Name = _name, ID = int.Parse(_id) };
        }
    }
}

Then you can change the code in your loop to this:

foreach(var d in data)
{
    var temp = JsonConvert.DeserializeObject<Helper>(Convert.ToString(d)));
    result.add(temp.GetAOrBObject());
}
return result;


问:
Lack of editing property and setEditing:animated: in UICollectionViewCell
Unlikely UITableViewCell, UICollectionViewCell lacks of setEditing:animated: and the editing property.

Is this by design? Is Apple enforcing other best practice for handling the editing in a UICollectionView and its cells?

答:
If you are changing some state like allowsMultipleSelection in your UICollectionView when editing:

```<code>override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    collectionView.allowsMultipleSelection = editing
}
</code>```

You could simply add this to your UICollectionViewCell subclass:

```<code>var isEditing: Bool {
    return (superview as! UICollectionView).allowsMultipleSelection
}
</code>```

Body:
If you are changing some state like allowsMultipleSelection in your UICollectionView when editing:

override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    collectionView.allowsMultipleSelection = editing
}

You could simply add this to your UICollectionViewCell subclass:

var isEditing: Bool {
    return (superview as! UICollectionView).allowsMultipleSelection
}


问:
On hover the sub menu is not staying as expected
in my code when i try to hover the main menu then the sub menu should open and i can click the other link of sub menu as well.I have done almost everything but except when i try to hover the sub menu it is not showing.

I hover on menu i can see the sub-menu but when i try to go sub-menu it disappears

```<code> $(document).ready(function(){

        $(".accounts").mouseenter(function() {
            $(".underdrop").slideDown();
        });
        $(".accounts").mouseleave(function() {
            $(".underdrop").slideUp();
        });

 });

.accounts{

display: inline-block;

position: relative;
}
.underdrop{
    width: 150px;
    position: absolute;
    background-color: #fff;
    margin-top: 20px;
    margin-left:250px;
    border: 1px solid #d7d7d7;
    padding-left: 0px;
    height:230px;
    z-index: 999999;
    -webkit-box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
       -moz-box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
            box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
    display:none;

}

.underdrop::before{
    content: '';
    position: absolute;
    border: 15px solid #4b968a;
    border-bottom-color: transparent;
    border-right-color: transparent;
    margin-left: 55px;
    transform: rotate(45deg );
    margin-top: -15.5px;
    z-index: 9999
}
</code>```

DEMO

答:
update your document.ready function like this. i have checked in jsfiddle

```<code>    $(document).ready(function(){

        $(".accounts").mouseenter(function() {
            $(".underdrop").slideDown();
        });
        $(".underdrop").mouseleave(function() {
            $(".underdrop").slideUp();
        });

 });
</code>```

check updated jsfiddle here

Body:
in my code when i try to hover the main menu then the sub menu should open and i can click the other link of sub menu as well.I have done almost everything but except when i try to hover the sub menu it is not showing.

I hover on menu i can see the sub-menu but when i try to go sub-menu it disappears

 $(document).ready(function(){

        $(".accounts").mouseenter(function() {
            $(".underdrop").slideDown();
        });
        $(".accounts").mouseleave(function() {
            $(".underdrop").slideUp();
        });

 });

.accounts{

display: inline-block;

position: relative;
}
.underdrop{
    width: 150px;
    position: absolute;
    background-color: #fff;
    margin-top: 20px;
    margin-left:250px;
    border: 1px solid #d7d7d7;
    padding-left: 0px;
    height:230px;
    z-index: 999999;
    -webkit-box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
       -moz-box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
            box-shadow: 0px 1px 9px 0px rgba(0,0,0,0.75);
    display:none;

}

.underdrop::before{
    content: '';
    position: absolute;
    border: 15px solid #4b968a;
    border-bottom-color: transparent;
    border-right-color: transparent;
    margin-left: 55px;
    transform: rotate(45deg );
    margin-top: -15.5px;
    z-index: 9999
}

DEMO

Body:
update your document.ready function like this. i have checked in jsfiddle

    $(document).ready(function(){

        $(".accounts").mouseenter(function() {
            $(".underdrop").slideDown();
        });
        $(".underdrop").mouseleave(function() {
            $(".underdrop").slideUp();
        });

 });

check updated jsfiddle here


问:
Cloud Haskell - How to write "pure" for Closures?
I've been playing with Cloud Haskell. I've noticed in the hackage documentation there's a kind of applicative interface. But in particular I'm trying to find or write a function closurePure with the following signature:

```<code>closurePure :: (Typeable a, Binary a) => a -> Closure a
</code>```

This is basically a restricted version of pure.

Whilst the Closure datatype itself is abstract, the following closure provided:

```<code>closure :: Static (ByteString -> a) -> ByteString -> Closure a
</code>```

So I can get this far:

```<code>closurePure :: (Typeable a, Binary a) => a -> Closure a
closurePure x = closure ??? (encode x)
</code>```

The problem is what to put where the ???s are.

My first attempt was the following:

```<code>myDecode :: (Typeable a, Binary a) => Static (ByteString -> a)
myDecode = staticPtr (static decode)
</code>```

But upon reading the GHC docs on static pointers, the show example suggested to me that you can't have a constraint because a constrained function doesn't have a Typeable instance. So I tried the work around suggested using Dict:

```<code>myDecode :: Typeable a => Static (Dict (Binary a) -> ByteString -> a)
myDecode = staticPtr (static (\Dict -> decode))
</code>```

But now I've got the wrong type that doesn't fit into the closure function above.

Is there anyway to write closurePure or something similar (or have I missed it in the Cloud Haskell docs)? Raising binary plain types to Closures seems essential to using the applicative interface given, but I can't work out how to do it.

Note that I can do this:

```<code>class StaticDecode a where
  staticPtrDecode :: StaticPtr (ByteString -> a)

instance StaticDecode Int where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Float where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Integer where
  staticPtrDecode = static Data.Binary.decode

-- More instances etc...

myPure :: forall a. (Typeable a, StaticDecode a, Binary a) => a -> Closure a
myPure x = closure (staticPtr staticPtrDecode) (encode x)
</code>```

Which works well but basically requires me to repeat an instance for each Binary instance. It seems messy and I'd prefer another way.

答:
Let's take a moment to consider what you are asking for.  Recall that typeclasses are basically shorthand for dictionary passing.  So let's rewrite:

```<code>data BinaryDict a = BinaryDict
  { bdEncode :: a -> ByteString
  , bdDecode :: ByteString -> a
  }
</code>```

Now you wish to write a function:

```<code>closurePure :: (Typeable a) => BinaryDict a -> a -> Closure a
</code>```

Your attempt is:

```<code>closurePure bdict = closure (staticPtr (static (bdDecode bdict))) . bdEncode bdict
</code>```

Now that we can see what's going on explicitly, we can see that static's argument cannot be closed.  If BinaryDicts were allowed to be created willy nilly, say from user data, this function would be impossible.  We would instead need:

```<code>closurePure :: (Typeable a) => Static (BinaryDict a) -> a -> Closure a
</code>```

That is, we need entries for the needed Binary instances in the static pointer table.  Hence your enumeration solution, and why I suspect that such a solution is required.  We also can't expect to enumerate it too automatically, because there are infinitely many instances.

It seems silly to me, however, since instances seem like just the sorts of things that you would want to be static automatically.  They are static by nature (what's that, reflection? I can't hear you).  This was probably at least ruminated about in the distributed Haskell papers (I haven't read them).

We could solve this problem in general by simply creating a class that concretely enumerates every instance of every class (déjà vu?).

```<code>class c => StaticConstraint c where
    staticConstraint :: StaticPtr (Dict c)
instance StaticConstraint (Show Int) where
    staticConstraint = static Dict
-- a handful more lines...
</code>```

Somewhat more seriously, if you really don't want to enumerate (I don't blame you), you can at least ease the pain with a calling convention:

```<code>closurePure :: (Typeable a, Binary a) => StaticPtr (ByteString -> a) -> a -> Closure a
closurePure decodePtr = closure (staticPtr decodePtr) . encode

someClosure :: Closure Int
someClosure = closurePure (static decode) 42
</code>```

This nonsense is necessary because static is a "syntactic form" rather than a function -- by mentioning it, we indicate that the Binary instance for Int must actually be generated and recorded in the static pointer table.

If you are feeling cheeky you could enable {-# LANGUAGE CPP #-} and

```<code>-- PURE :: (Binary a, Typeable a) => a -> Closure a, I promise
#define PURE (closurePure (static decode))

someClosure :: Closure Int
someClosure = PURE 42
</code>```

Maybe someday Haskell will take the next step and graduate to the time-tested Segmentation fault (core dumped) of its predecessors instead of spouting off those arrogant type errors.

Body:
I've been playing with Cloud Haskell. I've noticed in the hackage documentation there's a kind of applicative interface. But in particular I'm trying to find or write a function closurePure with the following signature:

closurePure :: (Typeable a, Binary a) => a -> Closure a

This is basically a restricted version of pure.

Whilst the Closure datatype itself is abstract, the following closure provided:

closure :: Static (ByteString -> a) -> ByteString -> Closure a

So I can get this far:

closurePure :: (Typeable a, Binary a) => a -> Closure a
closurePure x = closure ??? (encode x)

The problem is what to put where the ???s are.

My first attempt was the following:

myDecode :: (Typeable a, Binary a) => Static (ByteString -> a)
myDecode = staticPtr (static decode)

But upon reading the GHC docs on static pointers, the show example suggested to me that you can't have a constraint because a constrained function doesn't have a Typeable instance. So I tried the work around suggested using Dict:

myDecode :: Typeable a => Static (Dict (Binary a) -> ByteString -> a)
myDecode = staticPtr (static (\Dict -> decode))

But now I've got the wrong type that doesn't fit into the closure function above.

Is there anyway to write closurePure or something similar (or have I missed it in the Cloud Haskell docs)? Raising binary plain types to Closures seems essential to using the applicative interface given, but I can't work out how to do it.

Note that I can do this:

class StaticDecode a where
  staticPtrDecode :: StaticPtr (ByteString -> a)

instance StaticDecode Int where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Float where
  staticPtrDecode = static Data.Binary.decode

instance StaticDecode Integer where
  staticPtrDecode = static Data.Binary.decode

-- More instances etc...

myPure :: forall a. (Typeable a, StaticDecode a, Binary a) => a -> Closure a
myPure x = closure (staticPtr staticPtrDecode) (encode x)

Which works well but basically requires me to repeat an instance for each Binary instance. It seems messy and I'd prefer another way.

Body:
Let's take a moment to consider what you are asking for.  Recall that typeclasses are basically shorthand for dictionary passing.  So let's rewrite:

data BinaryDict a = BinaryDict
  { bdEncode :: a -> ByteString
  , bdDecode :: ByteString -> a
  }

Now you wish to write a function:

closurePure :: (Typeable a) => BinaryDict a -> a -> Closure a

Your attempt is:

closurePure bdict = closure (staticPtr (static (bdDecode bdict))) . bdEncode bdict

Now that we can see what's going on explicitly, we can see that static's argument cannot be closed.  If BinaryDicts were allowed to be created willy nilly, say from user data, this function would be impossible.  We would instead need:

closurePure :: (Typeable a) => Static (BinaryDict a) -> a -> Closure a

That is, we need entries for the needed Binary instances in the static pointer table.  Hence your enumeration solution, and why I suspect that such a solution is required.  We also can't expect to enumerate it too automatically, because there are infinitely many instances.

It seems silly to me, however, since instances seem like just the sorts of things that you would want to be static automatically.  They are static by nature (what's that, reflection? I can't hear you).  This was probably at least ruminated about in the distributed Haskell papers (I haven't read them).

We could solve this problem in general by simply creating a class that concretely enumerates every instance of every class (déjà vu?).

class c => StaticConstraint c where
    staticConstraint :: StaticPtr (Dict c)
instance StaticConstraint (Show Int) where
    staticConstraint = static Dict
-- a handful more lines...

Somewhat more seriously, if you really don't want to enumerate (I don't blame you), you can at least ease the pain with a calling convention:

closurePure :: (Typeable a, Binary a) => StaticPtr (ByteString -> a) -> a -> Closure a
closurePure decodePtr = closure (staticPtr decodePtr) . encode

someClosure :: Closure Int
someClosure = closurePure (static decode) 42

This nonsense is necessary because static is a "syntactic form" rather than a function -- by mentioning it, we indicate that the Binary instance for Int must actually be generated and recorded in the static pointer table.

If you are feeling cheeky you could enable {-# LANGUAGE CPP #-} and

-- PURE :: (Binary a, Typeable a) => a -> Closure a, I promise
#define PURE (closurePure (static decode))

someClosure :: Closure Int
someClosure = PURE 42

Maybe someday Haskell will take the next step and graduate to the time-tested Segmentation fault (core dumped) of its predecessors instead of spouting off those arrogant type errors.


问:
WCF database login always fails
I am using Windows 7 Ultimate 64 bit.

I made a mistake of opening a VS2008 .net 3.5 wcf application in VS2010 and building it and then following the upgrade prompts.

Since then, any database access from my wcf web site results in a login failure. If I choose file as the web site, then my own login is rejected by the sql server. If I publish to http, no identity is assigned to my application pool (ASP.NET v4.0) can login even though I add it as a user to the database.

This is driving me nuts. When I was working with .net 3.5 and VS2008, it worked fine. I had to add the login for the identity of the application pool (DefaultAppPool) after I published to http, but then it worked fine.

If I write a simple win forms application and use select my database using the Data Source Configuration Wizard, I have access to my database. It's not my database login credentials, but something else that WCF requires.

Can anyone shed some light on this?
Otherwise I might need a new screen.

PS I ran these to try and fix things, but it resolved nothing.

```<code>"%WINDIR%\Microsoft.Net\Framework\v4.0.30319\aspnet_regiis" -i -enable
"%WINDIR%\Microsoft.Net\Framework\v4.0.30319\ServiceModelReg.exe" -r
</code>```

答:
I found the answer (at least I think I did).

With VS2008 .net 3.5 when I use a wcf class library in my web site I had to very little to the web.config.
I had to make a few adjustments so that it would use my class library and not the service and code behind class it adds by default.

This time I had to copy and paste the ConnectionStrings element from my wcf class library app.config file.
I did not have to do this before (I double checked another example).

The web.config file appears to much smaller when built using VS2010 .NET 4.0 than with VS2008 .NET 3.5.
It looks like one has to migrate more stuff across than before.

Title: WCF database login always fails

Body:
I am using Windows 7 Ultimate 64 bit.

I made a mistake of opening a VS2008 .net 3.5 wcf application in VS2010 and building it and then following the upgrade prompts.

Since then, any database access from my wcf web site results in a login failure. If I choose file as the web site, then my own login is rejected by the sql server. If I publish to http, no identity is assigned to my application pool (ASP.NET v4.0) can login even though I add it as a user to the database.

This is driving me nuts. When I was working with .net 3.5 and VS2008, it worked fine. I had to add the login for the identity of the application pool (DefaultAppPool) after I published to http, but then it worked fine.

If I write a simple win forms application and use select my database using the Data Source Configuration Wizard, I have access to my database. It's not my database login credentials, but something else that WCF requires.

Can anyone shed some light on this?
Otherwise I might need a new screen.

PS I ran these to try and fix things, but it resolved nothing.

"%WINDIR%\Microsoft.Net\Framework\v4.0.30319\aspnet_regiis" -i -enable
"%WINDIR%\Microsoft.Net\Framework\v4.0.30319\ServiceModelReg.exe" -r


问:
How to convert array of objects to object with index?
I have a array like this->

```<code>var jsonResponse = [
     {
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    },
    {
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    }
]
</code>```

And I want to convert it to ->

```<code>{
    "abc" : {
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    },
    "ccc": {
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    }
]
</code>```

Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?

答:
```<code>let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)

console.log(JSON.stringify(indexedResult));
</code>```

Body:
I have a array like this->

var jsonResponse = [
     {
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    },
    {
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    }
]

And I want to convert it to ->

{
    "abc" : {
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    },
    "ccc": {
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}
        ]
    }
]

Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?


问:
Method return statement vs try-catch
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}
```

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

答:
In case of j = 0 exception will be thrown and caught (by catch). And message will be printed. The question is: If I do not want to return any result from this method in the case of dividing by zero I still MUST return some value or there is another way? Using 'throw' from catch clause?

You must either return a value matching the signature (int in this example) or throw something, otherwise the program will not compile.

And another observation: if I uncomment last return result statement I got an error message:
  variable result might not have been initialized

The result variable is assigned in a try block.
The compiler doesn't know at which exact point the exception might occur.
If an exception occurs before the assignment is completed,
then at the point of the return result statement,
the variable result might not have a value.
The solution is to set a value before the try block.

And if I comment last 'return result' I got an error message:
  missing return statement
  But I've already included return statement in try clause.

In this example, if an exception occurs in the try block,
then the catch block and the rest of the body of the function is executed,
and there is no other return statement to match the signature of the method.
You must return an int value on all execution paths.

Title: Method return statement vs try-catch

Body:
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!


问:
Multiple different conditions and if statments within a loop
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

```<code>for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}
</code>```

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

答:
The user has requested to map the numbers given in H07_NACE$NACE2.Code to the letters "A" to "U" according to given rules he has hardcoded in a number of if clauses.

A more flexible approach (and less tedious to code) is to use a lookup table (or constraint vector as Joseph Wood called it in his answer).

With data.table, we can use either a rolling join or a non-equi update join to do the mapping.

Sample data to be mapped

```<code>set.seed(1)
H07_NACE <- data.frame(NACE2.Code = sample(99, 10, replace = TRUE))
</code>```

Rolling join

For the rolling join, we specify the mapping rules by tiling the number range 1:99 contiguously and giving the start number of each tile.

```<code>library(data.table)
# set up lookup table
lookup <- data.table(Code = c(1, 4, 21, 45, 61:75, 98, 99),
                     Sector = LETTERS[1:21])
lookup
</code>```

```<code>    Code Sector
 1:    1      A
 2:    4      B
 3:   21      C
 4:   45      D
 5:   61      E
 6:   62      F
 7:   63      G
 8:   64      H
 9:   65      I
10:   66      J
11:   67      K
12:   68      L
13:   69      M
14:   70      N
15:   71      O
16:   72      P
17:   73      Q
18:   74      R
19:   75      S
20:   98      T
21:   99      U
    Code Sector
</code>```

```<code># map Code to Sector
lookup[setDT(H07_NACE), on = .(Code = NACE2.Code), roll = TRUE]
</code>```

```<code>    Code Sector
 1:   27      C
 2:   37      C
 3:   57      D
 4:   90      S
 5:   20      B
 6:   89      S
 7:   94      S
 8:   66      J
 9:   63      G
10:    7      B
</code>```

If the H07_NACE is to be updated we can append a new column by

```<code>setDT(H07_NACE)[, NACE2.Sector := lookup[H07_NACE, on = .(Code = NACE2.Code),
  roll = TRUE, Sector]][]
</code>```

```<code>    NACE2.Code NACE2.Sector
 1:         27            C
 2:         37            C
 3:         57            D
 4:         90            S
 5:         20            B
 6:         89            S
 7:         94            S
 8:         66            J
 9:         63            G
10:          7            B
</code>```

Non-equi update join

For the non-equi update join, we specify the mapping rules by giving the lower and upper bounds. This can be derived from lookup by

```<code>lookup2 <- lookup[, .(Sector, lower = Code,
                      upper = shift(Code - 1L, type = "lead", fill = max(Code)))]
lookup2
</code>```

```<code>    Sector lower upper
 1:      A     1     3
 2:      B     4    20
 3:      C    21    44
 4:      D    45    60
 5:      E    61    61
 6:      F    62    62
 7:      G    63    63
 8:      H    64    64
 9:      I    65    65
10:      J    66    66
11:      K    67    67
12:      L    68    68
13:      M    69    69
14:      N    70    70
15:      O    71    71
16:      P    72    72
17:      Q    73    73
18:      R    74    74
19:      S    75    97
20:      T    98    98
21:      U    99    99
    Sector lower upper
</code>```

The new column is created by

```<code>setDT(H07_NACE)[lookup2, on = .(NACE2.Code >= lower, NACE2.Code <= upper),
                NACE2.Sector := Sector][]
</code>```

```<code>library(data.table)
# set up lookup table
lookup <- data.table(Code = c(1, 4, 21, 45, 61:75, 98, 99),
                     Sector = LETTERS[1:21])
lookup
</code>```0

Body:
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

Body:
The user has requested to map the numbers given in H07_NACE$NACE2.Code to the letters "A" to "U" according to given rules he has hardcoded in a number of if clauses.

A more flexible approach (and less tedious to code) is to use a lookup table (or constraint vector as Joseph Wood called it in his answer).

With data.table, we can use either a rolling join or a non-equi update join to do the mapping.

Sample data to be mapped

set.seed(1)
H07_NACE <- data.frame(NACE2.Code = sample(99, 10, replace = TRUE))

Rolling join

For the rolling join, we specify the mapping rules by tiling the number range 1:99 contiguously and giving the start number of each tile.

library(data.table)
# set up lookup table
lookup <- data.table(Code = c(1, 4, 21, 45, 61:75, 98, 99),
                     Sector = LETTERS[1:21])
lookup

    Code Sector
 1:    1      A
 2:    4      B
 3:   21      C
 4:   45      D
 5:   61      E
 6:   62      F
 7:   63      G
 8:   64      H
 9:   65      I
10:   66      J
11:   67      K
12:   68      L
13:   69      M
14:   70      N
15:   71      O
16:   72      P
17:   73      Q
18:   74      R
19:   75      S
20:   98      T
21:   99      U
    Code Sector

# map Code to Sector
lookup[setDT(H07_NACE), on = .(Code = NACE2.Code), roll = TRUE]

    Code Sector
 1:   27      C
 2:   37      C
 3:   57      D
 4:   90      S
 5:   20      B
 6:   89      S
 7:   94      S
 8:   66      J
 9:   63      G
10:    7      B

If the H07_NACE is to be updated we can append a new column by

setDT(H07_NACE)[, NACE2.Sector := lookup[H07_NACE, on = .(Code = NACE2.Code),
  roll = TRUE, Sector]][]

    NACE2.Code NACE2.Sector
 1:         27            C
 2:         37            C
 3:         57            D
 4:         90            S
 5:         20            B
 6:         89            S
 7:         94            S
 8:         66            J
 9:         63            G
10:          7            B

Non-equi update join

For the non-equi update join, we specify the mapping rules by giving the lower and upper bounds. This can be derived from lookup by

lookup2 <- lookup[, .(Sector, lower = Code,
                      upper = shift(Code - 1L, type = "lead", fill = max(Code)))]
lookup2

    Sector lower upper
 1:      A     1     3
 2:      B     4    20
 3:      C    21    44
 4:      D    45    60
 5:      E    61    61
 6:      F    62    62
 7:      G    63    63
 8:      H    64    64
 9:      I    65    65
10:      J    66    66
11:      K    67    67
12:      L    68    68
13:      M    69    69
14:      N    70    70
15:      O    71    71
16:      P    72    72
17:      Q    73    73
18:      R    74    74
19:      S    75    97
20:      T    98    98
21:      U    99    99
    Sector lower upper

The new column is created by

setDT(H07_NACE)[lookup2, on = .(NACE2.Code >= lower, NACE2.Code <= upper),
                NACE2.Sector := Sector][]

    NACE2.Code NACE2.Sector
 1:         27            C
 2:         37            C
 3:         57            D
 4:         90            S
 5:         20            B
 6:         89            S
 7:         94            S
 8:         66            J
 9:         63            G
10:          7            B


问:
Share redis storage between multiple apps
I am using redis in a node application for caching data and now i want to access and modify stored data using a django application on the same server but i can't access to the data.

Django connection:

```<code>CACHES = {
  "default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/0",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
    }
  }
}
</code>```

using keys * command in terminal:

```<code>$ redis-cli
127.0.0.1:6379> keys *
1) "sess:Ok0eYOko5WaV7njfX04qgqG1oYe0xiL1"   -> this key is set in node
2) ":1:from-django"   -> this key is set in django
</code>```

Accessing keys in django application:

```<code>keys = cache.keys('*')
print(keys)  # prints only one key => ['from-django']
</code>```

I can't access first key that is set in node application and also django stored keys are prifixed with :1: by default!

I want to share all keys between node and django but they only access their own keys.

Any idea?

答:
You can access all of data from any where, But you are working with Redis in Cache model! and all of Cache systems has own unique data structure, You must work with Redis in Database model and scan it yourself.
Use Python Redis package to access all of Redis in your application.</p>

Body:
I am using redis in a node application for caching data and now i want to access and modify stored data using a django application on the same server but i can't access to the data.

Django connection:

CACHES = {
  "default": {
    "BACKEND": "django_redis.cache.RedisCache",
    "LOCATION": "redis://127.0.0.1:6379/0",
    "OPTIONS": {
        "CLIENT_CLASS": "django_redis.client.DefaultClient",
    }
  }
}

using keys * command in terminal:

$ redis-cli
127.0.0.1:6379> keys *
1) "sess:Ok0eYOko5WaV7njfX04qgqG1oYe0xiL1"   -> this key is set in node
2) ":1:from-django"   -> this key is set in django

Accessing keys in django application:

keys = cache.keys('*')
print(keys)  # prints only one key => ['from-django']

I can't access first key that is set in node application and also django stored keys are prifixed with :1: by default!

I want to share all keys between node and django but they only access their own keys.

Any idea?


问:
htaccess file to tidy up urls causes 500 server error if a trailing slash is added to the url
Hi please can anyone help,

I've written an htaccess file to tidy up my urls & remove the .php.  It all seems to work well but if a trailing slash is added onto a url now the .php has gone I get a 500 server error.  What I really want to happen is if a trailing slash is added then it's handled smoothly and redirected to the no trailing slash option.  This seems to work on the homepage, but not on any other page.

My website is www.bekcruddace.co.uk & the htaccess file is:

```<code>RewriteEngine on

#Redirects example.com to www.example.com
RewriteCond %{HTTP_HOST} ^bekcruddace.co.uk$
RewriteRule ^/?$ "http\:\/\/www\.bekcruddace\.co\.uk\/" [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
</code>```

Please could anyone offer any pointers?

I should also mention that the news sections is a separate plugin that runs independently so the url is slightly different & isn't relevant to my question.

Thank you.

答:
If you request  /file/ your rule rewrites it to an invalid location /file/.php . That is why your server is producing a 500 error.

You need to make the traling slash optional in your pattern so that the slash is excluded from the capture group:

```<code>RewriteRule ^(.*)/?$ $1.php
</code>```

Body:
Hi please can anyone help,

I've written an htaccess file to tidy up my urls & remove the .php.  It all seems to work well but if a trailing slash is added onto a url now the .php has gone I get a 500 server error.  What I really want to happen is if a trailing slash is added then it's handled smoothly and redirected to the no trailing slash option.  This seems to work on the homepage, but not on any other page.

My website is www.bekcruddace.co.uk & the htaccess file is:

RewriteEngine on

#Redirects example.com to www.example.com
RewriteCond %{HTTP_HOST} ^bekcruddace.co.uk$
RewriteRule ^/?$ "http\:\/\/www\.bekcruddace\.co\.uk\/" [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

Please could anyone offer any pointers?

I should also mention that the news sections is a separate plugin that runs independently so the url is slightly different & isn't relevant to my question.

Thank you.

Body:
If you request  /file/ your rule rewrites it to an invalid location /file/.php . That is why your server is producing a 500 error.

You need to make the traling slash optional in your pattern so that the slash is excluded from the capture group:

RewriteRule ^(.*)/?$ $1.php