问:
Objective C : How to Pass Instance Variable of a singleton class to other class from another class?
Suppose I am creating a static library and in which I have two NSObject Classes Named as ClassA and ClassB, User can Access ClassA.h to execute the functions inside library. Now I've some functions defined into ClassB and I want user to execute these functions from their ViewController as per their need but I don't want to give ClassB.h to user so how user can access it using ClassA.

ClassA.h

```<code>#import <Foundation/Foundation.h>

@interface ClassA : NSObject

+ (void) method_1;
+ (void) method_2;
+ (void) method_3;
//  Tried to pass Instance of ClassB to user ViewController

+ (id) getClassBInstanceObject;

@end
</code>```

ClassA.m

```<code>#import "ClassA.h"
#import "ClassB.h"

@implementation ClassA

+ (void) method_1 {
//Some Stuffs Done Here !!
}

+ (void) method_2 {
//Some Stuffs Done Here !!
}

+ (void) method_3 {
//Some Stuffs Done Here !!
}

//  Tried to pass Instance of ClassB to user ViewController

+ (id) getClassBInstanceObject {
 id objB = [ClassB sharedInstance];
    return objB;
}

@end
</code>```

ClassB.h

```<code>#import <Foundation/Foundation.h>

@interface ClassB : NSObject

+ (id)sharedInstance;
-(void)Test_ClassB_function;
@end
</code>```

ClassB.m

```<code>#import "ClassB.h"

@implementation ClassB

+ (id)sharedInstance {
    static ClassB *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    });
    return instance;
}
-(void)Test_ClassB_function {
    NSLog(@"this is the method called from ClassB !!!!");
}

@end
</code>```

Now User Have a Static library FAT (lib.a) file and ClassA.h File Which He'll include in his project and then he can import ClassA.h into his ViewController Class to execute library functions and user wants to execute Test_ClassB_function using ClassA.

ViewController.h

```<code>#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end
</code>```

ViewController.m

```<code>#import "ViewController.h"
#import "ClassA.h"

@interface ViewController ()

@end

@implementation ViewController

  override func viewDidLoad() {
        super.viewDidLoad()
[ClassA method_1];
[ClassA method_2];
[ClassA method_3];
}

- (IBAction)Button1:(id)sender {
id class_B_Object = [ClassA getClassBInstanceObject];

[class_B_Object Test_ClassB_function];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
</code>```

Can anybody tell me how to achieve this goal in Objective-C.

答:
Maybe try

In ClassA.h

```<code>+ (void) testClassBFunctionFromClassA;
</code>```

In ClassA.m

```<code>+ (void) testClassBFunctionFromClassA{

    [[ClassB sharedInstance] Test_ClassB_function];

}
</code>```

In ViewController.m

```<code>- (IBAction)Button1:(id)sender {
    [ClassA testClassBFunctionFromClassA];
}
</code>```

Body:
Suppose I am creating a static library and in which I have two NSObject Classes Named as ClassA and ClassB, User can Access ClassA.h to execute the functions inside library. Now I've some functions defined into ClassB and I want user to execute these functions from their ViewController as per their need but I don't want to give ClassB.h to user so how user can access it using ClassA.

ClassA.h

#import <Foundation/Foundation.h>

@interface ClassA : NSObject

+ (void) method_1;
+ (void) method_2;
+ (void) method_3;
//  Tried to pass Instance of ClassB to user ViewController

+ (id) getClassBInstanceObject;

@end

ClassA.m

#import "ClassA.h"
#import "ClassB.h"

@implementation ClassA

+ (void) method_1 {
//Some Stuffs Done Here !!
}

+ (void) method_2 {
//Some Stuffs Done Here !!
}

+ (void) method_3 {
//Some Stuffs Done Here !!
}

//  Tried to pass Instance of ClassB to user ViewController

+ (id) getClassBInstanceObject {
 id objB = [ClassB sharedInstance];
    return objB;
}

@end

ClassB.h

#import <Foundation/Foundation.h>

@interface ClassB : NSObject

+ (id)sharedInstance;
-(void)Test_ClassB_function;
@end

ClassB.m

#import "ClassB.h"

@implementation ClassB

+ (id)sharedInstance {
    static ClassB *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    });
    return instance;
}
-(void)Test_ClassB_function {
    NSLog(@"this is the method called from ClassB !!!!");
}

@end

Now User Have a Static library FAT (lib.a) file and ClassA.h File Which He'll include in his project and then he can import ClassA.h into his ViewController Class to execute library functions and user wants to execute Test_ClassB_function using ClassA.

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

ViewController.m

#import "ViewController.h"
#import "ClassA.h"

@interface ViewController ()

@end

@implementation ViewController

  override func viewDidLoad() {
        super.viewDidLoad()
[ClassA method_1];
[ClassA method_2];
[ClassA method_3];
}

- (IBAction)Button1:(id)sender {
id class_B_Object = [ClassA getClassBInstanceObject];

[class_B_Object Test_ClassB_function];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

Can anybody tell me how to achieve this goal in Objective-C.

Body:
Maybe try

In ClassA.h

+ (void) testClassBFunctionFromClassA;

In ClassA.m

+ (void) testClassBFunctionFromClassA{

    [[ClassB sharedInstance] Test_ClassB_function];

}

In ViewController.m

- (IBAction)Button1:(id)sender {
    [ClassA testClassBFunctionFromClassA];
}


来源: stackexchange

问:
JSON with Dynamic Keys while using Retrofit in Android
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

```<code>{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}
</code>```

答:
If you are using the Retrofit then you can directly parse this into some model let's say TestModel
based on your requirement call something like this.

```<code>@GET("your endpoint")
Call<TestModel> getTestData();
</code>```

and here you will get data

```<code>public void getTestData(){
    mApiServiceNetwork.getNetworkService(null,WebConstants.API_ENDPOINT)
            .getTestData()
            .enqueue(new Callback<TestModel>() {
                @Override
                public void onResponse(final Call<TestModel> call, final Response<TestModel> response) {
                    if (response.code()==200){
                        //handle the response
                        TestModel testModel = response.body();
                    }else{
                        //handle the error
                    }
                }

                @Override
                public void onFailure(final Call<TestModel> call, final Throwable t) {

                }
            });
}
</code>```

or

if you are getting data in JSON object then do like this.

```<code> private TestModel getTestModel(JsonObject jsonObject){
        Gson gson = new Gson();
        TestModel  testModel = gson.fromJson(jsonObject,TestModel.class);
        return testModel;
    }
</code>```

and if you are getting data in String then parse into Json object then call above method here is how you can convert string into json object.

```<code>JsonObject jsonParser = new JsonParser().parse(json).getAsJsonObject();
</code>```

and most important your TestModel should be like this below for both the cases.

```<code>public class TestModel {
@SerializedName("Meta Data")
@Expose
private MetaModel mMetaModel;

public MetaModel getMetaModel() {
    return mMetaModel;
}

public void setMetaModel(final MetaModel metaModel) {
    mMetaModel = metaModel;
}

public Map<String, TimeModel> getTimeModel() {
    return mTimeModel;
}

public void setTimeModel(final Map<String, TimeModel> timeModel) {
    mTimeModel = timeModel;
}

@SerializedName("Time Series (1min)")

@Expose
private Map<String,TimeModel> mTimeModel;

public static class MetaModel{

    @SerializedName("1. Information")
    @Expose
    private String _1Information;
    @SerializedName("2. Symbol")
    @Expose
    private String _2Symbol;
    @SerializedName("3. Last Refreshed")
    @Expose
    private String _3LastRefreshed;
    @SerializedName("4. Interval")
    @Expose
    private String _4Interval;
    @SerializedName("5. Output Size")
    @Expose
    private String _5OutputSize;
    @SerializedName("6. Time Zone")
    @Expose
    private String _6TimeZone;

    public String get_1Information() {
        return _1Information;
    }

    public void set_1Information(final String _1Information) {
        this._1Information = _1Information;
    }

    public String get_2Symbol() {
        return _2Symbol;
    }

    public void set_2Symbol(final String _2Symbol) {
        this._2Symbol = _2Symbol;
    }

    public String get_3LastRefreshed() {
        return _3LastRefreshed;
    }

    public void set_3LastRefreshed(final String _3LastRefreshed) {
        this._3LastRefreshed = _3LastRefreshed;
    }

    public String get_4Interval() {
        return _4Interval;
    }

    public void set_4Interval(final String _4Interval) {
        this._4Interval = _4Interval;
    }

    public String get_5OutputSize() {
        return _5OutputSize;
    }

    public void set_5OutputSize(final String _5OutputSize) {
        this._5OutputSize = _5OutputSize;
    }

    public String get_6TimeZone() {
        return _6TimeZone;
    }

    public void set_6TimeZone(final String _6TimeZone) {
        this._6TimeZone = _6TimeZone;
    }
}
public static class TimeModel{
    @SerializedName("1. open")
    @Expose
    private String _1Open;
    @SerializedName("2. high")
    @Expose
    private String _2High;
    @SerializedName("3. low")
    @Expose
    private String _3Low;
    @SerializedName("4. close")
    @Expose
    private String _4Close;
    @SerializedName("5. volume")
    @Expose
    private String _5Volume;

    public String get_1Open() {
        return _1Open;
    }

    public void set_1Open(final String _1Open) {
        this._1Open = _1Open;
    }

    public String get_2High() {
        return _2High;
    }

    public void set_2High(final String _2High) {
        this._2High = _2High;
    }

    public String get_3Low() {
        return _3Low;
    }

    public void set_3Low(final String _3Low) {
        this._3Low = _3Low;
    }

    public String get_4Close() {
        return _4Close;
    }

    public void set_4Close(final String _4Close) {
        this._4Close = _4Close;
    }

    public String get_5Volume() {
        return _5Volume;
    }

    public void set_5Volume(final String _5Volume) {
        this._5Volume = _5Volume;
    }
}
</code>```

}

