问:
Pickit 3 Connection Failed
I have been unable to connect to my Pickit 3 through MPLab IPE.
As background, I was never able to download or debug from MPLab X, usually I build the project on MPLab X and download it through the IPE.

Right now the only error showing up is "Connection Failed"

The Pickit3 Serial Number is being detected though, both on the IDE and the IPE.

Things I have already tried:

Connect Pickit 3 through an external powered USB Hub (3.0 and 2.0), this worked for about 2 weeks, then it suddenly failed again

Run as Administrator

Uninstall everything:
IDE, IPE, USB drivers (from device manager), even compilers (just in case)

Run on Safe Mode

I have tried on another PC, the Pickit seems fine as it is recognized and can download programs to a MCU

My PC's specs:

Acer Veriton M4630G

Windows 7 Professional 64-bit SP 1

Intel i7-4770

8GB RAM

Using PIC32MX460F512L

Any help would be really appreciated

答:
Did you try the following:

Does the PIC have power?

Did you follow the getting started chapter for connecting the PIC properly? Including decoupling capacitors etc? Is the powerline into the pic clean?

Did you try choosing a different programmer, then apply, then pick the PICKIT3? This sometimes resolves the issue.

Is the MCLR, PGD and PGC lines used for other stuff? Did you try disconnecting them from other hardware?

Usually if you disconnect the PICKIT3 when MPLABX is running looses the connection until you restart the software.
Sometimes a reboot is necessary, then insert the PICKIT3 and run the software in that order.

Try adding a new administrator user in Windows and login with that. If that works, it's probably a registry issue. You could try copying the new user registry for mplab to the old user (after making backups of course).

Title: Pickit 3 Connection Failed


来源: stackexchange

问:
Cleanest way to check if a date is in a range (Nullable Date)
What is the cleanest way to check if a supplied date is in a given date range?
For example:

```<code>DateTime? maxDate
DateTime? minDate
DateTime? userDate
</code>```

I want to check if the userDate is in the range.  Where min or max can be null.

So for example:

```<code>minDate = new DateTime(2017, 1, 1);
maxDate = null;
userDate = new DateTime(2017, 5, 3);
</code>```

In this scenario userDate would be in the range since it's greater then the minDate and no maxDate was specified.

I thought about using DateTime.Compare but it seems that I would create a mess of if/then statements to check userDate to the minDate and maxDate variables since the DateTime.Compare will only compare 2 dates at a time.

答:
```<code>if((minDate == null || minDate < userDate) && (maxDate == null || maxDate > userDate)) {
    // Do something
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the cleanest way to check if a supplied date is in a given date range?
For example:

DateTime? maxDate
DateTime? minDate
DateTime? userDate

I want to check if the userDate is in the range.  Where min or max can be null.

So for example:

minDate = new DateTime(2017, 1, 1);
maxDate = null;
userDate = new DateTime(2017, 5, 3);

In this scenario userDate would be in the range since it's greater then the minDate and no maxDate was specified.

I thought about using DateTime.Compare but it seems that I would create a mess of if/then statements to check userDate to the minDate and maxDate variables since the DateTime.Compare will only compare 2 dates at a time.


问:
How to convert all elements in an array to integer in JavaScript?
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

```<code>var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");
</code>```

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

答:
You need to loop through and parse/convert the elements in your array, like this:

```<code>var result_string = 'a,b,c,d|1,2,3,4',
    result = result_string.split("|"),
    alpha = result[0],
    count = result[1],
    count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers
</code>```

You can test it out here.  If the +, is throwing, think of it as:

```<code>for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

Body:
You need to loop through and parse/convert the elements in your array, like this:

var result_string = 'a,b,c,d|1,2,3,4',
    result = result_string.split("|"),
    alpha = result[0],
    count = result[1],
    count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers

You can test it out here.  If the +, is throwing, think of it as:

for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);


答:
Assuming null min/max would mean 'unbounded' in that direction, you could take advantage of the fact that DateTime itself has bounds.

For example:

```<code>public bool IsDateInRange(DateTime value, DateTime? min, DateTime? max)
{
    //Use provided min/max times if they were not null. Fallback to Min/Max supported values from DateTime
    min = min ?? DateTime.MinValue;
    max = max ?? DateTime.MaxValue;

    return value >= min && value <= max;
}
</code>```

I'm not really sure how you would want to handle the case where userDate = null. Is that ever in range? So my example function doesn't allow it. For that case, you could handle it explicitly if you want to define that behavior.

Title: Cleanest way to check if a date is in a range (Nullable Date)

Body:
Assuming null min/max would mean 'unbounded' in that direction, you could take advantage of the fact that DateTime itself has bounds.

For example:

public bool IsDateInRange(DateTime value, DateTime? min, DateTime? max)
{
    //Use provided min/max times if they were not null. Fallback to Min/Max supported values from DateTime
    min = min ?? DateTime.MinValue;
    max = max ?? DateTime.MaxValue;

    return value >= min && value <= max;
}

I'm not really sure how you would want to handle the case where userDate = null. Is that ever in range? So my example function doesn't allow it. For that case, you could handle it explicitly if you want to define that behavior.


问:
function to multiplying the values in a dictionary - Python
I am trying to define a function that performs the function of an boolean logic OR gate. The function should ideally accept a dictionary as my data is in a dictionary format.

I have looked up different things but I am now stuck.

I have started with somethign like this:

```<code>d = {'26': [0.5], '22': [0.5], '12': [0.5]}
def OR_function(**parameters):
    pi *= (1 - parameters)
    return (1 - pi)
OR_function(**d)
</code>```

(I know it's wrong)

Then after reading around all day I have managed to unpack the dictionary but I am still not able to perform the recursive in place product. I have had a look at functional programming operators but they accept only two parameters [https://docs.python.org/3/library/operator.html].

My function definition at the moment looks something like this:

```<code>import operator
def OR_function(**parameters):
print(operator.imul(list(*parameters)))
#pi = 0
#for i, j in parameters.items():
#    pi *= (1 - j[0])
#print(pi)
return 1 #- pi
</code>```

and it raises the following error:
'TypeError: op_imul expected 2 arguments, got 3'

Can someone help me?
Alternative ways to approach this are welcome. Please do explain the code in the answer so I can learn something.

答:
Unless I misunderstood what you are trying to do there should be no need to unpack the dictionary. This worked for me:

```<code>d = {'26': [0.5], '22': [0.5], '12': [0.5]}

def OR_function(parameters):
  pi = 1

  print(parameters)
  print("=================")

  for key, value in parameters.items():
      print(pi)
      pi *= (1 - value[0])

  print("=================")
  print(pi)
  return (1 - pi)

OR_function(d)
</code>```

Which yields this output (and it seems correct):

```<code>{'22': [0.5], '12': [0.5], '26': [0.5]}
=================
1
0.5
0.25
=================
0.125
</code>```

If the values in the dictionary are lists with more than one element the changes needed are very small, you only need an extra for loop:

```<code>d = {'26': [0.5, 0.7], '22': [0.5, 0.9], '12': [0.5, 0.5]}

def OR_function(parameters):
  pi = 1

  print(parameters)
  print("=================")

  for key, value in parameters.items():
      for x in value:
          print(pi)
          pi *= (1 - x)

  print(pi)
  return (1 - pi)

OR_function(d)
</code>```

From the commented code you posted:

```<code>#pi = 0
#for i, j in parameters.items():
#    pi *= (1 - j[0])
#print(pi)
</code>```

It looks like your problem was that you were initialising the variable pi to 0, which will yield the value of 0 in a recursive multiplication.

Body:
I am trying to define a function that performs the function of an boolean logic OR gate. The function should ideally accept a dictionary as my data is in a dictionary format.

I have looked up different things but I am now stuck.

I have started with somethign like this:

d = {'26': [0.5], '22': [0.5], '12': [0.5]}
def OR_function(**parameters):
    pi *= (1 - parameters)
    return (1 - pi)
OR_function(**d)

(I know it's wrong)

Then after reading around all day I have managed to unpack the dictionary but I am still not able to perform the recursive in place product. I have had a look at functional programming operators but they accept only two parameters [https://docs.python.org/3/library/operator.html].

My function definition at the moment looks something like this:

import operator
def OR_function(**parameters):
print(operator.imul(list(*parameters)))
#pi = 0
#for i, j in parameters.items():
#    pi *= (1 - j[0])
#print(pi)
return 1 #- pi

and it raises the following error:
'TypeError: op_imul expected 2 arguments, got 3'

Can someone help me?
Alternative ways to approach this are welcome. Please do explain the code in the answer so I can learn something.

Body:
Unless I misunderstood what you are trying to do there should be no need to unpack the dictionary. This worked for me:

d = {'26': [0.5], '22': [0.5], '12': [0.5]}

def OR_function(parameters):
  pi = 1

  print(parameters)
  print("=================")

  for key, value in parameters.items():
      print(pi)
      pi *= (1 - value[0])

  print("=================")
  print(pi)
  return (1 - pi)

OR_function(d)

Which yields this output (and it seems correct):

{'22': [0.5], '12': [0.5], '26': [0.5]}
=================
1
0.5
0.25
=================
0.125

If the values in the dictionary are lists with more than one element the changes needed are very small, you only need an extra for loop:

d = {'26': [0.5, 0.7], '22': [0.5, 0.9], '12': [0.5, 0.5]}

def OR_function(parameters):
  pi = 1

  print(parameters)
  print("=================")

  for key, value in parameters.items():
      for x in value:
          print(pi)
          pi *= (1 - x)

  print(pi)
  return (1 - pi)

OR_function(d)

From the commented code you posted:

#pi = 0
#for i, j in parameters.items():
#    pi *= (1 - j[0])
#print(pi)

It looks like your problem was that you were initialising the variable pi to 0, which will yield the value of 0 in a recursive multiplication.


问:
Going Two Activities back?
I have this Activities sequence:
Avtivity01 => Avtivity02 => Avtivity03

You can go from Avtivity01 to Avtivity02 after you click a button.

You can go from Avtivity02 to Avtivity03 after you click a button.

-

I want to go from Activity03 to Activity01 DIRECTLY after I click a button.

-

NOTE:

I do NOT want to use Intent, because I want to have Activity01 as if I pressed the back button from Activity02

How to do that, please?

答:
You can go back more than one screen to which ever screen you need using intent and use flags to prevent going back to same screen :</p>

```<code>Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);

gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(gotoScreenVar);
</code>```

Title: Going Two Activities back?

Body:
You can go back more than one screen to which ever screen you need using intent and use flags to prevent going back to same screen :

Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);

gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(gotoScreenVar);


问:
How to read stringified JSON string in Java
Kindly need your help as this really taking me long time to try.
From JSP, I passed the stingnify JSON object as a String to the Java action, it like

```<code>String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"NPD STATION SDN BHD"},
{"dealerID":"VARSSTH008","dealerName":"Winjaya Teleshop"}]
</code>```

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help!!!

答: Well you could write your own JSON parser, but there's no need to re-invent the wheel - there are a number of robust, mature JSON parsers freely available. I use JSONObject  and JSONArray  from Tapestry. If you download Tapestry 5 and unpack it, then just include the library tapestry-core-5.0.18.jar in your build path and you'll be set to go. Both JSONObject and JSONArray take a String as constructor argument, and the api is fully documented in those links.

ContentLicense: CC BY-SA 2.5

Body:
Kindly need your help as this really taking me long time to try.
From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"NPD STATION SDN BHD"},
{"dealerID":"VARSSTH008","dealerName":"Winjaya Teleshop"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help!!!


问:
StatsModel quantile regression ValueError
I got an error after running quantile regression in Python StatsModel module.  The error is following:

ValueError                                Traceback (most recent call last)
<ipython-input-221-3547de1b5e0d> in <module>()
 16 model = smf.quantreg(fit_formula, train)
 17
---> 18 fitted_model = model.fit(0.2)
 19
 20 #fitted_model.predict(test)

 in fit(self, q, vcov, kernel, bandwidth, max_iter, p_tol, **kwargs)
177             resid = np.abs(resid)
178             xstar = exog / resid[:, np.newaxis]
--> 179             diff = np.max(np.abs(beta - beta0))
180             history['params'].append(beta)
181             history['mse'].append(np.mean(resid*resid))

ValueError: operands could not be broadcast together with shapes (178,) (176,)
```

<p>I was thinking it was possibly caused by constant features, so I removed those, but I still got the same error.  I am wondering what is the cause.  My code is following:</p>

```quantiles = np.arange(.05, .99, .1)

cols = train.columns.tolist()[1:-2]
fit_formula = ''
for c in cols:
    fit_formula =  fit_formula + ' + ' + c
fit_formula = 'revenue ~ ' + train.columns.tolist()[0] + fit_formula

model = smf.quantreg(fit_formula, train)

fitted_model = model.fit(0.2)
```

答:
I think your design matrix is singular, i.e. this does not hold for your data:

np.linalg.matrix_rank(model.exog) == model.exog.shape[1]

Guessing from looking at the code: The parameter, beta, is initialized for the iteration loop with

```<code>exog_rank = np_matrix_rank(self.exog)
beta = np.ones(exog_rank)
</code>```

which has different lengtht than the beta from the auxiliary weighted least squares regression, and the convergence check fails. The iteratively reweighted step used a generalized inverse, pinv, which does not raise an exception because of the singular design matrix.

Based on your traceback, (178,) (176,), you would still have two collinear columns that need to be dropped.

(That's a bug: Either it should raise a proper exception for the singular case, or handle it with pinv throughout.)

Body:
I got an error after running quantile regression in Python StatsModel module.  The error is following:

ValueError                                Traceback (most recent call last)
<ipython-input-221-3547de1b5e0d> in <module>()
 16 model = smf.quantreg(fit_formula, train)
 17
---> 18 fitted_model = model.fit(0.2)
 19
 20 #fitted_model.predict(test)

 in fit(self, q, vcov, kernel, bandwidth, max_iter, p_tol, **kwargs)
177             resid = np.abs(resid)
178             xstar = exog / resid[:, np.newaxis]
--> 179             diff = np.max(np.abs(beta - beta0))
180             history['params'].append(beta)
181             history['mse'].append(np.mean(resid*resid))

ValueError: operands could not be broadcast together with shapes (178,) (176,)

I was thinking it was possibly caused by constant features, so I removed those, but I still got the same error.  I am wondering what is the cause.  My code is following:

quantiles = np.arange(.05, .99, .1)

cols = train.columns.tolist()[1:-2]
fit_formula = ''
for c in cols:
    fit_formula =  fit_formula + ' + ' + c
fit_formula = 'revenue ~ ' + train.columns.tolist()[0] + fit_formula

model = smf.quantreg(fit_formula, train)

fitted_model = model.fit(0.2)

Body:
I think your design matrix is singular, i.e. this does not hold for your data:

np.linalg.matrix_rank(model.exog) == model.exog.shape[1]

Guessing from looking at the code: The parameter, beta, is initialized for the iteration loop with

exog_rank = np_matrix_rank(self.exog)
beta = np.ones(exog_rank)

which has different lengtht than the beta from the auxiliary weighted least squares regression, and the convergence check fails. The iteratively reweighted step used a generalized inverse, pinv, which does not raise an exception because of the singular design matrix.

Based on your traceback, (178,) (176,), you would still have two collinear columns that need to be dropped.

(That's a bug: Either it should raise a proper exception for the singular case, or handle it with pinv throughout.)


问:
set a default value if the mysql selection query return empty rows
i have a select query in my php file as next >>

```<code>$sql = 'SELECT *
    FROM notes
    WHERE notes.code_apogee='.$CA.'';
</code>```

that return some empty rows where i should set a default value << 'en attend'

i used IFNULL as below :

```<code>SELECT IFNULL( (SELECT *
    FROM notes
    WHERE notes.code_apogee='.$CA') ,'en attend');
</code>```

but an error appear

```<code> MySQL a répondu: Documentation
#1241 - Operand should contain 1 column(s)
</code>```

any help ?? please

答:
IFNULL() won't take a subselect (which is all the columns in your case) as param, but just one (plus the else value).

So your query should be something like this:

```<code>SELECT id,
    IFNULL(notes.title, 'en attend') as title,
    IFNULL(notes.body, 'en attend') as body
FROM notes
WHERE notes.code_apogee='.$CA'
</code>```

(I just invented notes.title & notes.body, you need to replace that with actual column names)

You could of course let the db just return the NULLs and add 'en attend' when displaying the results:

```<code>echo !is_null($row['title']) ? $row['title'] : 'en attend';
</code>```

Body:
i have a select query in my php file as next >>

$sql = 'SELECT *
    FROM notes
    WHERE notes.code_apogee='.$CA.'';

that return some empty rows where i should set a default value << 'en attend'

i used IFNULL as below :

SELECT IFNULL( (SELECT *
    FROM notes
    WHERE notes.code_apogee='.$CA') ,'en attend');

but an error appear

 MySQL a répondu: Documentation
#1241 - Operand should contain 1 column(s)

any help ?? please

Body:
IFNULL() won't take a subselect (which is all the columns in your case) as param, but just one (plus the else value).

So your query should be something like this:

SELECT id,
    IFNULL(notes.title, 'en attend') as title,
    IFNULL(notes.body, 'en attend') as body
FROM notes
WHERE notes.code_apogee='.$CA'

(I just invented notes.title & notes.body, you need to replace that with actual column names)

You could of course let the db just return the NULLs and add 'en attend' when displaying the results:

echo !is_null($row['title']) ? $row['title'] : 'en attend';


问:
iOS app is only crashing on TestFlight build
I have an ios app in Swift.The app runs fine and does not crash when uploaded locally from xcode. But the app is crashing when uploaded from testflight.
I found that there is nothing wrong in code.
I have implemented Crashlytics in my app, it has given following report.

```<code>Crashed: com.apple.main-thread
EXC_BREAKPOINT 0x0000000100160fe4

Crashed: com.apple.main-thread
0  App                     0x100160fe4 HomeViewController.viewDidLoad() -> () (HomeViewController.swift:57)

1  App                     0x100161014 @objc HomeViewController.viewDidLoad() -> () (HomeViewController.swift)

2  UIKit                          0x18c373ec0 -[UIViewController loadViewIfRequired] + 1036

3  UIKit                          0x18c38b94c -[UIViewController __viewWillAppear:] + 132

4  UIKit                          0x18c5101d4 -[UINavigationController _startCustomTransition:] + 1144

5  UIKit                          0x18c42ab78 -[UINavigationController _startDeferredTransitionIfNeeded:] + 676

6  UIKit                          0x18c42a7e0 -[UINavigationController __viewWillLayoutSubviews] + 64

7  UIKit                          0x18c42a744 -[UILayoutContainerView layoutSubviews] + 188

8  UIKit                          0x18c37107c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1200

9  QuartzCore                     0x189561274 -[CALayer layoutSublayers] + 148

10 QuartzCore                     0x189555de8 CA::Layer::layout_if_needed(CA::Transaction*) + 292

11 QuartzCore                     0x189555ca8 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32

12 QuartzCore                     0x1894d134c CA::Context::commit_transaction(CA::Transaction*) + 252

13 QuartzCore                     0x1894f83ac CA::Transaction::commit() + 504
14 QuartzCore                     0x1894f8e78 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 120

15 CoreFoundation                 0x1861f09a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32

16 CoreFoundation                 0x1861ee630 __CFRunLoopDoObservers + 372

17 CoreFoundation                 0x1861eea7c __CFRunLoopRun + 956

18 CoreFoundation                 0x18611eda4 CFRunLoopRunSpecific + 424

19 GraphicsServices               0x187b88074 GSEventRunModal + 100

20 UIKit                          0x18c3d9058 UIApplicationMain + 208

21 App                     0x1000d8688 main (NewProductData.swift:18)

22 libdyld.dylib                  0x18512d59c start + 4
</code>```

I am not understanding anything from this reports, please help me out if anyone knows.

Here is viewDidload

```<code>  override func viewDidLoad() {
    super.viewDidLoad()
     Giving instance of HomeViewController to AppDelegate
      let appDele = UIApplication.shared.delegate as! AppDelegate
      appDele.homeVC = self
    token = FIRInstanceID.instanceID().token()!
//Method to handle Firebase token
    UserDefaults.standard.set(token, forKey: "Notificationtoken")
    print("@@@@@@@@@@@@@@@@@@@@@@@ token provided is \(String(describing: token))")
     let tokenstr = UserDefaults.standard.value(forKey: "Notificationtoken") as! String
    if(token == tokenstr){
        handleFCMToken(token: tokenstr)
    }
    else{
        handleFCMToken(token: token!)

    }

    setUpNavBar()
    setPopUpImage()
    setUpcarousel()
    setUpDelegates()
    let help = Helper()

    help.setUpGoogleAnalytics(screenName: "Home")

    self.presenter = HomeViewPresenter(homeView: self)
    presenter.getCarousel()
    if(showProfile){
        ProfileClicked()
    }
    // Do any additional setup after loading the view.
}
</code>```

And here is viewWillAppear

```<code> override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setUpUI()

}
</code>```

and method of setupUI

```<code> func setUpUI(){
    let wholesaler:Wholesaler = Helper.getWsProfile()

    DispatchQueue.main.async {
        self.wholesalerName.text = "Hello, \(wholesaler.wholesaler_name)"
        self.pdsPoints.text = "\(wholesaler.pdsPoints!)"
        self.visibilityPoints.text = "\(wholesaler.visibilityPoins!)"
    }
    iconNameString = ["SMS","Customer\n Groups","Visibility\n Contest","My\n Earnings","\(wholesaler.lastSchemeMonth!)\n Schemes","App\n News", "", "Contact\n Us"]

}
</code>```

答:
I think that viewing some code of your HomeViewController will give us more insight.

But here some comments:

Not sure about the full stack, but its seems weird that viewWillAppear is being called before viewDidLoad for some reason. Are you calling super correctly on those corresponding methods?

Have you try profiling the app using instruments in release mode vs debug mode? You can manage this on your schema settings.

Another hint, but I think it kind of advanced for your scenario, is the optimization level. Go to your target settings and search for Optimization Level, you'll notice it is different for debug and release. Sometimes complex algorithms with multiple blocks and/or threads may be affected by this.

Home it helps

Body:
I have an ios app in Swift.The app runs fine and does not crash when uploaded locally from xcode. But the app is crashing when uploaded from testflight.
I found that there is nothing wrong in code.
I have implemented Crashlytics in my app, it has given following report.

Crashed: com.apple.main-thread
EXC_BREAKPOINT 0x0000000100160fe4

Crashed: com.apple.main-thread
0  App                     0x100160fe4 HomeViewController.viewDidLoad() -> () (HomeViewController.swift:57)

1  App                     0x100161014 @objc HomeViewController.viewDidLoad() -> () (HomeViewController.swift)

2  UIKit                          0x18c373ec0 -[UIViewController loadViewIfRequired] + 1036

3  UIKit                          0x18c38b94c -[UIViewController __viewWillAppear:] + 132

4  UIKit                          0x18c5101d4 -[UINavigationController _startCustomTransition:] + 1144

5  UIKit                          0x18c42ab78 -[UINavigationController _startDeferredTransitionIfNeeded:] + 676

6  UIKit                          0x18c42a7e0 -[UINavigationController __viewWillLayoutSubviews] + 64

7  UIKit                          0x18c42a744 -[UILayoutContainerView layoutSubviews] + 188

8  UIKit                          0x18c37107c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1200

9  QuartzCore                     0x189561274 -[CALayer layoutSublayers] + 148

10 QuartzCore                     0x189555de8 CA::Layer::layout_if_needed(CA::Transaction*) + 292

11 QuartzCore                     0x189555ca8 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32

12 QuartzCore                     0x1894d134c CA::Context::commit_transaction(CA::Transaction*) + 252

13 QuartzCore                     0x1894f83ac CA::Transaction::commit() + 504
14 QuartzCore                     0x1894f8e78 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 120

15 CoreFoundation                 0x1861f09a8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32

16 CoreFoundation                 0x1861ee630 __CFRunLoopDoObservers + 372

17 CoreFoundation                 0x1861eea7c __CFRunLoopRun + 956

18 CoreFoundation                 0x18611eda4 CFRunLoopRunSpecific + 424

19 GraphicsServices               0x187b88074 GSEventRunModal + 100

20 UIKit                          0x18c3d9058 UIApplicationMain + 208

21 App                     0x1000d8688 main (NewProductData.swift:18)

22 libdyld.dylib                  0x18512d59c start + 4

I am not understanding anything from this reports, please help me out if anyone knows.

Here is viewDidload

  override func viewDidLoad() {
    super.viewDidLoad()
     Giving instance of HomeViewController to AppDelegate
      let appDele = UIApplication.shared.delegate as! AppDelegate
      appDele.homeVC = self
    token = FIRInstanceID.instanceID().token()!
//Method to handle Firebase token
    UserDefaults.standard.set(token, forKey: "Notificationtoken")
    print("@@@@@@@@@@@@@@@@@@@@@@@ token provided is \(String(describing: token))")
     let tokenstr = UserDefaults.standard.value(forKey: "Notificationtoken") as! String
    if(token == tokenstr){
        handleFCMToken(token: tokenstr)
    }
    else{
        handleFCMToken(token: token!)

    }

    setUpNavBar()
    setPopUpImage()
    setUpcarousel()
    setUpDelegates()
    let help = Helper()

    help.setUpGoogleAnalytics(screenName: "Home")

    self.presenter = HomeViewPresenter(homeView: self)
    presenter.getCarousel()
    if(showProfile){
        ProfileClicked()
    }
    // Do any additional setup after loading the view.
}

And here is viewWillAppear

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setUpUI()

}

and method of setupUI

 func setUpUI(){
    let wholesaler:Wholesaler = Helper.getWsProfile()

    DispatchQueue.main.async {
        self.wholesalerName.text = "Hello, \(wholesaler.wholesaler_name)"
        self.pdsPoints.text = "\(wholesaler.pdsPoints!)"
        self.visibilityPoints.text = "\(wholesaler.visibilityPoins!)"
    }
    iconNameString = ["SMS","Customer\n Groups","Visibility\n Contest","My\n Earnings","\(wholesaler.lastSchemeMonth!)\n Schemes","App\n News", "", "Contact\n Us"]

}


问:
can't resolve Cannot find module 'rxjs' within typescript/webpack
I've got a problem to load rxjs into a simple webpack setup (without angular). I'm running:

```<code>./node_modules/.bin/webpack --config webpack.config.js --watch
</code>```

to start webpack. The only file with the app, src/app.ts, starts with:

```<code>import { Observable } from 'rxjs';
</code>```

and this line is highlighted in VSCode and in webpack console with this error:

```<code>Cannot find module 'rxjs'.
</code>```

But the overall output works fine. Just this console error.

tsconfig.json:

```<code>{
    "compilerOptions": {
         "target": "es2015"
    },
    "files": [
        "src/app.ts"
    ]
}
</code>```

webpack.config.js:

```<code>module.exports = {
    entry: "./src/app.ts",
    output: {
        filename: "dist/bundle.js"
    },
    resolve: {
        // Add '.ts' and '.tsx' as a resolvable extension.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            { test: /\.ts?$/, loader: "ts-loader" }
        ]
    }
}
</code>```

package.json (everything installed properly):

```<code>{
  "scripts": {
    "start": "./node_modules/.bin/webpack --config webpack.config.js --watch"
  },
  "devDependencies": {
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "rxjs": "^5.4.0"
  }
}
</code>```

I can't find the reason for why can't ts/webpack resolve where is rxjs

答:
You must add node_modules to your webpack resolve.modules config:

```<code> resolve: {
    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    extensions: [".js", ".json", ".jsx", ".css"],
 }
</code>```

more info on https://webpack.js.org/configuration/resolve/

Body:
I've got a problem to load rxjs into a simple webpack setup (without angular). I'm running:

./node_modules/.bin/webpack --config webpack.config.js --watch

to start webpack. The only file with the app, src/app.ts, starts with:

import { Observable } from 'rxjs';

and this line is highlighted in VSCode and in webpack console with this error:

Cannot find module 'rxjs'.

But the overall output works fine. Just this console error.

tsconfig.json:

{
    "compilerOptions": {
         "target": "es2015"
    },
    "files": [
        "src/app.ts"
    ]
}

webpack.config.js:

module.exports = {
    entry: "./src/app.ts",
    output: {
        filename: "dist/bundle.js"
    },
    resolve: {
        // Add '.ts' and '.tsx' as a resolvable extension.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            { test: /\.ts?$/, loader: "ts-loader" }
        ]
    }
}

package.json (everything installed properly):

{
  "scripts": {
    "start": "./node_modules/.bin/webpack --config webpack.config.js --watch"
  },
  "devDependencies": {
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "rxjs": "^5.4.0"
  }
}

I can't find the reason for why can't ts/webpack resolve where is rxjs

Body:
You must add node_modules to your webpack resolve.modules config:

 resolve: {
    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    extensions: [".js", ".json", ".jsx", ".css"],
 }

more info on https://webpack.js.org/configuration/resolve/


问:
Case statements: multiple variables with multiple possibilities for each variable
At first I thought this syntax worked but it seems when will only check the first value of the groups, if any of the first values fail it will return locked. to bad the or operand doesn't work here.

```<code>def lock(a,b,c,d)
  case [a,b,c,d]
    when[(3||5||7), 2, (5||6), (8||9||0)]
      "unlocked"
    else
      "locked"
  end
end

lock(3, 2, 5, 8)
lock(5, 2, 5, 0)
lock(5, 2, 6, 8)
lock(7, 2, 5, 8)
lock(7, 2, 6, 9)
</code>```

I could do an if else statement for each variable, but i was hoping there was a way to do a case statement without having to make multiple when statements.

答:
As has been explained by others, this problem does not lend itself to the use of a case statement.

Since the variables appear to be digits, you could convert them to strings and use a regular expression.

```<code>def lock(entry, valid)
  r = /#{valid.map { |a| '['+a.join('|')+']' }.join }/
  entry.join.match?(r) ? 'unlocked' : 'locked'
end
</code>```

Suppose

```<code>valid = [[3, 5, 7], [2], [5, 6], [8, 9, 0]]
</code>```

We compute the following regular expression for this value of valid:

```<code>r #=> /[3|5|7][2][5|6][8|9|0]/
</code>```

Try it:

```<code>lock([3, 2, 5, 8], valid) #=> "unlocked"
lock([5, 2, 5, 0], valid) #=> "unlocked"
lock([5, 2, 6, 8], valid  #=> "unlocked"
lock([7, 2, 5, 8], valid) #=> "unlocked"
lock([7, 2, 6, 9], valid) #=> "unlocked"
lock([5, 2, 4, 0], valid) #=> "locked"
</code>```

Body:
At first I thought this syntax worked but it seems when will only check the first value of the groups, if any of the first values fail it will return locked. to bad the or operand doesn't work here.

def lock(a,b,c,d)
  case [a,b,c,d]
    when[(3||5||7), 2, (5||6), (8||9||0)]
      "unlocked"
    else
      "locked"
  end
end

lock(3, 2, 5, 8)
lock(5, 2, 5, 0)
lock(5, 2, 6, 8)
lock(7, 2, 5, 8)
lock(7, 2, 6, 9)

I could do an if else statement for each variable, but i was hoping there was a way to do a case statement without having to make multiple when statements.

Body:
As has been explained by others, this problem does not lend itself to the use of a case statement.

Since the variables appear to be digits, you could convert them to strings and use a regular expression.

def lock(entry, valid)
  r = /#{valid.map { |a| '['+a.join('|')+']' }.join }/
  entry.join.match?(r) ? 'unlocked' : 'locked'
end

Suppose

valid = [[3, 5, 7], [2], [5, 6], [8, 9, 0]]

We compute the following regular expression for this value of valid:

r #=> /[3|5|7][2][5|6][8|9|0]/

Try it:

lock([3, 2, 5, 8], valid) #=> "unlocked"
lock([5, 2, 5, 0], valid) #=> "unlocked"
lock([5, 2, 6, 8], valid  #=> "unlocked"
lock([7, 2, 5, 8], valid) #=> "unlocked"
lock([7, 2, 6, 9], valid) #=> "unlocked"
lock([5, 2, 4, 0], valid) #=> "locked"


问:
How to get Inno Setup to unzip a single file?
Is there a way to unzip just one file from a zip?
I'm using code based on response for  How to get Inno Setup to unzip a file it installed (all as part of the one installation process), works perfect for unzip but don't have an idea how can it unzip a single file: </p>

<pre class="lang-pascal prettyprint-override"><code>[Code]:

const
  NO_PROGRESS_BOX = 4;
  RESPOND_YES_TO_ALL = 16;

procedure UnZip(ZipPath, TargetPath: string);
var
  Shell: Variant;
  ZipFile: Variant;
  TargetFolder: Variant;
begin
  Shell := CreateOleObject('Shell.Application');

  ZipFile := Shell.NameSpace(ZipPath);
  if VarIsClear(ZipFile) then
    RaiseException(Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));

  TargetFolder := Shell.NameSpace(TargetPath);
  if VarIsClear(TargetFolder) then
    RaiseException(Format('Target path "%s" does not exist', [TargetPath]));

  TargetFolder.CopyHere(ZipFile.Items, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;
</code>```

答:
I found a way that works, not what I was expected but is functional.</p>

```<code>UnZip(AppFolder+'\modulos\seimpresoras-2.2.zip', tmpFolder);
FileCopy(tmpFolder+'\seimpresoras\resources\default.properties', AppFolder+'\printers.properties', False);
</code>```

Body:
Is there a way to unzip just one file from a zip?
I'm using code based on response for  How to get Inno Setup to unzip a file it installed (all as part of the one installation process), works perfect for unzip but don't have an idea how can it unzip a single file:

[Code]:

const
  NO_PROGRESS_BOX = 4;
  RESPOND_YES_TO_ALL = 16;

procedure UnZip(ZipPath, TargetPath: string);
var
  Shell: Variant;
  ZipFile: Variant;
  TargetFolder: Variant;
begin
  Shell := CreateOleObject('Shell.Application');

  ZipFile := Shell.NameSpace(ZipPath);
  if VarIsClear(ZipFile) then
    RaiseException(Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));

  TargetFolder := Shell.NameSpace(TargetPath);
  if VarIsClear(TargetFolder) then
    RaiseException(Format('Target path "%s" does not exist', [TargetPath]));

  TargetFolder.CopyHere(ZipFile.Items, NO_PROGRESS_BOX or RESPOND_YES_TO_ALL);
end;

Body:
I found a way that works, not what I was expected but is functional.

UnZip(AppFolder+'\modulos\seimpresoras-2.2.zip', tmpFolder);
FileCopy(tmpFolder+'\seimpresoras\resources\default.properties', AppFolder+'\printers.properties', False);


问:
log4j error on eclipse
For some reason, I am getting the following error for logs. After doing some research and some comments from the previous posts, I have created a log4j file, but it still does not work. Any help is greatly appreciated.</p>

```<code>log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.BasicClientConnectionManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

答:
this is the manual please read through it
URL for official manual

the very first thing you can do is in your main method call this

```<code>BasicConfigurator.configure();
</code>```

or you can also add this in your log4j.properties

```<code># Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
</code>```

just make sure log4j.properties file is in your eclipse project classpath

Title: log4j error on eclipse

Body:
For some reason, I am getting the following error for logs. After doing some research and some comments from the previous posts, I have created a log4j file, but it still does not work. Any help is greatly appreciated.

log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.BasicClientConnectionManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Body:
this is the manual please read through it
URL for official manual

the very first thing you can do is in your main method call this

BasicConfigurator.configure();

or you can also add this in your log4j.properties

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

just make sure log4j.properties file is in your eclipse project classpath


问:
Check if user inputs a week or weekend day, using for loop
sorry if this question feels redundant, but I havent been able to find the answer with this method. It doesnt get answered on the link provided.
 I have been trying to make a Javascript program that checks if the input from the user is a Week day or weekend. It has to be done with for or do while loops.

I want my program to check if the user input is in the array, if it is, the program should be able to tell if it`s a working day or weekend.

My problem: It always returns working day, even if I put Saturday or Sunday.

this is tagged as Javascript, but works for any language since it`s basic stuff.

Here`s my code so far

```<code>var input = prompt("Enter a day of the week");
var day = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

for (var i = 0; i <= day.length; i++)
{
    if(input >= day[5]){
        console.log("It´s weekend!"); {break;}
    }else
    {
        console.log("It´s a working day");

    }
}
</code>```

答:
I don't think you have to use a for loop. The following code should work:

```<code>var input = prompt("Enter a day of the week");
var workingday = ["monday", "tuesday", "Wensday", "thursday", "friday"];
var weekend = ["saturday", "sunday"]

if (workingday.indexOf(input) != -1) {
     console.log("It´s a working day!");
} else if (weekend.indexOf(input) != -1) {
     console.log("It´s weekend!");
} else {
     console.log("Invalid input!");
}
</code>```

By the way, you misspelled "Wensday".
To use for loop:

```<code>for (var i = 0; i < day.length; i++)  {
    if (day[i] == input)  {
        console.log((i >= 5) ? "It's weekend!" : "It's a working day");
    }
}
</code>```

Body:
sorry if this question feels redundant, but I havent been able to find the answer with this method. It doesnt get answered on the link provided.
 I have been trying to make a Javascript program that checks if the input from the user is a Week day or weekend. It has to be done with for or do while loops.

I want my program to check if the user input is in the array, if it is, the program should be able to tell if it`s a working day or weekend.

My problem: It always returns working day, even if I put Saturday or Sunday.

this is tagged as Javascript, but works for any language since it`s basic stuff.

Here`s my code so far

var input = prompt("Enter a day of the week");
var day = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

for (var i = 0; i <= day.length; i++)
{
    if(input >= day[5]){
        console.log("It´s weekend!"); {break;}
    }else
    {
        console.log("It´s a working day");

    }
}

Body:
I don't think you have to use a for loop. The following code should work:

var input = prompt("Enter a day of the week");
var workingday = ["monday", "tuesday", "Wensday", "thursday", "friday"];
var weekend = ["saturday", "sunday"]

if (workingday.indexOf(input) != -1) {
     console.log("It´s a working day!");
} else if (weekend.indexOf(input) != -1) {
     console.log("It´s weekend!");
} else {
     console.log("Invalid input!");
}

By the way, you misspelled "Wensday".
To use for loop:

for (var i = 0; i < day.length; i++)  {
    if (day[i] == input)  {
        console.log((i >= 5) ? "It's weekend!" : "It's a working day");
    }
}


答:
Your input is a string and your days are an array so you can't do a greater-than comparison in your if statement.

Instead, you need to find at what index (number) the day the input matches. There are already an array method called indexOf() finding the index of an item in an array. You can  then see if that day number is greater than or equal to the days of the weekend.

```<code>var dayNumber = days.indexOf(input);
if (dayNumber >= 5) {
  // it's the weekend
}
</code>```

However, if you have to use a for loop, you can simulate what indexOf() does. It works by increasing an number dayNumber each loop and then using that number to index into the days array. You can then compare the value at that index with your input. If it matches, you know what day number it is and can see if it's greater than or equal to the days of the weekend.

```<code>for (var dayNumber = 0; dayNumber < days.length; dayNumber++) {
  // check if the input matches the current index of the array
  if (input == days[dayNumber]) {
    // if it does, check if the day number is on the weekend
    if (dayNumber >= 5) {
      // it's the weekend
    }
  }
}
</code>```

This can be made more compact using an "and operator" && to combine the two nested if statements.

```<code>if (input == days[dayNumber] && dayNumber >= 5) {
  // it's the weekend
}
</code>```

Title: Check if user inputs a week or weekend day, using for loop

Body:
Your input is a string and your days are an array so you can't do a greater-than comparison in your if statement.

Instead, you need to find at what index (number) the day the input matches. There are already an array method called indexOf() finding the index of an item in an array. You can  then see if that day number is greater than or equal to the days of the weekend.

var dayNumber = days.indexOf(input);
if (dayNumber >= 5) {
  // it's the weekend
}

However, if you have to use a for loop, you can simulate what indexOf() does. It works by increasing an number dayNumber each loop and then using that number to index into the days array. You can then compare the value at that index with your input. If it matches, you know what day number it is and can see if it's greater than or equal to the days of the weekend.

for (var dayNumber = 0; dayNumber < days.length; dayNumber++) {
  // check if the input matches the current index of the array
  if (input == days[dayNumber]) {
    // if it does, check if the day number is on the weekend
    if (dayNumber >= 5) {
      // it's the weekend
    }
  }
}

This can be made more compact using an "and operator" && to combine the two nested if statements.

if (input == days[dayNumber] && dayNumber >= 5) {
  // it's the weekend
}


问:
In RStudio, making slide deck with RMarkdown, how can I easily change the theme?
I'm writing an .rmd file in RStudio, and using the Knit button to create a slide deck.  I have two options, it appears, ioslides and slidy.  I don't really like the default look-and-feel of either.  (I think ioslides uses screen real estate inefficiently, and slidy feels like a graphic designer wasn't involved.)

I did a web search for alternative templates/styles/themes, and came upon pages like this gallery, but the tools there seem to be for use outside RStudio, as completely independent projects.  In other words, they're not just themes for what I've got, but entirely other solutions that would change my workflow.

Is there a simple way to tell RStudio to use a different template/theme with either ioslides or slidy?  For example, can I download a CSS file from somewhere, and point RStudio to it with the css: option in the yaml header of my .rmd file?  If so, is there a gallery of such CSS templates?

答:
Have you tried using the built in Bootswatch themes? They're fairly limited, but in doing so you can quickly customise many elements.

e.g

```<code>title: "Test"
author: "John"
date: "5 June 2017"
output:
  slidy_presentation:
    fig_width: 12.5
    font_adjustment: -1
    theme: readable
</code>```

Other themes may be found here Bootswatch.

edit: removed a typo

Body:
Have you tried using the built in Bootswatch themes? They're fairly limited, but in doing so you can quickly customise many elements.

e.g

title: "Test"
author: "John"
date: "5 June 2017"
output:
  slidy_presentation:
    fig_width: 12.5
    font_adjustment: -1
    theme: readable

Other themes may be found here Bootswatch.

edit: removed a typo


问:
Capturing the CheckChanged event in a ListView in an AlertDialog
I have a Xamarin Android App where I am trying to present a list of options with check boxes and getting unexpected results.  I am creating a lambda event handler in the GetView method of the Adapter.  I was hoping that by doing it this way, the current item in the current call to GetView would be the one referenced when the CheckedChanged Event is called.  My Code is:

```<code>[Activity(Label = "ListViewCheckBox", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    public class Item
    {
        public string Name { get; set; }
        public bool Checked { get; set; }
    }

    List<Item> Items;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        CreateItems();
    }

    private void CreateItems()
    {
        Items = new List<Item>();

        for (int i = 0; i < 30; i++)
        {
            Item Item = new Item();
            Item.Name = "Question " + i.ToString();
            Items.Add(Item);
        }
    }

    [Export("onButtonClicked")]
    public void onButtonClicked(View view)
    {
        switch (view.Id)
        {
            case Resource.Id.btnShowDialog:
                ShowDialog();
                break;
        }
    }

    private void ShowDialog()
    {
        AlertDialog dlgList = (new AlertDialog.Builder(this)).Create();
        dlgList.SetTitle("Questions");
        var viewAD = this.LayoutInflater.Inflate(Resource.Layout.DialogList, null);

        ListView lvItems = viewAD.FindViewById<ListView>(Resource.Id.lvDialog);

        QuestionAdapter adItems = new QuestionAdapter(Items, this);
        lvItems.Adapter = adItems;

        dlgList.SetView(viewAD);
        dlgList.SetButton("Close", delegate { });
        dlgList.Show();
    }

    public class QuestionAdapter : BaseAdapter
    {
        private Activity context;
        private List<Item> _Items;

        public QuestionAdapter(List<Item> Questions, Activity context)
        {
            this.context = context;
            _Items = Questions;
        }

        // How many items are in the data set represented by this Adapter.
        public override int Count
        {
            get { return _Items.Count; }
        }

        // Get the data item associated with the specified position in the data set.
        public override Java.Lang.Object GetItem(int position)
        {
            return position;
        }

        // Get the row id associated with the specified position in the list.
        public override long GetItemId(int position)
        {
            return position;
        }

        // Get a View that displays the data at the specified position in the data set.
        // You can either create a View manually or inflate it from an XML layout file.
        public override View GetView(int position, View convertView, ViewGroup parent)
        {

            Item Item = _Items[position];

            if (convertView == null)
            {
                convertView = context.LayoutInflater.Inflate(Resource.Layout.DialogCheckListItem, null);
            }

            TextView t = convertView.FindViewById<TextView>(Resource.Id.txtItem);
            t.Text = Item.Name;

            CheckBox c = convertView.FindViewById<CheckBox>(Resource.Id.chkItem);
            c.Checked = Item.Checked;
            c.CheckedChange += (s, e) =>
            {
                Item.Checked = e.IsChecked;
            };

            return convertView;
        }
    }
}
</code>```

If I pop up the Alert Dialog once and check a few boxes and close it.  The next time I pop it up, extra boxes are marked as checked.  What is the proper way to wire up the event in an Adapter so that when the event fires, it acts on the underlying Item that is representing?  Hopefully someone can look at this and quickly point out my error, if not, I have a working solution posted here where you can see the results. https://github.com/JimWilcox3/ListViewCheckBox

答:
When a listview recycles views, all listeners attached to it as well. So if the checkbox was checked and has a CheckedChange, both will remain a part of recycled view based on position. So i reset the chackedChange by adding c.SetOnCheckedChangeListener(null); This code below should work for you:

```<code> c.SetOnCheckedChangeListener(null);
            t.Text = Item.Name;
            c.Checked = Item.Checked;
            c.CheckedChange += (s, e) =>
            {
                CheckBox checkBox = (CheckBox)s;
                if (checkBox.Checked)
                    Item.Checked = true;
                else
                    Item.Checked = false;
            };
</code>```

Also try to avoid creating adapter again and again so always when you open up dialog another 30 items is added excpet if that si what you really want. And bug related to the first item too.

Body:
I have a Xamarin Android App where I am trying to present a list of options with check boxes and getting unexpected results.  I am creating a lambda event handler in the GetView method of the Adapter.  I was hoping that by doing it this way, the current item in the current call to GetView would be the one referenced when the CheckedChanged Event is called.  My Code is:

[Activity(Label = "ListViewCheckBox", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    public class Item
    {
        public string Name { get; set; }
        public bool Checked { get; set; }
    }

    List<Item> Items;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        CreateItems();
    }

    private void CreateItems()
    {
        Items = new List<Item>();

        for (int i = 0; i < 30; i++)
        {
            Item Item = new Item();
            Item.Name = "Question " + i.ToString();
            Items.Add(Item);
        }
    }

    [Export("onButtonClicked")]
    public void onButtonClicked(View view)
    {
        switch (view.Id)
        {
            case Resource.Id.btnShowDialog:
                ShowDialog();
                break;
        }
    }

    private void ShowDialog()
    {
        AlertDialog dlgList = (new AlertDialog.Builder(this)).Create();
        dlgList.SetTitle("Questions");
        var viewAD = this.LayoutInflater.Inflate(Resource.Layout.DialogList, null);

        ListView lvItems = viewAD.FindViewById<ListView>(Resource.Id.lvDialog);

        QuestionAdapter adItems = new QuestionAdapter(Items, this);
        lvItems.Adapter = adItems;

        dlgList.SetView(viewAD);
        dlgList.SetButton("Close", delegate { });
        dlgList.Show();
    }

    public class QuestionAdapter : BaseAdapter
    {
        private Activity context;
        private List<Item> _Items;

        public QuestionAdapter(List<Item> Questions, Activity context)
        {
            this.context = context;
            _Items = Questions;
        }

        // How many items are in the data set represented by this Adapter.
        public override int Count
        {
            get { return _Items.Count; }
        }

        // Get the data item associated with the specified position in the data set.
        public override Java.Lang.Object GetItem(int position)
        {
            return position;
        }

        // Get the row id associated with the specified position in the list.
        public override long GetItemId(int position)
        {
            return position;
        }

        // Get a View that displays the data at the specified position in the data set.
        // You can either create a View manually or inflate it from an XML layout file.
        public override View GetView(int position, View convertView, ViewGroup parent)
        {

            Item Item = _Items[position];

            if (convertView == null)
            {
                convertView = context.LayoutInflater.Inflate(Resource.Layout.DialogCheckListItem, null);
            }

            TextView t = convertView.FindViewById<TextView>(Resource.Id.txtItem);
            t.Text = Item.Name;

            CheckBox c = convertView.FindViewById<CheckBox>(Resource.Id.chkItem);
            c.Checked = Item.Checked;
            c.CheckedChange += (s, e) =>
            {
                Item.Checked = e.IsChecked;
            };

            return convertView;
        }
    }
}

If I pop up the Alert Dialog once and check a few boxes and close it.  The next time I pop it up, extra boxes are marked as checked.  What is the proper way to wire up the event in an Adapter so that when the event fires, it acts on the underlying Item that is representing?  Hopefully someone can look at this and quickly point out my error, if not, I have a working solution posted here where you can see the results. https://github.com/JimWilcox3/ListViewCheckBox

Body:
When a listview recycles views, all listeners attached to it as well. So if the checkbox was checked and has a CheckedChange, both will remain a part of recycled view based on position. So i reset the chackedChange by adding c.SetOnCheckedChangeListener(null); This code below should work for you:

 c.SetOnCheckedChangeListener(null);
            t.Text = Item.Name;
            c.Checked = Item.Checked;
            c.CheckedChange += (s, e) =>
            {
                CheckBox checkBox = (CheckBox)s;
                if (checkBox.Checked)
                    Item.Checked = true;
                else
                    Item.Checked = false;
            };

Also try to avoid creating adapter again and again so always when you open up dialog another 30 items is added excpet if that si what you really want. And bug related to the first item too.


问:
Order of calling constructors
```<code>class Program
{
    static void Main(string[] args)
    {
        Foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected static Func<string, int> CalcFunction;

    public static void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    static Foo()
    {
        CalcFunction = s => { return s.Length; };
    }
}
</code>```

When I try to call Foo.Calc("Foo"); I have exception "Object reference not set to an instance of an object."
because static constructor of Foo was not called and CalcFunction is null. I don't want to use Init method for Foo class and call it before calling Calc().

Can I change order of calling constructors?

答:
No - your code has been compiled into

```<code>Base.Calc("Foo");
</code>```

... so Foo isn't being initialized at all.

This isn't a matter of the order of static constructors being run... it's that the static constructor for Foo simply isn't being run at all.

Basically, you should change your design. You could force the static constructor of Foo to be run by creating an instance of Foo, but that's pretty nasty... your code won't end up being clear that way.

Title: Order of calling constructors

Body:
class Program
{
    static void Main(string[] args)
    {
        Foo.Calc("Foo");
    }
}

public abstract class Base
{
    protected static Func<string, int> CalcFunction;

    public static void Calc(string str)
    {
        Console.WriteLine(CalcFunction(str));
    }
}

public class Foo : Base
{
    static Foo()
    {
        CalcFunction = s => { return s.Length; };
    }
}

When I try to call Foo.Calc("Foo"); I have exception "Object reference not set to an instance of an object."
because static constructor of Foo was not called and CalcFunction is null. I don't want to use Init method for Foo class and call it before calling Calc().

Can I change order of calling constructors?

Body:
No - your code has been compiled into

Base.Calc("Foo");

... so Foo isn't being initialized at all.

This isn't a matter of the order of static constructors being run... it's that the static constructor for Foo simply isn't being run at all.

Basically, you should change your design. You could force the static constructor of Foo to be run by creating an instance of Foo, but that's pretty nasty... your code won't end up being clear that way.


问:
Multiple headers in HTML
I'm to code a webpage where a large header is at the top of the page. This header contains the navigation bar, the logo and the website title. Once the user starts scrolling, I'd like this to switch to a small header with just a navigation bar, which stays at the top of the page as the user scrolls. I couldn't find any way to do this online, and thought this might be interesting for me and other people.

This is the large, first header, with css code:

```<code>    <style>
    header {
    background-color: #0097A7;
    color: #ffffff;
    padding: 2%;
    text-align: center;
    }

    h1 {
    font-size: 270%;
    margin: 2% 0;
    }

    nav {
    background-color: rgba( 255, 255, 255, .4);
    border-radius: 25px;
    width: 50%;
    margin-left: auto;
    margin-right: auto;
    font-family: 'Neuton', serif;
    font-weight: bold;
    }

    nav a {
    color: #fff;
    display :inline-block;
    font-size: 100%;
    font-weight: bold;
    padding: 1% 4%;
    }

    nav a:hover {
    background-color: rgba( 255, 255, 255, .4);
    box-sizing: border-box;
    border-radius: 25px;
    }

    </style>

    <header>
      <h1><img alt="Logo" class="logo" height="50" src="media/logo.png">
      Fish & Chips </h1>
     <nav>
        <a href="index.php">Home</a>
        <a href="gallery.php">Gallery</a>
        <a href="about.php">About Us</a>
        <a href="contact.php">Contact Us</a>
      </nav>
    </header>
</code>```

This is the header I would like to switch to:

```<code>    <header>
     <nav>
        <a href="index.php">Home</a>
        <a href="gallery.php">Gallery</a>
        <a href="about.php">About Us</a>
        <a href="contact.php">Contact Us</a>
      </nav>
    </header>
</code>```

This is the code I found online to fix the header to the top of the screen

```<code>    <style>
    nav {
      position:fixed;
      top:0px;
    }
    </style>
</code>```

I am unsure how to switch between these two headers. I assume it may be simple jquery like :

```<code>    if (xPos > 0){
    switch to small, fixed header
    } else{
    switch to large header
    }
</code>```

Where xPos is how far down the page the user is.

However, I am unsure how to do this and can't find it online.

答: I think you are trying to implement something called a collapsing header. For starters: YouTube tutorial</p>

Title: Multiple headers in HTML

Body:
I'm to code a webpage where a large header is at the top of the page. This header contains the navigation bar, the logo and the website title. Once the user starts scrolling, I'd like this to switch to a small header with just a navigation bar, which stays at the top of the page as the user scrolls. I couldn't find any way to do this online, and thought this might be interesting for me and other people.

This is the large, first header, with css code:

      Fish & Chips

        Home
        Gallery
        About Us
        Contact Us

This is the header I would like to switch to:

        Home
        Gallery
        About Us
        Contact Us

This is the code I found online to fix the header to the top of the screen

I am unsure how to switch between these two headers. I assume it may be simple jquery like :

    if (xPos > 0){
    switch to small, fixed header
    } else{
    switch to large header
    }

Where xPos is how far down the page the user is.

However, I am unsure how to do this and can't find it online.


问:
Check if entry to panda dataframe is unique when index might be the same
I have a panda DataFrame that I want to add rows to. The Dataframe looks like this:

```<code>   col1  col2
a     1     5
b     2     6
c     3     7
</code>```

I want to add rows to the dataframe, but only if they are unique. The problem is that some new rows might have the same index, but different values in the columns. If this is the case, I somehow need to know.

Some example rows to be added and the desired result:

row 1:

```<code>   col1  col2
a     1     5
</code>```

desired row 1 result: Not added - it is already in the dataframe

row 2:

```<code>   col1  col2
a     9     9
</code>```

desired row 2 result: something like,

```<code>print('non-unique entries for index a')
</code>```

row 3:

```<code>   col1  col2
d     4     4
</code>```

desired row 3 result: just add the row to the dataframe.

答:
try this:</p>

```<code># existing dataframe == df
# new rows == df_newrows

# dividing newrows dataframe into two, one for repeated indexes, one without.

df_newrows_usable = df_newrows.loc[df_newrows.index.isin(list(df.index.get_values()))==False]
df_newrows_discarded = df_newrows.loc[df_newrows.index.isin(list(df.index.get_values()))]

print ('repeated indexes:', df_newrows_discarded)

# concat df and newrows without repeated indexes

new_df = pd.concat([df,df_newrows],0)

print ('new dataframe:', new_df)
</code>```

Body:
I have a panda DataFrame that I want to add rows to. The Dataframe looks like this:

   col1  col2
a     1     5
b     2     6
c     3     7

I want to add rows to the dataframe, but only if they are unique. The problem is that some new rows might have the same index, but different values in the columns. If this is the case, I somehow need to know.

Some example rows to be added and the desired result:

row 1:

   col1  col2
a     1     5

desired row 1 result: Not added - it is already in the dataframe

row 2:

   col1  col2
a     9     9

desired row 2 result: something like,

print('non-unique entries for index a')

row 3:

   col1  col2
d     4     4

desired row 3 result: just add the row to the dataframe.

Body:
try this:

# existing dataframe == df
# new rows == df_newrows

# dividing newrows dataframe into two, one for repeated indexes, one without.

df_newrows_usable = df_newrows.loc[df_newrows.index.isin(list(df.index.get_values()))==False]
df_newrows_discarded = df_newrows.loc[df_newrows.index.isin(list(df.index.get_values()))]

print ('repeated indexes:', df_newrows_discarded)

# concat df and newrows without repeated indexes

new_df = pd.concat([df,df_newrows],0)

print ('new dataframe:', new_df)


答:
You should change default module resolution strategy from Classic to Node. In order to do this, change your tsconfig.json file:

```<code>{
    ...
    "compilerOptions": {
        ....
        "moduleResolution": "node"
    }
}
</code>```

See documentation on Module Resolution

Title: can't resolve Cannot find module 'rxjs' within typescript/webpack

Body:
I've got a problem to load rxjs into a simple webpack setup (without angular). I'm running:

./node_modules/.bin/webpack --config webpack.config.js --watch

to start webpack. The only file with the app, src/app.ts, starts with:

import { Observable } from 'rxjs';

and this line is highlighted in VSCode and in webpack console with this error:

Cannot find module 'rxjs'.

But the overall output works fine. Just this console error.

tsconfig.json:

{
    "compilerOptions": {
         "target": "es2015"
    },
    "files": [
        "src/app.ts"
    ]
}

webpack.config.js:

module.exports = {
    entry: "./src/app.ts",
    output: {
        filename: "dist/bundle.js"
    },
    resolve: {
        // Add '.ts' and '.tsx' as a resolvable extension.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            { test: /\.ts?$/, loader: "ts-loader" }
        ]
    }
}

package.json (everything installed properly):

{
  "scripts": {
    "start": "./node_modules/.bin/webpack --config webpack.config.js --watch"
  },
  "devDependencies": {
    "ts-loader": "^2.1.0",
    "typescript": "^2.3.4",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "rxjs": "^5.4.0"
  }
}

I can't find the reason for why can't ts/webpack resolve where is rxjs

Body:
You should change default module resolution strategy from Classic to Node. In order to do this, change your tsconfig.json file:

{
    ...
    "compilerOptions": {
        ....
        "moduleResolution": "node"
    }
}

See documentation on Module Resolution


问:
Getting the date format in VBA in the correct form
I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.

I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.

File Name:
Submittals Wk Ending 06.02.17.xlsx

This is what I have so far

```<code>Dim wrbk As String
Dim weekdate As String

range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value

msgbox weekdate 'use to check what the date format is

wrbk = "Submittals Wk Ending " & weekdate

Windows(wrbk & ".xlsx").Activate
</code>```

When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.

I have the other workbook open as well when I try to run it.

Any ideas? Thanks!

答:
To get the previous Friday of any date, try below UDF. This should work fine if the Date NumberFormat is same as your System's Date format. The key is the CDate() which converts according to System's Date format which Office apps defaults to.

```<code>Option Explicit

Function GetLastFridayDate(AnyDate As Variant) As Date
    Dim dInput As Date, dLastFriday As Date
    dInput = CDate(AnyDate)
    dLastFriday = dInput - Weekday(dInput) + vbFriday - IIf(Weekday(dInput) > vbFriday, 0, 7)
    GetLastFridayDate = dLastFriday
End Function
</code>```

Body:
I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.

I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.

File Name:
Submittals Wk Ending 06.02.17.xlsx

This is what I have so far

Dim wrbk As String
Dim weekdate As String

range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value

msgbox weekdate 'use to check what the date format is

wrbk = "Submittals Wk Ending " & weekdate

Windows(wrbk & ".xlsx").Activate

When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.

I have the other workbook open as well when I try to run it.

Any ideas? Thanks!

Body:
To get the previous Friday of any date, try below UDF. This should work fine if the Date NumberFormat is same as your System's Date format. The key is the CDate() which converts according to System's Date format which Office apps defaults to.

Option Explicit

Function GetLastFridayDate(AnyDate As Variant) As Date
    Dim dInput As Date, dLastFriday As Date
    dInput = CDate(AnyDate)
    dLastFriday = dInput - Weekday(dInput) + vbFriday - IIf(Weekday(dInput) > vbFriday, 0, 7)
    GetLastFridayDate = dLastFriday
End Function


问:
This error keeps appearing in my code and I can't figure out how to fix it
I'm making an ios game app in Xcode 8 using swift 3 and I keep getting an error that says "Thread 1: EXC_BAD_INSTRUCTION (codeEXC_1386_INVOP, subcode=0x0)" and a console message that says fatal error: "Index out of range (lldb)". Does anyone know how to fix this?

Here's the section of code with the error. I get it on the line that says 'let nodeB = cableSegments[i]'

```<code>for i in 1..<length {
        let nodeA = cableSegments[i - 1]
        let nodeB = cableSegments[i]
        let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                            anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

        scene.physicsWorld.add(joint)
    }
</code>```

答:
The "out of range" error is common in many programming languages. It indicates to you that the loop is trying to access a position in the array that is out of the array range.

Per your code above it's not possible to figure out where are you obtaining the length value, but it should be the array length.

May the code below could work:

```<code>var counter = 0

for i in 0..<cableSegments.count {

    counter += 1

    if counter == cableSegments.count {
        break
    }

    let nodeA = cableSegments[i]
    let nodeB = cableSegments[i + 1]
    let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                        anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

    scene.physicsWorld.add(joint)
}
</code>```

Body:
I'm making an ios game app in Xcode 8 using swift 3 and I keep getting an error that says "Thread 1: EXC_BAD_INSTRUCTION (codeEXC_1386_INVOP, subcode=0x0)" and a console message that says fatal error: "Index out of range (lldb)". Does anyone know how to fix this?

Here's the section of code with the error. I get it on the line that says 'let nodeB = cableSegments[i]'

for i in 1..<length {
        let nodeA = cableSegments[i - 1]
        let nodeB = cableSegments[i]
        let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                            anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

        scene.physicsWorld.add(joint)
    }

Body:
The "out of range" error is common in many programming languages. It indicates to you that the loop is trying to access a position in the array that is out of the array range.

Per your code above it's not possible to figure out where are you obtaining the length value, but it should be the array length.

May the code below could work:

var counter = 0

for i in 0..<cableSegments.count {

    counter += 1

    if counter == cableSegments.count {
        break
    }

    let nodeA = cableSegments[i]
    let nodeB = cableSegments[i + 1]
    let joint = SKPhysicsJointPin.joint(withBodyA: nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
                                        anchor: CGPoint(x: nodeA.frame.midX, y: nodeA.frame.minY))

    scene.physicsWorld.add(joint)
}


答:
C# guarantees that, before any code in Base is used, the static constructor for Base is run. There's nothing to guarantee that any code in Foo will run. (You've written a call to Foo.Calc, but this is really a call to Base.Calc.)

There's no simple fix: you could introduce an explicit init method, or flatten the class hierarchy, or move CalcFunction into Foo.

Title: Order of calling constructors


问:
Restore file from HDFS after namenode delete
My namenode server was hacked this weekend and /usr/local/hadoop directory no longer exists. Is it still possible to recover a file that is stored on HDFS? Datanodes are accessible and each contains somewhere in the hierarchy blk_{...} data.</p>

答:
If you don't have any copy/backup of the name dir, recovering the data will be quite a difficult task. The datanodes are not aware of any concept of a file, only blocks. All of the data exists in those blocks but you would have to manually reconstruct files from their blocks. If you have some specific files of very high importance and not that much data overall you may be able to sift through the blocks to find what you're looking for but I'm not aware of anything better than that.

This is why there are a number of ways to redundantly store multiple copies of the namespace, e.g. by specifying multiple directories in the dfs.namenode.name.dir property, and using either a Secondary or a Standby Namenode (see https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsUserGuide.html#Secondary_NameNode), which act as a remote location storing a copy of the namespace.


问:
How to Display Data in a single view from Multiple Tables in MVC using Entity framework
I want to display the the password and user name in the user view
could any one help me?  I created a Userand LogIn table as shown below. How do I display properties from both the User and LogIn table in my Razor view.

Models

```<code>public class User
{
    [Key]
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Mobile { get; set; }
    public string JobTittle { get; set; }
    public string Email { get; set; }
}

public class LogIn
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int LoginID { get; set; }
    [Required(ErrorMessage = "Required.")]
    public string UserName { get; set; }
    public string Password { get; set; }

    public  User User { get; set; }
}
</code>```

Controller

```<code>public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Index()
    {
        return View();
    }
}
</code>```

View

```<code>@model Coding.Models.User