the key point is if we give retrofit with Map<K,V> it will parse this into model automatically if the model is just like in JSON.

ContentLicense: CC BY-SA 3.0

Body:
I'm new in using Retrofit with Android. I'm stuck at a point where I make a request to the REST Api and the response has a dynamic keys. Can anyone tell me what is the best way to parse the JSON something like this.

{
  "Meta Data": {
    "1. Information": "Intraday (1min) prices and volumes",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2017-12-01 16:00:00",
    "4. Interval": "1min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (1min)": {
    "2017-12-01 16:00:00": {
      "1. open": "84.2000",
      "2. high": "84.2600",
      "3. low": "84.1800",
      "4. close": "84.2000",
      "5. volume": "3311341"
    },
    "2017-12-01 15:59:00": {
      "1. open": "84.2500",
      "2. high": "84.2600",
      "3. low": "84.2000",
      "4. close": "84.2000",
      "5. volume": "175169"
    },
    "2017-12-01 15:58:00": {
      "1. open": "84.2800",
      "2. high": "84.3000",
      "3. low": "84.2400",
      "4. close": "84.2550",
      "5. volume": "139520"
    }

  }
}

Body:
If you are using the Retrofit then you can directly parse this into some model let's say TestModel
based on your requirement call something like this.

@GET("your endpoint")
Call<TestModel> getTestData();

and here you will get data

public void getTestData(){
    mApiServiceNetwork.getNetworkService(null,WebConstants.API_ENDPOINT)
            .getTestData()
            .enqueue(new Callback<TestModel>() {
                @Override
                public void onResponse(final Call<TestModel> call, final Response<TestModel> response) {
                    if (response.code()==200){
                        //handle the response
                        TestModel testModel = response.body();
                    }else{
                        //handle the error
                    }
                }

                @Override
                public void onFailure(final Call<TestModel> call, final Throwable t) {

                }
            });
}

or

if you are getting data in JSON object then do like this.

 private TestModel getTestModel(JsonObject jsonObject){
        Gson gson = new Gson();
        TestModel  testModel = gson.fromJson(jsonObject,TestModel.class);
        return testModel;
    }

and if you are getting data in String then parse into Json object then call above method here is how you can convert string into json object.

JsonObject jsonParser = new JsonParser().parse(json).getAsJsonObject();

and most important your TestModel should be like this below for both the cases.

public class TestModel {
@SerializedName("Meta Data")
@Expose
private MetaModel mMetaModel;

public MetaModel getMetaModel() {
    return mMetaModel;
}

public void setMetaModel(final MetaModel metaModel) {
    mMetaModel = metaModel;
}

public Map<String, TimeModel> getTimeModel() {
    return mTimeModel;
}

public void setTimeModel(final Map<String, TimeModel> timeModel) {
    mTimeModel = timeModel;
}

@SerializedName("Time Series (1min)")

@Expose
private Map<String,TimeModel> mTimeModel;

public static class MetaModel{

    @SerializedName("1. Information")
    @Expose
    private String _1Information;
    @SerializedName("2. Symbol")
    @Expose
    private String _2Symbol;
    @SerializedName("3. Last Refreshed")
    @Expose
    private String _3LastRefreshed;
    @SerializedName("4. Interval")
    @Expose
    private String _4Interval;
    @SerializedName("5. Output Size")
    @Expose
    private String _5OutputSize;
    @SerializedName("6. Time Zone")
    @Expose
    private String _6TimeZone;

    public String get_1Information() {
        return _1Information;
    }

    public void set_1Information(final String _1Information) {
        this._1Information = _1Information;
    }

    public String get_2Symbol() {
        return _2Symbol;
    }

    public void set_2Symbol(final String _2Symbol) {
        this._2Symbol = _2Symbol;
    }

    public String get_3LastRefreshed() {
        return _3LastRefreshed;
    }

    public void set_3LastRefreshed(final String _3LastRefreshed) {
        this._3LastRefreshed = _3LastRefreshed;
    }

    public String get_4Interval() {
        return _4Interval;
    }

    public void set_4Interval(final String _4Interval) {
        this._4Interval = _4Interval;
    }

    public String get_5OutputSize() {
        return _5OutputSize;
    }

    public void set_5OutputSize(final String _5OutputSize) {
        this._5OutputSize = _5OutputSize;
    }

    public String get_6TimeZone() {
        return _6TimeZone;
    }

    public void set_6TimeZone(final String _6TimeZone) {
        this._6TimeZone = _6TimeZone;
    }
}
public static class TimeModel{
    @SerializedName("1. open")
    @Expose
    private String _1Open;
    @SerializedName("2. high")
    @Expose
    private String _2High;
    @SerializedName("3. low")
    @Expose
    private String _3Low;
    @SerializedName("4. close")
    @Expose
    private String _4Close;
    @SerializedName("5. volume")
    @Expose
    private String _5Volume;

    public String get_1Open() {
        return _1Open;
    }

    public void set_1Open(final String _1Open) {
        this._1Open = _1Open;
    }

    public String get_2High() {
        return _2High;
    }

    public void set_2High(final String _2High) {
        this._2High = _2High;
    }

    public String get_3Low() {
        return _3Low;
    }

    public void set_3Low(final String _3Low) {
        this._3Low = _3Low;
    }

    public String get_4Close() {
        return _4Close;
    }

    public void set_4Close(final String _4Close) {
        this._4Close = _4Close;
    }

    public String get_5Volume() {
        return _5Volume;
    }

    public void set_5Volume(final String _5Volume) {
        this._5Volume = _5Volume;
    }
}

}

the key point is if we give retrofit with Map<K,V> it will parse this into model automatically if the model is just like in JSON.


问:
POSTGRES : SELECT : Query for number of rows which EXIST BETWEEN given range
I have to query the table to search for given conditions :

order_no specified in the range must exist.

Example:  I am getting a request for a range of order_no: 003 - 007. So, I want to check whether all the order_no mentioned in range exist or not.If not exist return false.

The order_status of ALL order_no must be 1. If not exist return false.

Order_string    Order_no   Order_status
    ABE              1                1
    ABE              2                1
    ABE              3                0
    PSB              4                0
    PSB              5                1
    PSB              6                0
    REL              7                0
    REL              8                1
    REL              9                1
    REL              10               1

I was trying EXIST and BETWEEN but unable to query the DB.

答:
You should check these conditions:

```<code>count(order_no) = count(distinct order_no) -- order_no are distinct in the range
and count(*) = end_val- start_vat+ 1 -- number of rows equals to size of the range
and bool_and(order_status::bool) -- all order_status are 1
</code>```

The first condition is not necessary if the column is unique.

You can do this in the function:

```<code>create or replace function check_range(int, int)
returns boolean language sql as $$
    select
        count(order_no) = count(distinct order_no)
        and count(*) = $2- $1+ 1
        and bool_and(order_status::bool)
    from my_table
    where order_no between $1 and $2;
$$;
</code>```

Body:
You should check these conditions:

count(order_no) = count(distinct order_no) -- order_no are distinct in the range
and count(*) = end_val- start_vat+ 1 -- number of rows equals to size of the range
and bool_and(order_status::bool) -- all order_status are 1

The first condition is not necessary if the column is unique.

You can do this in the function:

create or replace function check_range(int, int)
returns boolean language sql as $$
    select
        count(order_no) = count(distinct order_no)
        and count(*) = $2- $1+ 1
        and bool_and(order_status::bool)
    from my_table
    where order_no between $1 and $2;
$$;


问:
Parenthesis surrounding return values in C
Quite often in ANSI C code I can see parenthesis sorrounding a single return value.

Like this:-

```<code>int foo(int x) {
  if (x)
    return (-1);
  else
    return (0);
}
</code>```

Why use () around the return value in those cases? Any ideas? I can see no reason for that.

答:
Using parentheses in a return statement shows a deficient grasp of C/C++ syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:

```<code>int foo(int x) {
  if (x) {
    return (-1);
  }
  else {
    return (0);
  }
}
</code>```

So many programmers do this. If one of you reads this, perhaps you might like to explain.

ContentLicense: CC BY-SA 4.0

Body:
Quite often in ANSI C code I can see parenthesis sorrounding a single return value.

Like this:-

int foo(int x) {
  if (x)
    return (-1);
  else
    return (0);
}

Why use () around the return value in those cases? Any ideas? I can see no reason for that.

LastEditorDisplayName: Prakash

Body:
Using parentheses in a return statement shows a deficient grasp of C/C++ syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:

int foo(int x) {
  if (x) {
    return (-1);
  }
  else {
    return (0);
  }
}

So many programmers do this. If one of you reads this, perhaps you might like to explain.

ContentLicense: CC BY-SA 2.5


问:
Open an Access database and run one of its Macros from Excel
From Excel, I need to open an Access database and run one of the database's macros.

I'm using Excel and Access 2007.  Here is my code in Excel:

```<code>Sub accessMacro()

   Dim appAccess As New Access.Application

   Set appAccess = Access.Application

   appAccess.OpenCurrentDatabase "C:\blah.mdb"

   appAccess.Visible = True

   appAccess.DoCmd.RunMacro "RunQueries.RunQueries"
   appAccess.CloseCurrentDatabase

End Sub
</code>```

In the Access database, there is a procedure named RunQueries in a module named RunQueries.

I get:

Runtime error '2485':

  Microsoft Access Office can't find the object 'RunQueries.'

I also tried

```<code>appAccess.DoCmd.RunMacro "RunQueries"
</code>```

and I get the same errors message.

I argued against it, and I have to do it this way (meaning, I have to use Excel as a frontend to open several Access dbs and run their macros).

答:
Try this:

Sub accessMacro()

   Dim appAccess

   Set appAccess = CreateObject("Access.Application")

   appAccess.OpenCurrentDatabase "C:\blah.mdb"

   appAccess.Visible = True

   appAccess.DoCmd.RunMacro "RunQueries.RunQueries"

   appAccess.CloseCurrentDatabase
End Sub
```

Body:
From Excel, I need to open an Access database and run one of the database's macros.

I'm using Excel and Access 2007.  Here is my code in Excel:

Sub accessMacro()

   Dim appAccess As New Access.Application

   Set appAccess = Access.Application

   appAccess.OpenCurrentDatabase "C:\blah.mdb"

   appAccess.Visible = True

   appAccess.DoCmd.RunMacro "RunQueries.RunQueries"
   appAccess.CloseCurrentDatabase

End Sub

In the Access database, there is a procedure named RunQueries in a module named RunQueries.

I get:

Runtime error '2485':

  Microsoft Access Office can't find the object 'RunQueries.'

I also tried

appAccess.DoCmd.RunMacro "RunQueries"

and I get the same errors message.

I argued against it, and I have to do it this way (meaning, I have to use Excel as a frontend to open several Access dbs and run their macros).


问:
PHP/Laravel Time Feld Required

I have a Laravel project that manages users and stuff like that. I'm storing data entered in a time form (time format), however, it keeps telling me that the time field is required even if I filled it.

Model part of the object

<?php

protected $fillable = ['name', 'timee'];

public $validationMessages;

public function validationRules()
{
    return [
        'name' => 'required|string',
        'timee' => 'required|time',
    ];
}
```

<p><strong>Time form in edit and create.blade.php</strong></p>

<pre class="lang-php prettyprint-override"><code><div class="form-group">
    {!! Form::label('timee', '* enter time :') !!}
    {!! Form::time('timee',null, ['class' => 'form-control']) !!}
    {{ $errors->first('timee') }}
</div>
</code>```

Migration

public function up()
{
    Schema::create('reminds', function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->time('timee');
    });
}
```

Each time I try to save it, it keeps telling me that the timee field is required even if I fill it. I don't get it, everything seems correct to me, thank you.

答:
use laravel date validation

```<code>'timee' => 'required|date_format:H:i'
</code>```

for more validation rules look at https://laravel.com/docs/5.5/validation#rule-date

Title: PHP/Laravel Time Feld Required

Body:
I have a Laravel project that manages users and stuff like that. I'm storing data entered in a time form (time format), however, it keeps telling me that the time field is required even if I filled it.

Model part of the object

<?php

protected $fillable = ['name', 'timee'];

public $validationMessages;

public function validationRules()
{
    return [
        'name' => 'required|string',
        'timee' => 'required|time',
    ];
}

Time form in edit and create.blade.php

    {!! Form::label('timee', '* enter time :') !!}
    {!! Form::time('timee',null, ['class' => 'form-control']) !!}
    {{ $errors->first('timee') }}

Migration

public function up()
{
    Schema::create('reminds', function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->time('timee');
    });
}