@{
    ViewBag.Title = "Create";
}

<h2>Sign Up</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

答:
The proper way to do this is to create a viewmodel that includes both the User and LogIn objects.  But the quick and dirty method is to just use ViewBags.

```<code>public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Create()
    {
        ViewBag.User = db.Users.FirstOrDefault(x => x.UserID == someId);
        ViewBag.LogIn = db.LogIns.FirstOrDefault(x => x.LoginID == someId);

        return View();
    }
}
</code>```

You can then use those ViewBags in your view

```<code><div>
    ViewBag.User.UserID
    ViewBag.LogIn.LoginID
</div>
</code>```

I would advise you to never store passwords in plain text.  They should be salted and hashed and never displayed.  In addition, I do not know why you would go and create your own LogIn table.  You should look into Microsoft Identity.

Body:
I want to display the the password and user name in the user view
could any one help me?  I created a Userand LogIn table as shown below. How do I display properties from both the User and LogIn table in my Razor view.

Models

public class User
{
    [Key]
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Mobile { get; set; }
    public string JobTittle { get; set; }
    public string Email { get; set; }
}

public class LogIn
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int LoginID { get; set; }
    [Required(ErrorMessage = "Required.")]
    public string UserName { get; set; }
    public string Password { get; set; }

    public  User User { get; set; }
}

Controller

public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Index()
    {
        return View();
    }
}

View

@model Coding.Models.User

@{
    ViewBag.Title = "Create";
}

Sign Up

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Body:
The proper way to do this is to create a viewmodel that includes both the User and LogIn objects.  But the quick and dirty method is to just use ViewBags.

public class UsersController : Controller
{
    private CodingContext db = new CodingContext();

    // GET: Users
    public ActionResult Create()
    {
        ViewBag.User = db.Users.FirstOrDefault(x => x.UserID == someId);
        ViewBag.LogIn = db.LogIns.FirstOrDefault(x => x.LoginID == someId);

        return View();
    }
}

You can then use those ViewBags in your view

<div>
    ViewBag.User.UserID
    ViewBag.LogIn.LoginID
</div>

I would advise you to never store passwords in plain text.  They should be salted and hashed and never displayed.  In addition, I do not know why you would go and create your own LogIn table.  You should look into Microsoft Identity.


问:
How to get headers element in node js
I would like to get headers element in server side with node js I try these two codes in client side:

CODE 1

```<code> var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ayI6IjU5Mjg0YjQ0MzNhNjU2MmRlNDI1ZGU5MCIsImlhdCI6MTQ5NjY5NjA1NiwiZXhwIjoyOTkzMzk1NzEyfQ.BQskPVT-h-Io4p3Hqraq2qRmVlp_pWAEw5rnIIEA4vk';
    $.ajax({
        url: 'YourRestEndPoint',
        headers: {
            'Authorization':'Basic' + token
        },
        method: 'POST',
        dataType: 'json',
        data: YourData,
        success: function(data){
          console.log('succes: '+data);
        }
      });
</code>```