Each time I try to save it, it keeps telling me that the timee field is required even if I fill it. I don't get it, everything seems correct to me, thank you.

Body:
use laravel date validation

'timee' => 'required|date_format:H:i'

for more validation rules look at https://laravel.com/docs/5.5/validation#rule-date


问:
"fatal error" when calling tableView.reloadData(), the tableView is properly connected
I am trying to dynamically update a tableView while the program is running. I believe I have updated the array that the data loads from correctly, but when I press the button that calls self.eventTable.reloadData() I receive the error:

```<code>fatal error: unexpectedly found nil while unwrapping an Optional value
</code>```

Here is the relevant code:

View Controller:

```<code>import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

//Timer view
@IBOutlet weak var playButton: UIBarButtonItem!;
@IBOutlet weak var pauseButton: UIBarButtonItem!;
@IBOutlet weak var refreshButton: UIBarButtonItem!;
@IBOutlet weak var timerLabel: UILabel!

var counter = 0
var timer = Timer()
var isTimerRunning = false

//testing view container
var viewShowing = 1;

override func viewDidLoad() {

    // Do any additional setup after loading the view, typically from a nib.
    pauseButton.isEnabled = false

    hideAll();
    self.basicContainer.isUserInteractionEnabled = true;
    self.basicContainer.isHidden = false;

    self.timerLabel.text = String("00:00:00");

    eventTable.dataSource = self
    eventTable.delegate = self

    super.viewDidLoad()
    loadEvents(event: "timer start")
}
</code>```

...

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

// Add table to keep track of events
@IBOutlet weak var eventTable: UITableView!

var eventData = [Session]()

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return eventData.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
    let event = eventData[indexPath.row]
    cell.eventLabel.text = event.session
    return cell
}

private func loadEvents(event: String) {
    guard let event1 = Session(session: event) else {
        fatalError("Unable to instantiate event")
    }

    eventData += [event1]

    DispatchQueue.main.async() {
        self.eventTable.reloadData()
    }
}

func testPrint() {
    loadEvents(event: "testing cell adding")
    //self.eventTable.reloadData()
    viewWillAppear(false)
    print("This is a test print");
}

}
</code>```

The function works fine when it is called in ViewDidLoad(), but not when it is called by the button in another class ("This is a test print" prints to console so I know the button call is going through).

Expected behavior is the tableView (eventTable) reloading showing two cells, "timer start" and "testing cell adding" (ideally with "testing cell adding" being at the top).

Also want to emphasize that eventTable is connected to the storyboard, which seems to be a common problem on here.

Here is the Session.swift file and the eventTableViewCell.swift file if those are helpful:

Session.swift

```<code>import Foundation
import UIKit

class Session {

//MARK: Properties

var session: String

//MARK: Initialization

init?(session: String) {

    guard !session.isEmpty else {
        return nil
    }

    self.session = session
}

}
</code>```

eventTableViewCell.swift

```<code>import Foundation
import UIKit

class eventTableViewCell: UITableViewCell {
//MARK: Properties
@IBOutlet weak var eventLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}

}
</code>```

Thanks!

Edit: The ViewController from where I call testPrint().

```<code>import UIKit

class BasicViewController: UIViewController {

var VC = ViewController();

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

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

//Basic buttons
@IBOutlet weak var warmButton: UIButton!
@IBOutlet weak var dryButton: UIButton!
@IBOutlet weak var stimulateButton: UIButton!
@IBOutlet weak var controlButton: UIButton!
@IBOutlet weak var bedButton: UIButton!
@IBOutlet weak var tempButton: UIButton!
@IBOutlet weak var pulseButton: UIButton!
@IBOutlet weak var ecgButton: UIButton!
@IBOutlet weak var apgarButton: UIButton!
@IBOutlet weak var helpButton: UIButton!

//APGAR options
@IBOutlet weak var skinColor: UIButton!
@IBOutlet weak var pulse: UIButton!
@IBOutlet weak var grimace: UIButton!
@IBOutlet weak var flexion: UIButton!
@IBOutlet weak var respiratoryEffort: UIButton!

@IBAction func warmButton(sender: AnyObject) {
    VC.testPrint();
}
}
</code>```

It would seem that you are all right in stating that I am instantiating a new ViewController which is causing the issue. How should I go about fixing this? Fairly new to Swift

答:
I think, your problem is in this lines of codes:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
    let event = eventData[indexPath.row]
    cell.eventLabel.text = event.session
    return cell
}
</code>```

Can you check the cell identifier is same as your cell identifier

And number of rows in eventData array

Body:
I am trying to dynamically update a tableView while the program is running. I believe I have updated the array that the data loads from correctly, but when I press the button that calls self.eventTable.reloadData() I receive the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Here is the relevant code:

View Controller:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

//Timer view
@IBOutlet weak var playButton: UIBarButtonItem!;
@IBOutlet weak var pauseButton: UIBarButtonItem!;
@IBOutlet weak var refreshButton: UIBarButtonItem!;
@IBOutlet weak var timerLabel: UILabel!

var counter = 0
var timer = Timer()
var isTimerRunning = false

//testing view container
var viewShowing = 1;