Code 2:

```<code>$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader(
          'Authorization':'Basic' + token);
         },
         success: function() { alert('Success!' + authHeader); }
});
</code>```

And here the code server:

```<code>res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");

console.log(req.headers['authorization']);
</code>```

I can't get the token in the server side.

答:
In Code 1, you have 'Authorization' as the property name in your header. However, in your code, you console.log 'authorization'.

Try the same capitalization of both. Let me know if the capital was an error with copying and pasting.

Title: How to get headers element in node js

Body:
I would like to get headers element in server side with node js I try these two codes in client side:

CODE 1

 var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ayI6IjU5Mjg0YjQ0MzNhNjU2MmRlNDI1ZGU5MCIsImlhdCI6MTQ5NjY5NjA1NiwiZXhwIjoyOTkzMzk1NzEyfQ.BQskPVT-h-Io4p3Hqraq2qRmVlp_pWAEw5rnIIEA4vk';
    $.ajax({
        url: 'YourRestEndPoint',
        headers: {
            'Authorization':'Basic' + token
        },
        method: 'POST',
        dataType: 'json',
        data: YourData,
        success: function(data){
          console.log('succes: '+data);
        }
      });

Code 2:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader(
          'Authorization':'Basic' + token);
         },
         success: function() { alert('Success!' + authHeader); }
});