override func viewDidLoad() {

    // Do any additional setup after loading the view, typically from a nib.
    pauseButton.isEnabled = false

    hideAll();
    self.basicContainer.isUserInteractionEnabled = true;
    self.basicContainer.isHidden = false;

    self.timerLabel.text = String("00:00:00");

    eventTable.dataSource = self
    eventTable.delegate = self

    super.viewDidLoad()
    loadEvents(event: "timer start")
}

...

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

// Add table to keep track of events
@IBOutlet weak var eventTable: UITableView!

var eventData = [Session]()

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return eventData.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
    let event = eventData[indexPath.row]
    cell.eventLabel.text = event.session
    return cell
}

private func loadEvents(event: String) {
    guard let event1 = Session(session: event) else {
        fatalError("Unable to instantiate event")
    }

    eventData += [event1]

    DispatchQueue.main.async() {
        self.eventTable.reloadData()
    }
}

func testPrint() {
    loadEvents(event: "testing cell adding")
    //self.eventTable.reloadData()
    viewWillAppear(false)
    print("This is a test print");
}

}

The function works fine when it is called in ViewDidLoad(), but not when it is called by the button in another class ("This is a test print" prints to console so I know the button call is going through).

Expected behavior is the tableView (eventTable) reloading showing two cells, "timer start" and "testing cell adding" (ideally with "testing cell adding" being at the top).

Also want to emphasize that eventTable is connected to the storyboard, which seems to be a common problem on here.

Here is the Session.swift file and the eventTableViewCell.swift file if those are helpful:

Session.swift

import Foundation
import UIKit

class Session {

//MARK: Properties

var session: String

//MARK: Initialization

init?(session: String) {

    guard !session.isEmpty else {
        return nil
    }

    self.session = session
}

}

eventTableViewCell.swift

import Foundation
import UIKit

class eventTableViewCell: UITableViewCell {
//MARK: Properties
@IBOutlet weak var eventLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}

}

Thanks!

Edit: The ViewController from where I call testPrint().

import UIKit

class BasicViewController: UIViewController {

var VC = ViewController();

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

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

//Basic buttons
@IBOutlet weak var warmButton: UIButton!
@IBOutlet weak var dryButton: UIButton!
@IBOutlet weak var stimulateButton: UIButton!
@IBOutlet weak var controlButton: UIButton!
@IBOutlet weak var bedButton: UIButton!
@IBOutlet weak var tempButton: UIButton!
@IBOutlet weak var pulseButton: UIButton!
@IBOutlet weak var ecgButton: UIButton!
@IBOutlet weak var apgarButton: UIButton!
@IBOutlet weak var helpButton: UIButton!

//APGAR options
@IBOutlet weak var skinColor: UIButton!
@IBOutlet weak var pulse: UIButton!
@IBOutlet weak var grimace: UIButton!
@IBOutlet weak var flexion: UIButton!
@IBOutlet weak var respiratoryEffort: UIButton!

@IBAction func warmButton(sender: AnyObject) {
    VC.testPrint();
}
}

It would seem that you are all right in stating that I am instantiating a new ViewController which is causing the issue. How should I go about fixing this? Fairly new to Swift

Body:
I think, your problem is in this lines of codes:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as! eventTableViewCell
    let event = eventData[indexPath.row]
    cell.eventLabel.text = event.session
    return cell
}

Can you check the cell identifier is same as your cell identifier

And number of rows in eventData array


问:
Ionic 3 Google Map does not display on Android + IOS
I use Ionic 3 version and I try to add a page into my app, to display a map with markers.
I already use for my app a Google Map Id for Autocomplete (Google places...).
I went to Google APIs and I added Map Embed, Javascript etc... to my API Key.
But The page appears with "Google" in the bottom and the display button", but the map is empty.
See attached file...

Install the Cordova and Ionic Native plugins:

$ ionic cordova plugin add https://github.com/mapsplugin/cordova-plugin-googlemaps#multiple_maps --variable API_KEY_FOR_ANDROID="AIzaSyB6mEnxH4vC+++++++++9wnXXNNmK2co" --variable API_KEY_FOR_IOS="AIzaSyB6mEnxH4v++++++++++++++wnXXNNmK2co"
$ npm install --save @ionic-native/google-maps

Home.ts:

```<code>import { NavController } from 'ionic-angular';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { GoogleMaps, CameraPosition, GoogleMapsEvent, GoogleMap, MarkerOptions, Marker } from "@ionic-native/google-maps";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  constructor(public navCtrl: NavController, private googleMaps: GoogleMaps) {

  }
  ngAfterViewInit() {
 this.loadMap();
}

loadMap() {
 // make sure to create following structure in your view.html file
 // and add a height (for example 100%) to it, else the map won't be visible
 // <ion-content>
 //  <div #map id="map" style="height:100%;"></div>
 // </ion-content>

 // create a new map by passing HTMLElement
 let element: HTMLElement = document.getElementById('map');

 let map: GoogleMap = this.googleMaps.create(element);

 // listen to MAP_READY event
 // You must wait for this event to fire before adding something to the map or modifying it in anyway
 map.one(GoogleMapsEvent.MAP_READY).then(
   () => {
     console.log('Map is ready!');
     // Now you can add elements to the map like the marker
   }
 );

 // create CameraPosition
 let position: CameraPosition = {
   target: {
     lat: 43.0741904,
     lng: -89.3809802
   },
   zoom: 18,
   tilt: 30
 };

 // move the map's camera to position
}
}
</code>```

Home.HTML

Home.html :
<ion-header>
  <ion-navbar>
    <ion-title>
      Map
    </ion-title>
    <ion-buttons end>
      <button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>

</ion-content>```
</div>
</div>
</p>

<p>Home.scss</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>page-home {

}</code>```

答:
Please try below code and make sure you are using correct API key, write following code in your .ts file:

```<code>  ionViewDidLoad() {
    this.loadMap();
   }
   loadMap() {

        let mapOptions: GoogleMapOptions = {
          camera: {
            target: {
              lat: 43.0741904,
              lng: -89.3809802
            },
            zoom: 18,
            tilt: 30
          }
        };

        this.map = this.googleMaps.create('map_canvas', mapOptions);

        // Wait the MAP_READY before using any methods.
        this.map.one(GoogleMapsEvent.MAP_READY)
          .then(() => {
            console.log('Map is ready!');

            this.map.addMarker({
                title: 'Ionic',
                icon: 'blue',
                animation: 'DROP',
                position: {
                  lat: 43.0741904,
                  lng: -89.3809802
                }
              })
              .then(marker => {
                marker.on(GoogleMapsEvent.MARKER_CLICK)
                  .subscribe(() => {
                    alert('clicked');
                  });
              });

          });
      }
</code>```

In your .html file define map like below

```<code><ion-content>
  <div id="map_canvas" style="height: 100%;"></div>
</ion-content>
</code>```

Body:
I use Ionic 3 version and I try to add a page into my app, to display a map with markers.
I already use for my app a Google Map Id for Autocomplete (Google places...).
I went to Google APIs and I added Map Embed, Javascript etc... to my API Key.
But The page appears with "Google" in the bottom and the display button", but the map is empty.
See attached file...

Install the Cordova and Ionic Native plugins:

$ ionic cordova plugin add https://github.com/mapsplugin/cordova-plugin-googlemaps#multiple_maps --variable API_KEY_FOR_ANDROID="AIzaSyB6mEnxH4vC+++++++++9wnXXNNmK2co" --variable API_KEY_FOR_IOS="AIzaSyB6mEnxH4v++++++++++++++wnXXNNmK2co"
$ npm install --save @ionic-native/google-maps

Home.ts:

import { NavController } from 'ionic-angular';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { GoogleMaps, CameraPosition, GoogleMapsEvent, GoogleMap, MarkerOptions, Marker } from "@ionic-native/google-maps";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;
  constructor(public navCtrl: NavController, private googleMaps: GoogleMaps) {

  }
  ngAfterViewInit() {
 this.loadMap();
}

loadMap() {
 // make sure to create following structure in your view.html file
 // and add a height (for example 100%) to it, else the map won't be visible
 // <ion-content>
 //

 // </ion-content>

 // create a new map by passing HTMLElement
 let element: HTMLElement = document.getElementById('map');

 let map: GoogleMap = this.googleMaps.create(element);

 // listen to MAP_READY event
 // You must wait for this event to fire before adding something to the map or modifying it in anyway
 map.one(GoogleMapsEvent.MAP_READY).then(
   () => {
     console.log('Map is ready!');
     // Now you can add elements to the map like the marker
   }
 );

 // create CameraPosition
 let position: CameraPosition = {
   target: {
     lat: 43.0741904,
     lng: -89.3809802
   },
   zoom: 18,
   tilt: 30
 };

 // move the map's camera to position
}
}

Home.HTML

Home.html :
<ion-header>
  <ion-navbar>
    <ion-title>
      Map
    </ion-title>
    <ion-buttons end>
      <button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>

</ion-content>

Home.scss

page-home {

}

Body:
Please try below code and make sure you are using correct API key, write following code in your .ts file:

  ionViewDidLoad() {
    this.loadMap();
   }
   loadMap() {

        let mapOptions: GoogleMapOptions = {
          camera: {
            target: {
              lat: 43.0741904,
              lng: -89.3809802
            },
            zoom: 18,
            tilt: 30
          }
        };

        this.map = this.googleMaps.create('map_canvas', mapOptions);

        // Wait the MAP_READY before using any methods.
        this.map.one(GoogleMapsEvent.MAP_READY)
          .then(() => {
            console.log('Map is ready!');

            this.map.addMarker({
                title: 'Ionic',
                icon: 'blue',
                animation: 'DROP',
                position: {
                  lat: 43.0741904,
                  lng: -89.3809802
                }
              })
              .then(marker => {
                marker.on(GoogleMapsEvent.MARKER_CLICK)
                  .subscribe(() => {
                    alert('clicked');
                  });
              });

          });
      }