And here the code server:

res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");

console.log(req.headers['authorization']);

I can't get the token in the server side.


问:
Force python axis to show specific numbers
I have a python plot, using the following code:

```<code>fig = plt.figure()
ax = plt.add_subplot(111)
ax.imshow(an_image)
</code>```

What I want to do, is simply force the x and y axes, to span a certain minimum and maximum number. (Cannot do this with ax.set_xlim() or ax.set_ylim() because those actually change the axis limits). I just want some particular x_min , x_max , y_min, and y_max numbers to show up on my image.

How do I do that?

EDIT: To further clarify what I mean, look at this image below. What I want, are the numbers on the axes written in red. I want them to replace what is already there in black.  How do I accomplish that?

Thanks

答:
You can specifically set tick locations with:

```<code>ax.set_xticks([0, 200])
ax.set_yticks([0, 100])

ax.set_xticklabels(['-30', '+100'])
ax.set_yticklabels(['+20', '-20'])
</code>```

Alternatively, you could change the origin to lower with imshow and you wouldn't have to flip the yticklabels.

Body:
I have a python plot, using the following code:

fig = plt.figure()
ax = plt.add_subplot(111)
ax.imshow(an_image)

What I want to do, is simply force the x and y axes, to span a certain minimum and maximum number. (Cannot do this with ax.set_xlim() or ax.set_ylim() because those actually change the axis limits). I just want some particular x_min , x_max , y_min, and y_max numbers to show up on my image.

How do I do that?

EDIT: To further clarify what I mean, look at this image below. What I want, are the numbers on the axes written in red. I want them to replace what is already there in black.  How do I accomplish that?

Thanks

Body:
You can specifically set tick locations with:

ax.set_xticks([0, 200])
ax.set_yticks([0, 100])

ax.set_xticklabels(['-30', '+100'])
ax.set_yticklabels(['+20', '-20'])

Alternatively, you could change the origin to lower with imshow and you wouldn't have to flip the yticklabels.


问:
I cannot figure out why my variable is out of range
I am getting an error in my python code. This is the code

```<code>binary=[]
bits=int(input("How many bits do you want to have?   >>"))
numOfCombos=2**bits
lenOfPart=numOfCombos/2
x=0
y=0
z=0
while x!=numOfCombos:
    binary.insert(x,[])
    x+=1
x=0
while x!=lenOfPart:
    binary[x].insert(0,"0")
    x+=1
while x!=lenOfPart*2:
    binary[x].insert(0,"1")
    x+=1
x=0
p=0
while x!=bits:
    lenOfPart=lenOfPart/2
    while z!=len(binary)-1:
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"0")
            y+=1
            p+=1
        p=0
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"1")
            y+=1
            p+=1
        p=0
        z+=1
    y=0
    x+=1

print(numOfCombos)
print(len(binary))
print(binary)
</code>```