In your .html file define map like below

<ion-content>
  <div id="map_canvas" style="height: 100%;"></div>
</ion-content>


问:
Storing game states and scores in keychain
I am trying to store some strings (scores, lastPlayedLevel, etc) of my game in keychain. Because it is said to be the most safe method.
Since I am new to Keychain concept I have problems in understanding probably "very simple" things.

I use SAMKeychain wrapper and I want to set lastPlayedLevel string as below

```<code>[SAMKeychain setPassword:@"25" forService:[[NSBundle mainBundle] bundleIdentifier] account:@"lastPlayedLevel"];
</code>```

Is it a correct approach? I am not sure about the "account" part. I want "lastPlayedLevel" be synced across all devices of the user. Do I have to write a user specific string instead?

答: Putting score and game state in keychain is overkill IMHO. What you need to do is just store them in the NSUserDefaults, but encode your data into binary before storing it so anybody opening your NSUSerDefaults file wont be able to view/edit it straight away. If you want more secrecy, then encode the value first (for example char xor or other) before encoding to binary.</p>

Body:
I am trying to store some strings (scores, lastPlayedLevel, etc) of my game in keychain. Because it is said to be the most safe method.
Since I am new to Keychain concept I have problems in understanding probably "very simple" things.

I use SAMKeychain wrapper and I want to set lastPlayedLevel string as below

[SAMKeychain setPassword:@"25" forService:[[NSBundle mainBundle] bundleIdentifier] account:@"lastPlayedLevel"];

Is it a correct approach? I am not sure about the "account" part. I want "lastPlayedLevel" be synced across all devices of the user. Do I have to write a user specific string instead?


问:
How to dynamically hide some options from a drop-down list using jQuery

I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">
            <div id="state1">
               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>
            </div>
            <div id="state2">
               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>
            </div>
        </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

答:
Problems in your code

selected_state is a variable

cant place div inside select options

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); // get the selected state
    $("#city").children().hide(); // hide all the options
    $("." + selected_state).show(); // only show cities in selected state
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State:
  <select name="state" id="state">
      <option value="state1">State1</option>
      <option value="state2">State2</option>
  </select> City:

   <select name="city" id="city">
    <option class="state0" value="-1">-select city-</option>
         <option class="state1" value="0">City1a</option>
         <option class="state1" value="1">City1b</option>
         <option class="state1" value="2">City1c</option>

         <option class="state2" value="3">City2a</option>
         <option class="state2" value="4">City2b</option>
         <option class="state2" value="5">City2c</option>
  </select>

  <input name="submit" type="submit" value="Submit" />
</form></code>```

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
Problems in your code

selected_state is a variable

cant place div inside select options

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); // get the selected state
    $("#city").children().hide(); // hide all the options
    $("." + selected_state).show(); // only show cities in selected state
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State:
  <select name="state" id="state">
      <option value="state1">State1</option>
      <option value="state2">State2</option>
  </select> City:

   <select name="city" id="city">
    <option class="state0" value="-1">-select city-</option>
         <option class="state1" value="0">City1a</option>
         <option class="state1" value="1">City1b</option>
         <option class="state1" value="2">City1c</option>

         <option class="state2" value="3">City2a</option>
         <option class="state2" value="4">City2b</option>
         <option class="state2" value="5">City2c</option>
  </select>

  <input name="submit" type="submit" value="Submit" />
</form>


问:
How can I pass an object as an url variable in flask?
I am new to python and Flask. I am currently working on a project where I need to render different pages for different actions but they both need to have access to the one same object.

for example:

```<code>@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    render_template("/results/'+objs+'")

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)
</code>```

I am able to pass string, integer even path as a parameter. I couldn't find any references to see if passing an object is doable or not. Appreciate your responses!

Thanks,
Deepak

答:
it looks like what you need is to use flask url_for

```<code>@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    return redirect(url_for('app.functionB', objs=objs))

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)
    return "something {}".format(objs)
</code>```

not also that you views functions should always return a response

it's one of the solutions to your problem, hope it will help

Body:
I am new to python and Flask. I am currently working on a project where I need to render different pages for different actions but they both need to have access to the one same object.

for example:

@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    render_template("/results/'+objs+'")

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)

I am able to pass string, integer even path as a parameter. I couldn't find any references to see if passing an object is doable or not. Appreciate your responses!

Thanks,
Deepak

Body:
it looks like what you need is to use flask url_for

@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    return redirect(url_for('app.functionB', objs=objs))

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)
    return "something {}".format(objs)

not also that you views functions should always return a response

it's one of the solutions to your problem, hope it will help


问:
How to set background image in UIButton of Xamarin.IOS application?

I have tried the code below but text image gets overlapped.

```<code>btnBack.SetImage(UIImage.FromFile("Images/arrow-back.png"), UIControlState.Normal);
btnBack.TintColor = UIColor.White;
</code>```

答:
This is a normal issue when setting text and image simultaneously on Button.

You can use TitleEdgeInsets and ImageEdgeInsets to get rid of it.

For example:

```<code>button.ImageEdgeInsets = new UIEdgeInsets(0, -10, 0, 0);
button.TitleEdgeInsets = new UIEdgeInsets(0, 0, 0, -10);
</code>```

Moreover, you can also create a UIView which contains image and text, in this way it is more controllable.

Body:
I have tried the code below but text image gets overlapped.

btnBack.SetImage(UIImage.FromFile("Images/arrow-back.png"), UIControlState.Normal);
btnBack.TintColor = UIColor.White;

Body:
This is a normal issue when setting text and image simultaneously on Button.

You can use TitleEdgeInsets and ImageEdgeInsets to get rid of it.

For example:

button.ImageEdgeInsets = new UIEdgeInsets(0, -10, 0, 0);
button.TitleEdgeInsets = new UIEdgeInsets(0, 0, 0, -10);

Moreover, you can also create a UIView which contains image and text, in this way it is more controllable.


问:
Gitlab ce in docker container issue with port
I recently installed gitlab community edition with docker-compose on my ubuntu server (16.04), which runs an nginx web server.

Sometimes the port is displayed in the url which make it load until ERR_TIMED_OUT happens.

It is always the same urls :

- new merge request

- new milestones

- link to website in email sent

(and maybe a few other that I don't have at the top of my head right now)

For example, when I try to create a merge request, I have this url :
http://exemple.com:9090/group/project/merge_requests/new

instead of

http://exemple.com/group/project/merge_requests/new

Here is my docker-compose.yml

```<code>web:
  image: 'gitlab/gitlab-ce:latest'
  restart: always
  hostname: 'exemple.com'
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url 'http://exemple.com:9090'
      gitlab_rails['smtp_enable'] = true
      gitlab_rails['smtp_address'] = "smtp.gmail.com"
      gitlab_rails['smtp_port'] = 587
      gitlab_rails['smtp_user_name'] = "account@gmail.com"
      gitlab_rails['smtp_password'] = "password"
      gitlab_rails['smtp_domain'] = "smtp.gmail.com"
      gitlab_rails['smtp_authentication'] = "login"
      gitlab_rails['smtp_enable_starttls_auto'] = true
      gitlab_rails['smtp_tls'] = false
      gitlab_rails['smtp_openssl_verify_mode'] = 'peer'
      gitlab_rails['gitlab_shell_ssh_port'] = 2224
  ports:
    - '9090:9090'
    - '2224:22'
  volumes:
    - '/srv/gitlab/config:/etc/gitlab'
    - '/srv/gitlab/logs:/var/log/gitlab'
    - '/srv/gitlab/data:/var/opt/gitlab'
</code>```

The nginx server block :

```<code>server {
    listen 80;
    listen [::]80;

    server_name exemple.com www.exemple.com;

    location / {
        proxy_pass http://127.0.0.1:9090;
    }
}
</code>```

note : nginx is not in a docker container

答:
If you want to preserve the data, don't follow the below. Instead create a new container.
1- Make sure you remove the current container

```<code>docker-compose stop && docker-compose rm
</code>```

2- In you docker-compose.yml file, external_url should looks like this:

```<code>external_url 'http://example.com'
</code>```

3- Remove any local Gitlab configuration files previously created

```<code>sudo rm -rf /srv/gitlab/*
</code>```

4- Recreate and start the container

```<code>docker-compose up -d
</code>```

Body:
I recently installed gitlab community edition with docker-compose on my ubuntu server (16.04), which runs an nginx web server.

Sometimes the port is displayed in the url which make it load until ERR_TIMED_OUT happens.

It is always the same urls :

- new merge request

- new milestones

- link to website in email sent

(and maybe a few other that I don't have at the top of my head right now)

For example, when I try to create a merge request, I have this url :
http://exemple.com:9090/group/project/merge_requests/new

instead of

http://exemple.com/group/project/merge_requests/new

Here is my docker-compose.yml

web:
  image: 'gitlab/gitlab-ce:latest'
  restart: always
  hostname: 'exemple.com'
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url 'http://exemple.com:9090'
      gitlab_rails['smtp_enable'] = true
      gitlab_rails['smtp_address'] = "smtp.gmail.com"
      gitlab_rails['smtp_port'] = 587
      gitlab_rails['smtp_user_name'] = "account@gmail.com"
      gitlab_rails['smtp_password'] = "password"
      gitlab_rails['smtp_domain'] = "smtp.gmail.com"
      gitlab_rails['smtp_authentication'] = "login"
      gitlab_rails['smtp_enable_starttls_auto'] = true
      gitlab_rails['smtp_tls'] = false
      gitlab_rails['smtp_openssl_verify_mode'] = 'peer'
      gitlab_rails['gitlab_shell_ssh_port'] = 2224
  ports:
    - '9090:9090'
    - '2224:22'
  volumes:
    - '/srv/gitlab/config:/etc/gitlab'
    - '/srv/gitlab/logs:/var/log/gitlab'
    - '/srv/gitlab/data:/var/opt/gitlab'

The nginx server block :

server {
    listen 80;
    listen [::]80;

    server_name exemple.com www.exemple.com;

    location / {
        proxy_pass http://127.0.0.1:9090;
    }
}

note : nginx is not in a docker container

Body:
If you want to preserve the data, don't follow the below. Instead create a new container.
1- Make sure you remove the current container

docker-compose stop && docker-compose rm

2- In you docker-compose.yml file, external_url should looks like this:

external_url 'http://example.com'

3- Remove any local Gitlab configuration files previously created

sudo rm -rf /srv/gitlab/*

4- Recreate and start the container

docker-compose up -d


问:
Entity framework Modify multiple records with common data
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

```<code>var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}
</code>```

is there any good way to do this.

Appreciate your help.

答:
This is going to be Update the Records not to Delete Totally

Assuming that you have already created a Model name ISVCSPModel

```<code>ISVCSPModel ISVCSPmodel= db.ISVCSP.Find(beneficiaryId)
db.Entry(ISVCSPmodel).State = EntityState.Modified;
ISVCSPmodel.IsDeleted = true;
db.SaveChangesAsync();
</code>```

Body:
I have an "Apps" Table which consists of multiple apps data
Now I wanted to delete (soft delete means making isDelete = true)

I'm deleting records by the following code.

var deletingISVCSPRecord = await db.ISVCSP.Where(s => s.BeneficiaryId == beneficiaryId).ToListAsync();
foreach (var item in deletingISVCSPRecord)
{
    item.IsDeleted = true;
    await db.SaveChangesAsync();
}

is there any good way to do this.

Appreciate your help.

Body:
This is going to be Update the Records not to Delete Totally

Assuming that you have already created a Model name ISVCSPModel

ISVCSPModel ISVCSPmodel= db.ISVCSP.Find(beneficiaryId)
db.Entry(ISVCSPmodel).State = EntityState.Modified;
ISVCSPmodel.IsDeleted = true;
db.SaveChangesAsync();


答:
Don't use the div inside select.

The way you used the selected_state is not how to use it.

You should be able to make out a relation with both the drop down.

Something like this is what you have to do.

```<code><form method="post">
State: <select name="state" id="state">
    <option value="">Select</option>
    <option value="state1">State1</option>
    <option value="state2">State2</option>
</select>
City:
<select name="city" id="city">

</select>
<input name="submit" type="submit" value="Submit" />
</code>```

```<code>    $(document).ready(function($) {
    $("#state").change(function() {
        var selected_state =$("#state option:selected").val(); //get the selected state
        GetAllCityByState(selected_state);
    });

        function GetAllCityByState(stateid) {
        $("#city").html('');
        $("#city").empty();
        if(stateid == "state1")
        {
          $("#city").append($("<option></option>").val(0).html("City1a"));
          $("#city").append($("<option></option>").val(1).html("City1b"));
          $("#city").append($("<option></option>").val(2).html("City1c"));
        }
        else if(stateid == "state2")
        {
          $("#city").append($("<option></option>").val(3).html("City2a"));
          $("#city").append($("<option></option>").val(4).html("City2b"));
          $("#city").append($("<option></option>").val(5).html("City2c"));
        }
        $("#city").select().val();
    }
});
</code>```

Please find the fiddle here

Title: How to dynamically hide some options from a drop-down list using jQuery

Body:
Don't use the div inside select.

The way you used the selected_state is not how to use it.

You should be able to make out a relation with both the drop down.

Something like this is what you have to do.

<form method="post">
State: <select name="state" id="state">
    <option value="">Select</option>
    <option value="state1">State1</option>
    <option value="state2">State2</option>
</select>
City:
<select name="city" id="city">

</select>
<input name="submit" type="submit" value="Submit" />

    $(document).ready(function($) {
    $("#state").change(function() {
        var selected_state =$("#state option:selected").val(); //get the selected state
        GetAllCityByState(selected_state);
    });

        function GetAllCityByState(stateid) {
        $("#city").html('');
        $("#city").empty();
        if(stateid == "state1")
        {
          $("#city").append($("<option></option>").val(0).html("City1a"));
          $("#city").append($("<option></option>").val(1).html("City1b"));
          $("#city").append($("<option></option>").val(2).html("City1c"));
        }
        else if(stateid == "state2")
        {
          $("#city").append($("<option></option>").val(3).html("City2a"));
          $("#city").append($("<option></option>").val(4).html("City2b"));
          $("#city").append($("<option></option>").val(5).html("City2c"));
        }
        $("#city").select().val();
    }
});

Please find the fiddle here


问:
R: factor as new level when I predict with test data
I am getting an error from my datasets similar logic with the code I posted in below. I have tried increased the number of training data but didn't solve. I have already excluded all NA values.

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
    factor y has new levels L, X

```<code>set.seed(234)
d <- data.frame(w=abs(rnorm(50)*1000),
            x=rnorm(50),
            y=sample(LETTERS[1:26], 50, replace=TRUE))

train_idx <- sample(1:nrow(d), floor(0.8*nrow(d)))
train <- d[train_idx,]
test  <- d[-train_idx,]

fit  <- lm(w ~x + y, data=train)
predict(fit, test)
</code>```

答:
As @jdobres has already explained the reason of why this error popped up I'll straightforwardly jump to the solution approach:

Let's try below line of code just before predict statement

```<code>#add all levels of 'y' in 'test' dataset to fit$xlevels[["y"]] in the fit object
fit$xlevels[["y"]] <- union(fit$xlevels[["y"]], levels(test[["y"]]))
</code>```

Hope this would resolve your problem!

Body:
I am getting an error from my datasets similar logic with the code I posted in below. I have tried increased the number of training data but didn't solve. I have already excluded all NA values.

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
    factor y has new levels L, X

set.seed(234)
d <- data.frame(w=abs(rnorm(50)*1000),
            x=rnorm(50),
            y=sample(LETTERS[1:26], 50, replace=TRUE))

train_idx <- sample(1:nrow(d), floor(0.8*nrow(d)))
train <- d[train_idx,]
test  <- d[-train_idx,]

fit  <- lm(w ~x + y, data=train)
predict(fit, test)

Body:
As @jdobres has already explained the reason of why this error popped up I'll straightforwardly jump to the solution approach:

Let's try below line of code just before predict statement

#add all levels of 'y' in 'test' dataset to fit$xlevels[["y"]] in the fit object
fit$xlevels[["y"]] <- union(fit$xlevels[["y"]], levels(test[["y"]]))

Hope this would resolve your problem!


问:
Temp TableSpace Usage
we have a Job in our system which is processing data in bulk, so some user complain Application is slow while job is running, from AWR report we observed Temp table space waits even Temp tables pace is 32GB with auto extend on, is there any way to check what was the temp table space usage at JOB execution time. mean can we check history usage of table space. thanks in advance</p>

答:
```<code>--#1: Find the maximum temporary tablespace used during a snapshot.
select begin_time, end_time, instance_number, round(maxval/1024/1024) temp_mb
from dba_hist_sysmetric_summary
where metric_name = 'Temp Space Used'
order by 1,2,3;

--#2: Find SQL statements running around the same time.
--Look for the event it was waiting on.  Was it waiting on something like
--"resumable session", implying that no temporary tablespace was available?  Or was it
--waiting on reading and writing temporary tablespace because of large data or a bad plan?
select sql_id, event, round(temp_space_allocated)/1024/1024 temp_mb, sql_plan_line_id,
    dba_hist_active_sess_history.*
from dba_hist_active_sess_history
where sample_time between timestamp '2017-12-03 12:00:00' and timestamp '2017-12-03 13:00:00'
order by sample_time desc;

--#3: Find the slow operation in the SQL Monitor Report.  (If you're using AWR you probably
--have also licensed the diagnostics pack, and can use this tool.)  Find the operation that
--used too much temporary tablespace and try to figure out why.  Are the objects simply
--too large for the temporary tablespace?  Is there a cross join creating a huge
--intermediate result set?  Is the execution plan bad and Oracle is sorting/hashing
--result sets poorly?
select dbms_sqltune.report_sql_monitor(sql_id => '[enter SQL_ID from above]') from dual;
</code>```

Title: Temp TableSpace Usage


问:
spacing between UITableViewCells swift3
I am creating a IOS app in swift and want to add spacing between cells like this

I would like to give space of each table view cell same like my attach image.
How I can do that? and Right now all cells are coming without any space.
swift3

答:
One simple way is collection view instead of table view and give cell spacing to collection view and use

```<code>func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
    let widthSize = collectionView.frame.size.width / 1
    return CGSize(width: widthSize-2, height: widthSize+20)
}
</code>```

And if you want tableview only then add background view as container view and set background color white and cell background color clear color set backround view of cell leading, trilling, bottom to 10

```<code>backgroundView.layer.cornerRadius = 2.0
backgroundView.layer.masksToBounds = false
backgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
</code>```

Title: spacing between UITableViewCells swift3

Body:
One simple way is collection view instead of table view and give cell spacing to collection view and use

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
    let widthSize = collectionView.frame.size.width / 1
    return CGSize(width: widthSize-2, height: widthSize+20)
}

And if you want tableview only then add background view as container view and set background color white and cell background color clear color set backround view of cell leading, trilling, bottom to 10

backgroundView.layer.cornerRadius = 2.0
backgroundView.layer.masksToBounds = false
backgroundView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor


问:
Dragging cell to bottom or top will stop and reordering `collectionView` will not reorder
I add a longPress Gesture to collectionView, and use system API to implement reordering collectionview. here is my code:

```<code>CGPoint point = [sender locationInView:_collectionView];
NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:point];
if (!indexPath) {
    return;
}
DragableCollectionViewCell *tempCell = (DragableCollectionViewCell *)[_collectionView cellForItemAtIndexPath:indexPath];

switch (sender.state) {
    case UIGestureRecognizerStateBegan: {

        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

        [tempCell showDeletButton];
        [tempCell.deleteButton zkj_addEventHandler:^(id sender) {
            [tempCell hideDeleteButton];
            [self.dataSource[indexPath.section] removeObjectAtIndex:indexPath.item];
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        } withControlEvents:UIControlEventTouchUpInside];

        [_collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
    }
        break;
    case UIGestureRecognizerStateChanged: {
        [_collectionView updateInteractiveMovementTargetPosition:point];
    }
        break;
    case UIGestureRecognizerStateEnded: {
        [_collectionView endInteractiveMovement];
    }
        break;

    default:
        [_collectionView cancelInteractiveMovement];
        break;
}
</code>```

and I had implement dataSource and delegate of collectionView correctly. After that, it works, I can move drag cell and reorder collectionView. But when I drag cell to bottom or top, the cell will stop at bottom or top, and collectionView will not reorder automatically.

答:
In iOS-11,

You can use Drag and Drop API for reordering in UICollectionView.
It is much more flexible and easy to implement than your custom implementation.

Refer to the below link for a nice tutorial on how to implement that:
 https://medium.com/@p.gpt10/drag-it-drop-it-in-collection-table-ios-11-6bd28795b313

Body:
I add a longPress Gesture to collectionView, and use system API to implement reordering collectionview. here is my code:

CGPoint point = [sender locationInView:_collectionView];
NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:point];
if (!indexPath) {
    return;
}
DragableCollectionViewCell *tempCell = (DragableCollectionViewCell *)[_collectionView cellForItemAtIndexPath:indexPath];

switch (sender.state) {
    case UIGestureRecognizerStateBegan: {

        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

        [tempCell showDeletButton];
        [tempCell.deleteButton zkj_addEventHandler:^(id sender) {
            [tempCell hideDeleteButton];
            [self.dataSource[indexPath.section] removeObjectAtIndex:indexPath.item];
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        } withControlEvents:UIControlEventTouchUpInside];

        [_collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
    }
        break;
    case UIGestureRecognizerStateChanged: {
        [_collectionView updateInteractiveMovementTargetPosition:point];
    }
        break;
    case UIGestureRecognizerStateEnded: {
        [_collectionView endInteractiveMovement];
    }
        break;

    default:
        [_collectionView cancelInteractiveMovement];
        break;
}

and I had implement dataSource and delegate of collectionView correctly. After that, it works, I can move drag cell and reorder collectionView. But when I drag cell to bottom or top, the cell will stop at bottom or top, and collectionView will not reorder automatically.


问:
Highest appearance of a value within each group
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

```<code>| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |
</code>```

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

答:
I am not sure I get your question right. If you would like to get the website-ID with the most visits, you can use this:</p>

```<code>select count(user-ID) as cnt from dataTable group by website-ID order by cnt desc
</code>```

Body:
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

Body:
I am not sure I get your question right. If you would like to get the website-ID with the most visits, you can use this:

select count(user-ID) as cnt from dataTable group by website-ID order by cnt desc


答:
Don't use div inside select . You can try this way.

$(document).ready(function($) {
  var c1 = '<option value="0">City1a</option><optionvalue="1">City1b</option><option value="2">City1c</option>'
  var c2 = ' <option value="3">City2a</option> <option value="4">City2b</option><option value="5">City2c</option>'
  $("#city").html(c1);
  $("#state").change(function() {
$("#city").html('');

var selected_state = $("#state").val(); //get the selected state
if (selected_state == 'state1')
  $("#city").html(c1);
else
  $("#city").html(c2);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

  </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
Don't use div inside select . You can try this way.

$(document).ready(function($) {
  var c1 = '<option value="0">City1a</option><optionvalue="1">City1b</option><option value="2">City1c</option>'
  var c2 = ' <option value="3">City2a</option> <option value="4">City2b</option><option value="5">City2c</option>'
  $("#city").html(c1);
  $("#state").change(function() {
$("#city").html('');

var selected_state = $("#state").val(); //get the selected state
if (selected_state == 'state1')
  $("#city").html(c1);
else
  $("#city").html(c2);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

  </select>
  <input name="submit" type="submit" value="Submit" />
</form>


问:
How do I fix " 'tuple' object does not support item assignment " in my code?
```<code>import math
def ListSqrRoot(nums):
    n=len(nums)
    for i in range(n):
        nums[i]=math.sqrt(nums[i])

def main():
    nums=eval(input("Please enter a list of numbers:"))
    print( "Before calling the function your list is:")
    print (nums)
    ListSqrRoot(nums)
    print ("After calling the function your list is:")
    print (nums)

main()
</code>```

答:
The core problem is that the expression you enter into eval, such as "1, 2, 3" are tuples, which are immutable, i.e., unable to be changed.

Additionally, using eval like this is dangerous, and can lead to some confusing errors. (What happens if you put in an empty list?) Python has plenty of nice string manipulation functions, so it is also completely unnecessary. Try,

```<code>line = input('enter numbers:')
nums = [int(s.strip()) for s in line.strip().split(',') if s]
</code>```

Body:
The core problem is that the expression you enter into eval, such as "1, 2, 3" are tuples, which are immutable, i.e., unable to be changed.

Additionally, using eval like this is dangerous, and can lead to some confusing errors. (What happens if you put in an empty list?) Python has plenty of nice string manipulation functions, so it is also completely unnecessary. Try,

line = input('enter numbers:')
nums = [int(s.strip()) for s in line.strip().split(',') if s]


问:
Is there a way to use value from CUST_DDA port as input port for lookup?
I'm trying to use a Lookup transformation to extract ACCT_ID from ACCT table based on the port CUST_DDA which is an output port from an expression.
I'm using an sqloverride as below. The initial lookup condition :

```<code>SUBSTR_ACCT_ID = IN_CUST_DDA
</code>```

Override:

```<code>SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(IN_CUST_DDA))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
</code>```

The above sql override is failing due to the error : ORA-00904: "IN_CUST_DDA": invalid identifier

Is there a way to use the value from CUST_DDA port as an input port for the lookup. CUST_DDA is not a field that belongs to the ACCT table. Is there a way to do this.

Thanks.

答:
To achieve this you need to configure your lookup as non-cached, so the query will be executed for each input row. Note, that this degrades performance a lot.
Next, you need to use a bit different syntax, enclosing the input port in question marks. Here's an example. In your case it should be something like (this might need a little adjustment):</p>

```<code>SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(?IN_CUST_DDA?))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(?IN_CUST_DDA?)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(?IN_CUST_DDA?)
</code>```

Body:
I'm trying to use a Lookup transformation to extract ACCT_ID from ACCT table based on the port CUST_DDA which is an output port from an expression.
I'm using an sqloverride as below. The initial lookup condition :

SUBSTR_ACCT_ID = IN_CUST_DDA

Override:

SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(IN_CUST_DDA))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)

The above sql override is failing due to the error : ORA-00904: "IN_CUST_DDA": invalid identifier

Is there a way to use the value from CUST_DDA port as an input port for the lookup. CUST_DDA is not a field that belongs to the ACCT table. Is there a way to do this.

Thanks.

Body:
To achieve this you need to configure your lookup as non-cached, so the query will be executed for each input row. Note, that this degrades performance a lot.
Next, you need to use a bit different syntax, enclosing the input port in question marks. Here's an example. In your case it should be something like (this might need a little adjustment):

SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(?IN_CUST_DDA?))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(?IN_CUST_DDA?)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(?IN_CUST_DDA?)


问:
Detect when AvPlayer is stopped
I'm using the AVPlayer class to read streams.
I have to monitor playback.

Here is my question : Is it possible to detect when the player is stopped by the user ?

I looked at MPMoviePlayerController. If the user stopped the video, this controller sends a notification : MPMovieFinishReasonUserExited. Is there an equivalent ?

答:
here's the swift 3 code for @Thlbaut's answer

```<code>self.avPlayer?.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
</code>```

then

```<code>override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "rate" {
        if let playRate = self.avPlayer?.rate {
            if playRate == 0.0 {
                print("playback paused")
            } else {
                print("playback started")
            }
        }
    }
}
</code>```

Title: Detect when AvPlayer is stopped

Body:
here's the swift 3 code for @Thlbaut's answer

self.avPlayer?.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)

then

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "rate" {
        if let playRate = self.avPlayer?.rate {
            if playRate == 0.0 {
                print("playback paused")
            } else {
                print("playback started")
            }
        }
    }
}


问:
How to filter data from csv file based on certain conditions using pandas dataframe
I have below data. These are satellite number ,its state and value.
Here Value of status 'B' is changing either 0 or some value. Value of
status 'A' is always 0.  Sat with status A and Val=0 for corresponding status 'B'is not acceptable
and not counted.

My aim is to iterate through each row and find correct Satellite present at each row. If any row is all A or B=0 that row is not counted.

So my desire output is :
 a=3,1,1,1
 Count=4 ,Row 4 is not counted

```<code>sv-01   sv-02  SV-03  state-01 state-02 state-03    val-01   val-02  val-03
 7        12     8         B          B         B     .23     0.34    1.03
 7        12     8         B          B         A     .35     0       0
 7        12     8         B          A         A     1.45    0       0
 7        12     8         A          A         A      0      0       0
 7        12     8         A          B         B      0      0     3.21
</code>```

# My python implementation is

```<code>  mask = read_data.filter(like='state').eq('A')
  result_count_Nj1 = mask.sum(axis=1).rsub(3)
</code>```

# I have tried

```<code>mask = read_data.filter(like='state').eq('A')  and read_data.filter(like='state').eq('B'!=0)
</code>```

# But it shows error. Please suggest where I am making mistake

Thanks

答:
I believe you need:</p>

```<code>#check B values
maskB = read_data.filter(like='state') == 'B'
print (maskB)
   state-01  state-02  state-03
0      True      True      True
1      True      True     False
2      True     False     False
3     False     False     False
4     False      True      True

#check not 0 values for B values only
mask0 = read_data.filter(like='val').where(maskB.values, 0) != 0
print (mask0)
   val-01  val-02  val-03
0    True    True    True
1    True   False   False
2    True   False   False
3   False   False   False
4   False   False    True

a = mask0.sum(1)
print (a)
0    3
1    1
2    1
3    0
4    1
dtype: int64

b = mask0.any(1).sum()
print (b)
4
</code>```

Body:
I have below data. These are satellite number ,its state and value.
Here Value of status 'B' is changing either 0 or some value. Value of
status 'A' is always 0.  Sat with status A and Val=0 for corresponding status 'B'is not acceptable
and not counted.

My aim is to iterate through each row and find correct Satellite present at each row. If any row is all A or B=0 that row is not counted.

So my desire output is :
 a=3,1,1,1
 Count=4 ,Row 4 is not counted

sv-01   sv-02  SV-03  state-01 state-02 state-03    val-01   val-02  val-03
 7        12     8         B          B         B     .23     0.34    1.03
 7        12     8         B          B         A     .35     0       0
 7        12     8         B          A         A     1.45    0       0
 7        12     8         A          A         A      0      0       0
 7        12     8         A          B         B      0      0     3.21

# My python implementation is

  mask = read_data.filter(like='state').eq('A')
  result_count_Nj1 = mask.sum(axis=1).rsub(3)

# I have tried

mask = read_data.filter(like='state').eq('A')  and read_data.filter(like='state').eq('B'!=0)

# But it shows error. Please suggest where I am making mistake

Thanks

Body:
I believe you need:

#check B values
maskB = read_data.filter(like='state') == 'B'
print (maskB)
   state-01  state-02  state-03
0      True      True      True
1      True      True     False
2      True     False     False
3     False     False     False
4     False      True      True

#check not 0 values for B values only
mask0 = read_data.filter(like='val').where(maskB.values, 0) != 0
print (mask0)
   val-01  val-02  val-03
0    True    True    True
1    True   False   False
2    True   False   False
3   False   False   False
4   False   False    True

a = mask0.sum(1)
print (a)
0    3
1    1
2    1
3    0
4    1
dtype: int64

b = mask0.any(1).sum()
print (b)
4


问:
How to properly overload the << operator for an ostream?
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

```<code>namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}
</code>```

And the "implementation":

```<code>using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}
</code>```

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

答: You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.

OwnerDisplayName: Matthias van der Vlies

Body:
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.

Here is the relevant part of my matrix class:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
    }
}

And the "implementation":

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

    [...]

}

This is the error given by the compiler:

matrix.cpp:459: error: 'std::ostream&
  Math::Matrix::operator<<(std::ostream&,
  const Math::Matrix&)' must take
  exactly one argument

I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)

LastEditorDisplayName: Mehrdad Afshari

OwnerDisplayName: Mehrdad Afshari


问:
ASP.NET, VisualStudio 2010: Web.config not publishing?
For some mysterious reason, all of a sudden when I publish my website, Web.config does not get coppied over.

At first when I saw that the properties of Web.config was set to "Do not copy", that seemed like the reason... but when I change the option, it doesn't stick.

Is there some shortcut key or some global TFS setting that might effect this?

This has never happened before...

答:
Apparently, if you look at "Properties", there is an option called "Build Action" ... set this to "Content" if you would like this file to be coppied over on Publish. If not, select "None"

Reference: http://forums.asp.net/p/1528920/3698633.aspx


问:
Android Studio 3.0 Execution failed for task: unable to merge dex
android studio was getting build error while build execution with following:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex"

My app:build.gradle file:

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

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.pdroid.foodieschoice"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.firebaseui:firebase-ui-auth:2.3.0'

    testCompile 'junit:junit:4.12'
}
configurations.all {
    resolutionStrategy {
        force 'com.android.support:appcompat-v7:26.0.1'
        force 'com.android.support:support-compat:26.0.1'
        force 'com.android.support:support-core-ui:26.0.1'
        force 'com.android.support:support-annotations:26.0.1'
        force 'com.android.support:recyclerview-v7:26.0.1'
    }
}

apply plugin: 'com.google.gms.google-services'
</code>```

any solutions

Edit: i have done with sample through firebase github site and solved

答:
For me, adding

```<code>multiDexEnabled true
</code>```

and

```<code>packagingOptions {
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }
</code>```

into the app level Build.gradle file solved the issue

Body:
android studio was getting build error while build execution with following:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex"

My app:build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.pdroid.foodieschoice"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.firebaseui:firebase-ui-auth:2.3.0'

    testCompile 'junit:junit:4.12'
}
configurations.all {
    resolutionStrategy {
        force 'com.android.support:appcompat-v7:26.0.1'
        force 'com.android.support:support-compat:26.0.1'
        force 'com.android.support:support-core-ui:26.0.1'
        force 'com.android.support:support-annotations:26.0.1'
        force 'com.android.support:recyclerview-v7:26.0.1'
    }
}

apply plugin: 'com.google.gms.google-services'

any solutions

Edit: i have done with sample through firebase github site and solved

Body:
For me, adding

multiDexEnabled true

and

packagingOptions {
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }

into the app level Build.gradle file solved the issue


问:
Maven root pom.xml marked as red when importing existing project into eclipse
When importing existing maven project into eclipse my root pom.xml is marked red.
when i select on the pom.xml the message reads :

Can't import project XYZ from an existing workspace folder

This only happens for the root pom.xml

Eclipse in use: Luna Service Release 2 (4.4.2)
Maven Integration for Eclipse 1.5.2.20150413-2215

I have tested with number of different maven projects and in different workspaces.

Please note this worked before, I have been working on some tutorials and created number of Maven projects with same name and artifact Ids etc. I have deleted all the earlier projects, but could there still be some conflicts ?

any suggestions will help

答:
Solution:

1.Click on Windows tab then Preference(if you are using Eclipse).

2.Search for the Workspaces first and remove all of them from list(which you can add later eventually)

3.Then search for Maven and choose User Setting and check your .m2 path along with the updated setting.xml(meanwhile check the proxy too)

4.After that restart your eclipse and import the existing maven project again.

I'm 100% percent sure u'll no longer face this issue after that. Good Luck :)


问:
Javascript showing number with leading zero
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the following button to call the function</p>
<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p></code>```

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old

答:
When you do 010,  it gets treated as base 8 which is octal. The decimal representation of octal 010 is 8. That is the reason you seeing 8.

Either remove that zero or pass it as a string like below

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the following button to call the function</p>
<form>
   <input type="button" onclick="sayHello('abc', '010')" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p></code>```

Body:
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}

Click the following button to call the function

<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>

Use different parameters inside the function and then try...

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old

Body:
When you do 010,  it gets treated as base 8 which is octal. The decimal representation of octal 010 is 8. That is the reason you seeing 8.

Either remove that zero or pass it as a string like below

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}

<p>Click the following button to call the function</p>
<form>
   <input type="button" onclick="sayHello('abc', '010')" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>