I am getting an error that reads

```<code>How many bits do you want to have?   >>3
Traceback (most recent call last):
  File "C:/Users/#####/AppData/Local/Programs/Python/Python36-32/binarygen.py", line 24, in <module>
    binary[y].insert(len(binary[y]),"0")
IndexError: list index out of range
</code>```

I do not understand why my variables are not working. I have tested all the things I can think of. If you have any advice, please respond as soon as possible. If you think that the entire program is wrong, please insert a working version into your answer. The purpose of the program is to generate all the possible binary combinations for a given number of bits. Thank you for your time and help.

答:
You have an "off by one" error in that loop.  You're trying to add a character to the end of the final element of binary (I think).  However, for an input of 3, you use subscript 8 (2**3).  Binary has elements 0-7; subscript 8 is out of bounds.  Perhaps you need

```<code>        binary[y].insert(len(binary[y])-1,"0")
</code>```

However, I note that you always insert at the end of the list.  Why not simply use append?

```<code>        binary[y].append("0")
</code>```

Better yet, instead of having lists of characters, make each a string:

```<code>        binary[y] += "0"
</code>```

Also, please note replication capabilities in Python; you don't need those tedious while loops: just add as many 1s or 0s as you need.  Something like:

```<code>    binary += "0" * (lenOfPart" - p)
</code>```

You can simplify this a lot, once you learn some of the language facilities.

Most of all, figure out at the upper levels what you really need to accomplish.  Tell us; you can simplyfy both the problem and the solution.  For instance, as Delirious Lettuce showed, you can cut through a lot of grief by searching first for built-in capabilities in the itertools package.

Body:
I am getting an error in my python code. This is the code

binary=[]
bits=int(input("How many bits do you want to have?   >>"))
numOfCombos=2**bits
lenOfPart=numOfCombos/2
x=0
y=0
z=0
while x!=numOfCombos:
    binary.insert(x,[])
    x+=1
x=0
while x!=lenOfPart:
    binary[x].insert(0,"0")
    x+=1
while x!=lenOfPart*2:
    binary[x].insert(0,"1")
    x+=1
x=0
p=0
while x!=bits:
    lenOfPart=lenOfPart/2
    while z!=len(binary)-1:
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"0")
            y+=1
            p+=1
        p=0
        while p!=lenOfPart:
            binary[y].insert(len(binary[y]),"1")
            y+=1
            p+=1
        p=0
        z+=1
    y=0
    x+=1

print(numOfCombos)
print(len(binary))
print(binary)

I am getting an error that reads

How many bits do you want to have?   >>3
Traceback (most recent call last):
  File "C:/Users/#####/AppData/Local/Programs/Python/Python36-32/binarygen.py", line 24, in <module>
    binary[y].insert(len(binary[y]),"0")
IndexError: list index out of range

I do not understand why my variables are not working. I have tested all the things I can think of. If you have any advice, please respond as soon as possible. If you think that the entire program is wrong, please insert a working version into your answer. The purpose of the program is to generate all the possible binary combinations for a given number of bits. Thank you for your time and help.

Body:
You have an "off by one" error in that loop.  You're trying to add a character to the end of the final element of binary (I think).  However, for an input of 3, you use subscript 8 (2**3).  Binary has elements 0-7; subscript 8 is out of bounds.  Perhaps you need

        binary[y].insert(len(binary[y])-1,"0")

However, I note that you always insert at the end of the list.  Why not simply use append?

        binary[y].append("0")

Better yet, instead of having lists of characters, make each a string:

        binary[y] += "0"

Also, please note replication capabilities in Python; you don't need those tedious while loops: just add as many 1s or 0s as you need.  Something like:

    binary += "0" * (lenOfPart" - p)

You can simplify this a lot, once you learn some of the language facilities.

Most of all, figure out at the upper levels what you really need to accomplish.  Tell us; you can simplyfy both the problem and the solution.  For instance, as Delirious Lettuce showed, you can cut through a lot of grief by searching first for built-in capabilities in the itertools package.


问:
How to use a OxyPlot Bar Chart inside a listview control for Xamarin.Forms IOS?
I have a ListView with a binding template. And I have a list of PlotModels which I am using to bind to the list view.
And my PlotView is inside the template where I am binding the PlotModel to the PlotView.

Everything is running smooth in Android. But the problem is I am getting a error "PlotModel is already in use by some other PlotView control.".
when I am trying to run it on IOS.

//My content page

```<code>public MyConstructor()
{
List<MyChart> charts = new List<MyChart>();
charts.Add(new MyChart { PlotModel = PlotModel1 });
charts.Add(new MyChart { PlotModel = PlotModel2 });
charts.Add(new MyChart { PlotModel = PlotModel3 });
charts.Add(new MyChart { PlotModel = PlotModel4 });
ListView lvPlots = new ListView(ListViewCachingStrategy.RetainElement)
{
ItemsSource = charts,
ItemTemplate = new DataTemplate(typeof(NewDashboardSubCell)),
HasUnevenRows = true
};
Content = lvPlots;
}
public class MyChart
{
       public MyPlotModel PlotModel { get; set; }
}
</code>```

//My View Cell

```<code>public class NewDashboardSubCell : ViewCell
{
        PlotView plotView;
        public NewDashboardSubCell()
        {
            try
            {
                plotView = new PlotView
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    IsVisible = true,
                    IsEnabled = true,
                    HeightRequest = App.ScreenHeight - 100,
                    WidthRequest = App.ScreenWidth - 40
                };
                plotView.SetBinding(PlotView.ModelProperty, "PlotModel");
                View = plotView;
            }
            catch (Exception ex)
            {
            }
        }
}
</code>```

Any suggestions?

答: A PlotModel cannot be used in more than one view. Create model for each item in the array an not just a view. But if it works on Android you might just need to clean install the app to get the changes if you already fix the issue.</p>

Body:
I have a ListView with a binding template. And I have a list of PlotModels which I am using to bind to the list view.
And my PlotView is inside the template where I am binding the PlotModel to the PlotView.

Everything is running smooth in Android. But the problem is I am getting a error "PlotModel is already in use by some other PlotView control.".
when I am trying to run it on IOS.

//My content page

public MyConstructor()
{
List<MyChart> charts = new List<MyChart>();
charts.Add(new MyChart { PlotModel = PlotModel1 });
charts.Add(new MyChart { PlotModel = PlotModel2 });
charts.Add(new MyChart { PlotModel = PlotModel3 });
charts.Add(new MyChart { PlotModel = PlotModel4 });
ListView lvPlots = new ListView(ListViewCachingStrategy.RetainElement)
{
ItemsSource = charts,
ItemTemplate = new DataTemplate(typeof(NewDashboardSubCell)),
HasUnevenRows = true
};
Content = lvPlots;
}
public class MyChart
{
       public MyPlotModel PlotModel { get; set; }
}

//My View Cell

public class NewDashboardSubCell : ViewCell
{
        PlotView plotView;
        public NewDashboardSubCell()
        {
            try
            {
                plotView = new PlotView
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    IsVisible = true,
                    IsEnabled = true,
                    HeightRequest = App.ScreenHeight - 100,
                    WidthRequest = App.ScreenWidth - 40
                };
                plotView.SetBinding(PlotView.ModelProperty, "PlotModel");
                View = plotView;
            }
            catch (Exception ex)
            {
            }
        }
}

Any suggestions?