问:
RCTBridge is Always Nil
I have been using React Native for a mobile app project for over a year now. I have a native component to bridge the BLE stack to the React Native portion of the app. Recently I upgraded to version 9.1 of XCode and I cannot get the React-Native Bridge to work within the iOS version. The RCTBridge is always nil so I can never use the eventDispatcher(). Here is my setup:

I have a native Swift component which I integrate into the app via a bridgin header. The origanization looks like this:

```<code>BLEScanner.swift (This is the native component)
BluetoothModuleBridge.m
Module-Practive-Bridging-Header.h (The bridging header)
</code>```

Relevant code snippets from each file:

BLEScanner.swift

```<code>import Foundation

@objc(BLEScanner)
class BLEScanner: NSObject {

  //....

  var bridge: RCTBridge!  // THIS IS ALWAYS NIL

  //....

  @objc func requestBluetoothState() -> Void {
    print("REQUEST BLE STATE")
    let ret = [
      "enabled" : true
    ]

    //THIS LINE WILL FAIL BECAUSE bridge IS NIL
    self.bridge.eventDispatcher().sendDeviceEvent(withName: "BluetoothStateEvent", body: ret)
  }

}
</code>```

BluetoothModuleBridge.m

```<code>#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(BLEScanner, NSObject)

RCT_EXTERN_METHOD(requestBluetoothState)

@end
</code>```

Module-Practive-Bridging-Header.h

```<code>// BluetoothModule-Bridging-Header.h
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>

#import <React/RCTRootView.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>

#import "AppDelegate.h"
#import "BugsnagReactNative/BugsnagReactNative.h"

#import "nokeLockSDK.h"
#import "nokeServerSDK.h"
#import "TI_aes_128.h"
</code>```

What I have Tried

Updated React Native from 0.36 to 0.50.3

Tried running on multiple devices

Tried on older version of XCode

Tried compiling on different machine

Compared to a similar app that works and uses this same design.

I am very confused as to why the RCTBridge is returning as nil. It seems odd to me that an XCode update would cause this, however, it is the only change made.

Can anyone point me in the right direction in debugging this issue?

I am using XCode 9.1 and React Native 0.50.3

答:
Do you have your own initial method? If so try remove it. After my test, it has no problem.

And it is recommended to Subclass RCTEventEmitter instead.

Title: RCTBridge is Always Nil

Body:
I have been using React Native for a mobile app project for over a year now. I have a native component to bridge the BLE stack to the React Native portion of the app. Recently I upgraded to version 9.1 of XCode and I cannot get the React-Native Bridge to work within the iOS version. The RCTBridge is always nil so I can never use the eventDispatcher(). Here is my setup:

I have a native Swift component which I integrate into the app via a bridgin header. The origanization looks like this:

BLEScanner.swift (This is the native component)
BluetoothModuleBridge.m
Module-Practive-Bridging-Header.h (The bridging header)

Relevant code snippets from each file:

BLEScanner.swift

import Foundation

@objc(BLEScanner)
class BLEScanner: NSObject {

  //....

  var bridge: RCTBridge!  // THIS IS ALWAYS NIL

  //....

  @objc func requestBluetoothState() -> Void {
    print("REQUEST BLE STATE")
    let ret = [
      "enabled" : true
    ]

    //THIS LINE WILL FAIL BECAUSE bridge IS NIL
    self.bridge.eventDispatcher().sendDeviceEvent(withName: "BluetoothStateEvent", body: ret)
  }

}

BluetoothModuleBridge.m

#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(BLEScanner, NSObject)

RCT_EXTERN_METHOD(requestBluetoothState)

@end

Module-Practive-Bridging-Header.h

// BluetoothModule-Bridging-Header.h
#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>

#import <React/RCTRootView.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>

#import "AppDelegate.h"
#import "BugsnagReactNative/BugsnagReactNative.h"

#import "nokeLockSDK.h"
#import "nokeServerSDK.h"
#import "TI_aes_128.h"

What I have Tried

Updated React Native from 0.36 to 0.50.3

Tried running on multiple devices

Tried on older version of XCode

Tried compiling on different machine

Compared to a similar app that works and uses this same design.

I am very confused as to why the RCTBridge is returning as nil. It seems odd to me that an XCode update would cause this, however, it is the only change made.

Can anyone point me in the right direction in debugging this issue?

I am using XCode 9.1 and React Native 0.50.3


来源: stackexchange

问:
Why won't my function return largest even if numbers are negative
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.</p>

```<code>def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large
</code>```

答:
The code is working fine. I suppose you want to print the largest even number, even if it is negative. In that case you should use abs() function.
And also you are using for loop two times which I suppose is of no use. Below is the code, which works for given largest even number even if it is negative.

```<code>def largest_even(list_int):
    large = 0
    print(list_int)
    for i in list_int:
        if i % 2 == 0:
            if abs(i) > abs(large):
                large = i
    return large

print(largest_even([1,2,3,1,5,-10]))
</code>```

Output:

```<code>[1, 2, 3, 1, 5, -10]
-10
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.

def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large

Body:
The code is working fine. I suppose you want to print the largest even number, even if it is negative. In that case you should use abs() function.
And also you are using for loop two times which I suppose is of no use. Below is the code, which works for given largest even number even if it is negative.

def largest_even(list_int):
    large = 0
    print(list_int)
    for i in list_int:
        if i % 2 == 0:
            if abs(i) > abs(large):
                large = i
    return large

print(largest_even([1,2,3,1,5,-10]))

Output:

[1, 2, 3, 1, 5, -10]
-10


问:
How to disallow implicit any?
I am using TSLint with "no-any": true, "no-unsafe-any": true. It disallow:

```<code>let foo: any;
</code>```

However it still allows:

```<code>let foo;
</code>```

How to turn on the rule for implicit any?

答:
As of now there is no option in tslint to achieve that.
You could use the typescript compiler option "noImplicitAny": true, which can be configured using tsconfig.json.

Reference : https://www.typescriptlang.org/docs/handbook/compiler-options.html

Title: How to disallow implicit any?

Body:
I am using TSLint with "no-any": true, "no-unsafe-any": true. It disallow:

let foo: any;

However it still allows:

let foo;

How to turn on the rule for implicit any?


问:
Passing JSON over .ajax() with jQuery
I'm having trouble understanding how to create a jQuery .ajax function to post data (multiple variables) to my php page, then return the information from the PHP page.

```<code>$('#RoomCode').change(function()
{
    //alert($(this).attr('value'));
    var RoomCode = $(this).attr('value');

    //Create JSON Object to send to Ajaxdo
    var toAjax = { "GetRoomCodeParams": [ { "GetRoomCode" : "1", "RoomCode" : RoomCode } ]};
    alert(toAjax);
    $.ajax({
        url: "ajaxdo.php",
        type: "POST",
        dataType: json,
        cache: false,
        data toAjax,
        success: function (response) {

            alert(response);
            $('#RoomInfoCode', '#RoomClassCode').fadeOut();
            $('#RoomInfoCode').empty();
            $('#RoomInfoCode').fadeIn();

        }
    });

});
</code>```

EDIT: Thanks for pointing out the missing colon : (now appended to code)

now i receive missing }  after property list success: (response) {}

i have since cleared ammended success to the following, and still receive this error:

```<code>success: function (response) { }
</code>```

答:
You've missed out a colon, try

```<code>data:toAjax,
</code>```

rather than

```<code>data toAjax,
</code>```

ContentLicense: CC BY-SA 2.5

Title: Passing JSON over .ajax() with jQuery

Body:
I'm having trouble understanding how to create a jQuery .ajax function to post data (multiple variables) to my php page, then return the information from the PHP page.

$('#RoomCode').change(function()
{
    //alert($(this).attr('value'));
    var RoomCode = $(this).attr('value');

    //Create JSON Object to send to Ajaxdo
    var toAjax = { "GetRoomCodeParams": [ { "GetRoomCode" : "1", "RoomCode" : RoomCode } ]};
    alert(toAjax);
    $.ajax({
        url: "ajaxdo.php",
        type: "POST",
        dataType: json,
        cache: false,
        data toAjax,
        success: function (response) {

            alert(response);
            $('#RoomInfoCode', '#RoomClassCode').fadeOut();
            $('#RoomInfoCode').empty();
            $('#RoomInfoCode').fadeIn();

        }
    });

});

EDIT: Thanks for pointing out the missing colon : (now appended to code)

now i receive missing }  after property list success: (response) {}

i have since cleared ammended success to the following, and still receive this error:

success: function (response) { }

Body:
You've missed out a colon, try

data:toAjax,

rather than

data toAjax,


问:
JavaScript dynamic code to self execute function
I have a problem, but I can't solve it......

There is a function on the other website, so I can't modify it

The code is

And I want to add a protoype "aaa" to get i(5) return value

how can I do it?

```<code>(function () {
    function i(a) {
        return a + 1; //complex calculate...
    }

    window.Util = {
        n: i(1),
        windowUtil: i(2),
        Hub: i(3)
    };
})

eval("window.Util.aaa =  i(5) ");
</code>```

But it error

"Uncaught ReferenceError: I is not defined".....

答:
There are a couple of issues here

function expression is defined but not invoked

i is not exposed to global scope for eval to work.

Demo

(function () {
    window.i = function i(a) {
        return a + 1; //complex calculate...
    }

    window.Util = {
        n: i(1),
        windowUtil: i(2),
        Hub: i(3)
    };
})();

console.log(eval("window.Util.aaa =  i(5) "));```

Body:
I have a problem, but I can't solve it......

There is a function on the other website, so I can't modify it

The code is

And I want to add a protoype "aaa" to get i(5) return value

how can I do it?

(function () {
    function i(a) {
        return a + 1; //complex calculate...
    }

    window.Util = {
        n: i(1),
        windowUtil: i(2),
        Hub: i(3)
    };
})

eval("window.Util.aaa =  i(5) ");

But it error

"Uncaught ReferenceError: I is not defined".....


问:
unable to open div box as layer using z-index
I am trying to open action div box as layer in but unable to do that.

when i click on action button div box will open within that  only. it should be open as layer.

Code:

ul {
  z-index: 2
}

table {
  z-index: 1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
  <thead>
    <tr>
      <th>Sr.No</th>
      <th>LeadCreated DateTime</th>
      <th>RetailerName</th>
      <th>ShopName</th>
      <th>Mobile</th>
      <th>Address</th>
      <th>City</th>
      <th>Pincode</th>
      <th>Status</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr class="odd gradeX">
      <td>1</td>
      <td>10-10-2017</td>
      <td>Test</td>
      <td>Test</td>
      <td>9904773479</td>
      <td>Surat</td>
      <td>Surat</td>
      <td>304230</td>
      <td style="background: <?php if ($row->Status == 'InProcess') echo 'green';if ($row->Status == 'Closed') echo 'orange';if ($row->Status == 'Dead') echo 'black'; ?>;color: #FFFFFF">
        <?= $row->Status ?>
      </td>
      <td class="pbutton">
        <div class="btn-group">
          <!-- Button trigger modal -->
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                                                Action <span class="caret"></span>
                                                            </button>
          <ul class="dropdown-menu pull-right " role="menu" style="position: relative;width: 160px;z-index: 99">
            <li>LeadId ?>" data-toggle="modal" data-target="#viewleadmodal"><span class="glyphicon glyphicon-fullscreen"></span> View</li>
            <li><span class="fa fa-edit"></span> Add Lead Update</li>
            <li><span class="fa fa-edit"></span> Edit</li>
            <li><span class="glyphicon glyphicon-trash"></span> Delete</li>
          </ul>
        </div>
      </td>
    </tr>

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

答:
Try this

```<code>ul.dropdown-menu{
  position:absolute !important;
}
</code>```

or use inline styles

```<code><ul class="dropdown-menu pull-right " role="menu" style="position: absolute;width: 160px;z-index: 99">
</code>```

Body:
I am trying to open action div box as layer in but unable to do that.

when i click on action button div box will open within that  only. it should be open as layer.

Code:

ul {
  z-index: 2
}

table {
  z-index: 1
}

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Sr.No
      LeadCreated DateTime
      RetailerName
      ShopName
      Mobile
      Address
      City
      Pincode
      Status
      Action

      1
      10-10-2017
      Test
      Test
      9904773479
      Surat
      Surat
      304230
      <td style="background: <?php if ($row->Status == 'InProcess') echo 'green';if ($row->Status == 'Closed') echo 'orange';if ($row->Status == 'Dead') echo 'black'; ?>;color: #FFFFFF">
        <?= $row->Status ?>

          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                                                Action
                                                            </button>

<a href="#viewleadmodal" data-id="<?= $row->LeadId ?>" data-toggle="modal" data-target="#viewleadmodal"> View

 Add Lead Update

 Edit

 Delete

Body:
Try this

ul.dropdown-menu{
  position:absolute !important;
}

or use inline styles

<ul class="dropdown-menu pull-right " role="menu" style="position: absolute;width: 160px;z-index: 99">


问:
Enable VT-x in your BIOS security settings (refer to documentation for your computer)
While I was adding a virtual device in my Android Studio, Android Studio is Showing This Error. See This Image:

.

答:
Intel HAXM is required to run this AVD.
VT-x is disabled in BIOS.

Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio
I dont no how to do Bios Security


问:
MySQL Triggers that updates a table based on inserted and stored values
I have to create a trigger in a table proyect, to check if all the tests for the proyect are 'ready'. If all of them are ready, I need to search the proyect and put the status of the proyect as 'ready'. If not, Incomplete.

I'm aware that I need to create one trigger for the UPDATE, and another one for the INSERT. I've planned something like this, But I can not make it work.

I created this solution, if the total number of test for that proyect, is below to the number of test ready for that proyect, then the proyect is not ready. and if both are equals, the proyect is ready.

I don't know why it doesn't work:

```<code>CREATE TRIGGER update-proyect
AFTER INSERT ON tests
FOR EACH ROW

SET @total = select COUNT(*)
              from tests
            where IdProyect= NEW.IdProyect;

SET @ready = select COUNT(*)
            from prueba
            from tests
            where IdProyect= NEW.IdProyect
            AND status = 'ready';

IF (@total == @ready)
   UPDATE proyect SET status = 'Ready' WHERE IdProyect = NEW.IdProyect;
ELSE
   UPDATE proyect SET status = 'Incomplete' WHERE IdProyect = NEW.IdProyect;
END IF;
</code>```

答:
Loads of errors update-proyect is an invalid trigger name change to update_proyect, If you have more than 1 statement in a trigger they have to be encased in a begin and end statements, a select after a set has to be encased in braces, there is no == comparison relation operator in mysql either use = or null safe equals <=>,  an if statement has to have a then statement.
This at least syntaxes.</p>

```<code>DROP TRIGGER IF EXISTS update_proyect;
DELIMITER $$

CREATE TRIGGER update_proyect
AFTER INSERT ON tests
FOR EACH ROW
BEGIN
SET @total = (select COUNT(*)
              from tests
            where IdProyect= NEW.IdProyect
                );

SET @ready = (select COUNT(*)
            from prueba
            #from tests
            where IdProyect= NEW.IdProyect
            AND status = 'ready'
            );

IF (@total = @ready) THEN
   UPDATE proyect SET status = 'Ready' WHERE IdProyect = NEW.IdProyect;
ELSE
   UPDATE proyect SET status = 'Incomplete' WHERE IdProyect = NEW.IdProyect;
END IF;

END $$

DELIMITER ;
</code>```

Body:
I have to create a trigger in a table proyect, to check if all the tests for the proyect are 'ready'. If all of them are ready, I need to search the proyect and put the status of the proyect as 'ready'. If not, Incomplete.

I'm aware that I need to create one trigger for the UPDATE, and another one for the INSERT. I've planned something like this, But I can not make it work.

I created this solution, if the total number of test for that proyect, is below to the number of test ready for that proyect, then the proyect is not ready. and if both are equals, the proyect is ready.

I don't know why it doesn't work:

CREATE TRIGGER update-proyect
AFTER INSERT ON tests
FOR EACH ROW

SET @total = select COUNT(*)
              from tests
            where IdProyect= NEW.IdProyect;

SET @ready = select COUNT(*)
            from prueba
            from tests
            where IdProyect= NEW.IdProyect
            AND status = 'ready';

IF (@total == @ready)
   UPDATE proyect SET status = 'Ready' WHERE IdProyect = NEW.IdProyect;
ELSE
   UPDATE proyect SET status = 'Incomplete' WHERE IdProyect = NEW.IdProyect;
END IF;

Body:
Loads of errors update-proyect is an invalid trigger name change to update_proyect, If you have more than 1 statement in a trigger they have to be encased in a begin and end statements, a select after a set has to be encased in braces, there is no == comparison relation operator in mysql either use = or null safe equals <=>,  an if statement has to have a then statement.
This at least syntaxes.

DROP TRIGGER IF EXISTS update_proyect;
DELIMITER $$

CREATE TRIGGER update_proyect
AFTER INSERT ON tests
FOR EACH ROW
BEGIN
SET @total = (select COUNT(*)
              from tests
            where IdProyect= NEW.IdProyect
                );

SET @ready = (select COUNT(*)
            from prueba
            #from tests
            where IdProyect= NEW.IdProyect
            AND status = 'ready'
            );

IF (@total = @ready) THEN
   UPDATE proyect SET status = 'Ready' WHERE IdProyect = NEW.IdProyect;
ELSE
   UPDATE proyect SET status = 'Incomplete' WHERE IdProyect = NEW.IdProyect;
END IF;

END $$

DELIMITER ;


问:
Prevent jQuery automaticly redirecting after AJAX call
I have an ajax call that loads a div into a popup, but when I click on button, the trigger happens, the div gets loaded then the entire page gets reloaded. I just wanted to know how could I find this second function that is reloading my entire page and add the exception, so that on me adding the div it does not trigger? I have tried return false and event.preventDefault(); but that didn't work

My AJAX call code is like this

```<code>        $('.trigger').on('click', function(){
          $.ajax({
            url: '../load_div.php',
            type: 'POST',
            data: {
              data: data
            },
            datatype: 'JSON'
          }).done( function(data) {
              console.log(data);
              $('.div_class').html(data);
            });

          });
</code>```

答:
A submit button will automatically load another page.
to avoid this. You can use

```<code><button type="button"></button>
</code>```

or

```<code><input type="button">
</code>```

or in your event handler

```<code>$('.trigger').on('click', function(event){
   event.preventDefault(); //prevents page redirect
   $.ajax({
     url: '../load_div.php',
     type: 'POST',
     data: {
       data: data
     },
     datatype: 'JSON'
   }).done( function(data) {
       console.log(data);
       $('.div_class').html(data);
   });
});
</code>```

Body:
I have an ajax call that loads a div into a popup, but when I click on button, the trigger happens, the div gets loaded then the entire page gets reloaded. I just wanted to know how could I find this second function that is reloading my entire page and add the exception, so that on me adding the div it does not trigger? I have tried return false and event.preventDefault(); but that didn't work

My AJAX call code is like this

        $('.trigger').on('click', function(){
          $.ajax({
            url: '../load_div.php',
            type: 'POST',
            data: {
              data: data
            },
            datatype: 'JSON'
          }).done( function(data) {
              console.log(data);
              $('.div_class').html(data);
            });

          });

Body:
A submit button will automatically load another page.
to avoid this. You can use

<button type="button"></button>

or

<input type="button">

or in your event handler

$('.trigger').on('click', function(event){
   event.preventDefault(); //prevents page redirect
   $.ajax({
     url: '../load_div.php',
     type: 'POST',
     data: {
       data: data
     },
     datatype: 'JSON'
   }).done( function(data) {
       console.log(data);
       $('.div_class').html(data);
   });
});


问:
Inserting 2 rows, each to different tables where one row refrences the other's primary key
Hello folks
Checkout this scenario

Table 1 columns -> | table_1_id (pkey) | some_column | comments |

Table 2 columns -> | table_2_id (pkey) | some_other_column | table_1_id (fkey) | comments |

All primary keys are of type serial or auto number.
The 3rd column on Table 2 is an fk that references Table 1's primary key.

I would like to insert rows into both programmaticaly (from a c++ app)

Do i have to insert to table one then SELECT-query the entry's primary key then insert the Table 2 row with the pkey result?

Is there a more efficient way of handling this? Say using almost 2 queries?

答:
I would suggest looking http://wiki.postgresql.org/wiki/FAQ

The site is a useful resource to go through to get familiar with PostgreSQL

Specifically, the section How do I get the value of a SERIAL insert?

The simplest way is to retrieve the
  assigned SERIAL value with RETURNING.
  Using the example table in the
  previous question, it would look like
  this:

INSERT INTO person (name) VALUES
  ('Blaise Pascal') RETURNING id;

You can also call nextval() and use that value in the INSERT, or call currval() after the INSERT.


问:
Apache spark - convert JavaRDD to csv file
I am try to write my org.apache.spark.api.java.JavaRDD<Object> as pipe separated text to .txt file using Apache spark. For that I am using the spark provided saveAsTextFile method. But issue with this method is, it directly writes the object to file with no formatting and I could not able to give proper file name too.

So which is the best way to format/convert my object into pipe separated string and write that to .txt file and also what is proper way to name file.

This is dependencies in build.gradle

```<code>dependencies {

provided(
        [group: 'org.apache.spark', name: 'spark-core_2.10', version: '1.4.0'],
        [group: 'org.apache.spark', name: 'spark-sql_2.10', version: '1.4.0'],
        [group: 'com.datastax.spark', name: 'spark-cassandra-connector-java_2.10', version: '1.4.0']
)

    compile([

            [group: 'com.databricks', name: 'spark-csv_2.10', version: '1.4.0'],
    ])

}
</code>```

答:
Here is the complete code, using which you can format the data:

```<code>    String args[] = {"/Users/***/Documents/hContent/input/***/micro-/sample.txt",
                    "Users/**/Documents/hadoop/output"};

    SparkConf conf = new SparkConf();
    JavaSparkContext sc = new JavaSparkContext("local", "MaxTemperatureSpark", conf);
    JavaRDD<String> lines = sc.textFile(args[0]);

    JavaRDD<String[]> records = lines.map(new Function<String, String[]>(){

        public String[] call(String t){
            return t.split("\t");
        }
    });

    JavaRDD<String[]> filtered = records.filter(new Function<String[], Boolean>() {

        public Boolean call(String[] rec) throws Exception {
            // TODO Auto-generated method stub
            return rec[0] != "9999" && rec[1].matches("[01459]");
        }
    });

    JavaPairRDD<Integer, Integer> tuples = filtered.mapToPair(
            new PairFunction<String[], Integer, Integer>() {

                public Tuple2<Integer, Integer> call(String[] rec) throws Exception {
                    // TODO Auto-generated method stub
                    return new Tuple2<Integer, Integer>(
                            Integer.parseInt(rec[0]), Integer.parseInt(rec[1]));
                }

            }

    );

    JavaPairRDD<Integer, Integer> maxTemps = tuples.reduceByKey(
                new Function2<Integer, Integer, Integer>() {

                    public Integer call(Integer arg0, Integer arg1) throws Exception {
                        // TODO Auto-generated method stub
                        return Math.max(arg0, arg1);
                    }
                }
            );

    maxTemps.saveAsTextFile(args[1]);
</code>```

Note that the output folder specifies the location where the output files will be created and the name of the files starts as "part-00000". So you can parse the output folder and search for the files.

Body:
I am try to write my org.apache.spark.api.java.JavaRDD<Object> as pipe separated text to .txt file using Apache spark. For that I am using the spark provided saveAsTextFile method. But issue with this method is, it directly writes the object to file with no formatting and I could not able to give proper file name too.

So which is the best way to format/convert my object into pipe separated string and write that to .txt file and also what is proper way to name file.

This is dependencies in build.gradle

dependencies {

provided(
        [group: 'org.apache.spark', name: 'spark-core_2.10', version: '1.4.0'],
        [group: 'org.apache.spark', name: 'spark-sql_2.10', version: '1.4.0'],
        [group: 'com.datastax.spark', name: 'spark-cassandra-connector-java_2.10', version: '1.4.0']
)

    compile([

            [group: 'com.databricks', name: 'spark-csv_2.10', version: '1.4.0'],
    ])

}

Body:
Here is the complete code, using which you can format the data:

    String args[] = {"/Users/***/Documents/hContent/input/***/micro-/sample.txt",
                    "Users/**/Documents/hadoop/output"};

    SparkConf conf = new SparkConf();
    JavaSparkContext sc = new JavaSparkContext("local", "MaxTemperatureSpark", conf);
    JavaRDD<String> lines = sc.textFile(args[0]);

    JavaRDD<String[]> records = lines.map(new Function<String, String[]>(){

        public String[] call(String t){
            return t.split("\t");
        }
    });

    JavaRDD<String[]> filtered = records.filter(new Function<String[], Boolean>() {

        public Boolean call(String[] rec) throws Exception {
            // TODO Auto-generated method stub
            return rec[0] != "9999" && rec[1].matches("[01459]");
        }
    });

    JavaPairRDD<Integer, Integer> tuples = filtered.mapToPair(
            new PairFunction<String[], Integer, Integer>() {

                public Tuple2<Integer, Integer> call(String[] rec) throws Exception {
                    // TODO Auto-generated method stub
                    return new Tuple2<Integer, Integer>(
                            Integer.parseInt(rec[0]), Integer.parseInt(rec[1]));
                }

            }

    );

    JavaPairRDD<Integer, Integer> maxTemps = tuples.reduceByKey(
                new Function2<Integer, Integer, Integer>() {

                    public Integer call(Integer arg0, Integer arg1) throws Exception {
                        // TODO Auto-generated method stub
                        return Math.max(arg0, arg1);
                    }
                }
            );

    maxTemps.saveAsTextFile(args[1]);

Note that the output folder specifies the location where the output files will be created and the name of the files starts as "part-00000". So you can parse the output folder and search for the files.


答:
You have defined function i() inside the self invoking function.Use it outside the self invoking function. Like this:

function i(a) {
    return a + 1; //complex calculate...
}
(function () {
    window.util = {
        n: i(1),
        windowUtil: i(2),
        Hub: i(3)
    };
})()

alert(eval("window.util.aaa =  i(5)"))```

Title: JavaScript dynamic code to self execute function


问:
How to compare rows in a single column?
I have data like the below in an Oracle database

```<code>Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.5    64.6   28.71
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98
</code>```

I have converted the above data like this using pivot

```<code>Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.5               64.6              28.71
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98
</code>```

I want to compare session 1 height with session 3 height, and session 1 weight with session 3 weight.

For e.g.

```<code>if SESSION_1_HEIGHT =SESSION_3_HEIGHT then height_status=true else height_status=false
if SESSION_1_WEIGHT =SESSION_3_WEIGHT then weight_status=true else weight_status=false
if SESSION_1_BMI =SESSION_3_BMI then bmi_status=true else bmi_status=false
</code>```

Please look here at SQLFiddle

答:
For Table that you sampled at SqlFiddle:

```<code>CREATE TABLE TABLE_NAME ( Name, "Session", CATEGORY, HT, WT, BMI ) AS
SELECT 'John', 'SESSION 1', 'OW', 1.5,  64.6, 28.71 FROM DUAL UNION ALL
SELECT 'John', 'SESSION 3', 'OW', 1.52, 63.2, 27.35 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 1', 'OW', 1.48, 55.7, 25.43 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 3', 'OW', 1.52, 55.4, 23.98 FROM DUAL;
</code>```

This should give the result you wanted:

```<code>SELECT T.*, CASE WHEN T.SESSION_1_HEIGHT = T.SESSION_3_HEIGHT THEN 1 ELSE 0 END AS HeightEquals, CASE WHEN T.SESSION_1_WEIGHT = T.SESSION_3_WEIGHT THEN 1 ELSE 0 END AS WeightEquals, CASE WHEN T.SESSION_1_BMI = T.SESSION_3_BMI THEN 1 ELSE 0 END AS BmiEquals FROM (
  SELECT *
  FROM table_name
  PIVOT(
    MAX( HT ) AS height,
    MAX( WT ) AS weight,
    MAX( BMI ) AS BMI
    FOR "Session" IN (
      'SESSION 1' AS Session_1,
      'SESSION 3' AS Session_3
    )
  )
) T;
</code>```

Hope it helps..

Title: How to compare rows in a single column?

Body:
I have data like the below in an Oracle database

Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.5    64.6   28.71
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98

I have converted the above data like this using pivot

Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.5               64.6              28.71
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98

I want to compare session 1 height with session 3 height, and session 1 weight with session 3 weight.

For e.g.

if SESSION_1_HEIGHT =SESSION_3_HEIGHT then height_status=true else height_status=false
if SESSION_1_WEIGHT =SESSION_3_WEIGHT then weight_status=true else weight_status=false
if SESSION_1_BMI =SESSION_3_BMI then bmi_status=true else bmi_status=false

Please look here at SQLFiddle

Body:
For Table that you sampled at SqlFiddle:

CREATE TABLE TABLE_NAME ( Name, "Session", CATEGORY, HT, WT, BMI ) AS
SELECT 'John', 'SESSION 1', 'OW', 1.5,  64.6, 28.71 FROM DUAL UNION ALL
SELECT 'John', 'SESSION 3', 'OW', 1.52, 63.2, 27.35 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 1', 'OW', 1.48, 55.7, 25.43 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 3', 'OW', 1.52, 55.4, 23.98 FROM DUAL;

This should give the result you wanted:

SELECT T.*, CASE WHEN T.SESSION_1_HEIGHT = T.SESSION_3_HEIGHT THEN 1 ELSE 0 END AS HeightEquals, CASE WHEN T.SESSION_1_WEIGHT = T.SESSION_3_WEIGHT THEN 1 ELSE 0 END AS WeightEquals, CASE WHEN T.SESSION_1_BMI = T.SESSION_3_BMI THEN 1 ELSE 0 END AS BmiEquals FROM (
  SELECT *
  FROM table_name
  PIVOT(
    MAX( HT ) AS height,
    MAX( WT ) AS weight,
    MAX( BMI ) AS BMI
    FOR "Session" IN (
      'SESSION 1' AS Session_1,
      'SESSION 3' AS Session_3
    )
  )
) T;

Hope it helps..


问:
How Do I Set The Value Of A String In Android?
I have a string and a button as follows:

```<code>String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}
</code>```

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this

答:
To save a String in SharedPreferences :

```<code>SharedPreferences.Editor editor = getSharedPreferences("com.package.name", Context.MODE_PRIVATE).edit();
editor.putString("keyName", message);
editor.apply();
</code>```

To get it back :

```<code>SharedPreferences sharedPrefs = getSharedPreferences("com.package.name", Context.MODE_PRIVATE);
message = sharedPrefs.getString("keyName",defaultValue);
</code>```

When the user modifies it, save it. When the app start, get it with as default value "Hello World" so that while the user hadn't click the button, it will stay as Hello World.

Body:
I have a string and a button as follows:

String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this

Body:
To save a String in SharedPreferences :

SharedPreferences.Editor editor = getSharedPreferences("com.package.name", Context.MODE_PRIVATE).edit();
editor.putString("keyName", message);
editor.apply();

To get it back :

SharedPreferences sharedPrefs = getSharedPreferences("com.package.name", Context.MODE_PRIVATE);
message = sharedPrefs.getString("keyName",defaultValue);

When the user modifies it, save it. When the app start, get it with as default value "Hello World" so that while the user hadn't click the button, it will stay as Hello World.


问:
2D object detection with only a single training image
The vision system is given a single training image (e.g. a piece of 2D artwork ) and it is asked whether the piece of artwork is present in the newly captured photos. The newly captured photos can contain a lot of any other object and when the artwork is presented, it must face up but may be occluded.

The pose space is x,y,rotation and scale. The artwork may be highly symmetric or not.

What is the latest state of the art handling this kind of problem?

I have tried/considered the following options but there are some problems in all of them. If my argument is invalid please correct me.

deep learning(rcnn/yolo): a lot of labeled data are needed means a lot of human labor is needed for each new pieces of artwork.

traditional machine learning(SVM,Random forest): same as above

sift/surf/orb + ransac or voting: when the artwork is symmetric, the features matched are mostly incorrect. A lot of time is needed in the ransac/voting stage.

generalized hough transform: the state space is too large for the voting table. Pyramid can be applied but it is difficult to choose some universal thresholds for different kinds of artwork to proceed down the pyramid.

chamfer matching: the state space is too large. Too much time is needed in searching across the state space.

答:
You can try using traditional feature based image processing algorithm which might give true positive template matches up to a descent accuracy.

Given template image as in the question:

First dilate the image to join all very closely spaced connected
components.

Find the convex hull of the connected object obtained above,This will give you a polygon.

Use above polygon edge length information like (max-length/min-length) ratio as feature of the template.

Also find the pixel density in the polygon as second feature.

We have 2 features now.

Scene image feature vector:

Similarly Again in the scene image use dilation followed by connected components identification, define convex hull(polygon) around each connected objects and define feature vector for each object(edge info, pixel density).

Now as usual search for template feature vector in the scene image feature vectors data with minimum feature distance(also use certain upper level distance threshold value to avoid false positive matches).

This should give the true positive matches if available in the scene image.

Exception: This method would not work for occluded objects.


问:
Add filter in stored procedure but give error invalid
When I add filter in my stored procedure, it throws an error "invalid column name".

My query is:

```<code>select name, monthlysalary as ms
from Patient
where ms = 2000;
</code>```

答:
You can not use aliases at where part

It should be like that.

```<code>select name, monthlysalary as ms from Patient where monthlysalary =2000;
</code>```

Body:
When I add filter in my stored procedure, it throws an error "invalid column name".

My query is:

select name, monthlysalary as ms
from Patient
where ms = 2000;

Body:
You can not use aliases at where part

It should be like that.

select name, monthlysalary as ms from Patient where monthlysalary =2000;


问:
Comparing values in Python data frame efficiently
I'm trading daily on Cryptocurrencies and would like to find which are the most desirable Cryptos for trading.
I have CSV file for every Crypto with the following fields:

```<code>Date           Sell       Buy
43051.23918    1925.16    1929.83
43051.23919    1925.12    1929.79
43051.23922    1925.12    1929.79
43051.23924    1926.16    1930.83
43051.23925    1926.12    1930.79
43051.23926    1926.12    1930.79
43051.23927    1950.96    1987.56
43051.23928    1190.90    1911.56
43051.23929    1926.12    1930.79
</code>```

I would like to check:

How many quotes will end with profit:

for Buy positions - if one of the following Sells > current Buy.

for Sell positions - if one of the following Buys < current Sell.

How much time it would take to a theoretical position to become profitable.

What can be the profit potential.

I'm using the following code:

```<code>#converting from OLE to datetime
OLE_TIME_ZERO = dt.datetime(1899, 12, 30, 0, 0, 0)
def ole(oledt):
    return OLE_TIME_ZERO + dt.timedelta(days=float(oledt))

#variables initialization
buy_time = ole(43031.57567) - ole(43031.57567)
sell_time = ole(43031.57567) - ole(43031.57567)
profit_buy_counter = 0
no_profit_buy_counter = 0
profit_sell_counter = 0
no_profit_sell_counter = 0

max_profit_buy_positions = 0
max_profit_buy_counter = 0

max_profit_sell_positions = 0
max_profit_sell_counter = 0

df = pd.read_csv("C:/P/Crypto/bitcoin_test_normal_276k.csv")

#comparing to max
for index, row in df.iterrows():
    a = index + 1
    df_slice = df[a:]
    if df_slice["Sell"].max() - row["Buy"] > 0:
        max_profit_buy_positions += df_slice["Sell"].max() - row["Buy"]
        max_profit_buy_counter += 1
    for index1, row1 in df_slice.iterrows():
        if row["Buy"] < row1["Sell"]  :
            buy_time += ole(row1["Date"])- ole(row["Date"])
            profit_buy_counter += 1
            break
    else:
            no_profit_buy_counter += 1

#comparing to sell
for index, row in df.iterrows():
    a = index + 1
    df_slice = df[a:]
    if  row["Sell"] - df_slice["Buy"].min() > 0:
        max_profit_sell_positions += row["Sell"] - df_slice["Buy"].min()
        max_profit_sell_counter += 1
    for index2, row2 in df_slice.iterrows():
        if row["Sell"] > row2["Buy"] :
            sell_time += ole(row2["Date"])- ole(row["Date"])
            profit_sell_counter += 1
            break
    else:
        no_profit_sell_counter += 1

num_rows = len(df.index)

buy_avg_time = buy_time/num_rows
sell_avg_time = sell_time/num_rows

if max_profit_buy_counter == 0:
    avg_max_profit_buy = "There is no profitable buy positions"
else:
    avg_max_profit_buy = max_profit_buy_positions/max_profit_buy_counter

if max_profit_sell_counter == 0:
    avg_max_profit_sell = "There is no profitable sell positions"
else:
   avg_max_profit_sell = max_profit_sell_positions/max_profit_sell_counter
</code>```

The code works fine for 10K-20K lines but for a larger amount (276K) it take a long time (more than 10 hrs)

What can I do in order to improve it?

Is there any "Pythonic" way to compare each value in a data frame to all following values?

note - the dates in the CSV are in OLE so I need to convert it to Datetime.

File for testing:
Thanks for your comment.
Here you can find the file that I used:

答:
First, I'd want to create the cumulative maximum/minimum values for Sell and Buy per row, so it's easy to compare to. pandas has cummax and cummin, but they go the wrong way. So we'll do:

```<code>df['Max Sell'] = df[::-1]['Sell'].cummax()[::-1]
df['Min Buy'] = df[::-1]['Buy'].cummin()[::-1]
</code>```

Now, we can just compare each row:

```<code>df['Buy Profit'] = df['Max Sell'] - df['Buy']
df['Sell Profit'] = df['Sell'] - df['Min Buy']
</code>```

I'm positive this isn't exactly what you want as I don't perfectly understand what you're trying to do, but hopefully it leads you in the right direction.

After comparing your function and mine, there is a slight difference, as your a is offset one off the index. Removing that offset, you'll see that my method produces the same results as yours, only in vastly shorter time:

```<code>for index, row in df.iterrows():
    a = index
    df_slice = df[a:]
    assert (df_slice["Sell"].max() - row["Buy"]) == df['Max Sell'][a] - df['Buy'][a]
else:
    print("All assertions passed!")
</code>```

Note this will still take the very long time required by your function. Note that this can be fixed with shift, but I don't want to run your function for long enough to figure out what way to shift it.

Body:
I'm trading daily on Cryptocurrencies and would like to find which are the most desirable Cryptos for trading.
I have CSV file for every Crypto with the following fields:

Date           Sell       Buy
43051.23918    1925.16    1929.83
43051.23919    1925.12    1929.79
43051.23922    1925.12    1929.79
43051.23924    1926.16    1930.83
43051.23925    1926.12    1930.79
43051.23926    1926.12    1930.79
43051.23927    1950.96    1987.56
43051.23928    1190.90    1911.56
43051.23929    1926.12    1930.79

I would like to check:

How many quotes will end with profit:

for Buy positions - if one of the following Sells > current Buy.

for Sell positions - if one of the following Buys < current Sell.

How much time it would take to a theoretical position to become profitable.

What can be the profit potential.

I'm using the following code:

#converting from OLE to datetime
OLE_TIME_ZERO = dt.datetime(1899, 12, 30, 0, 0, 0)
def ole(oledt):
    return OLE_TIME_ZERO + dt.timedelta(days=float(oledt))

#variables initialization
buy_time = ole(43031.57567) - ole(43031.57567)
sell_time = ole(43031.57567) - ole(43031.57567)
profit_buy_counter = 0
no_profit_buy_counter = 0
profit_sell_counter = 0
no_profit_sell_counter = 0

max_profit_buy_positions = 0
max_profit_buy_counter = 0

max_profit_sell_positions = 0
max_profit_sell_counter = 0

df = pd.read_csv("C:/P/Crypto/bitcoin_test_normal_276k.csv")

#comparing to max
for index, row in df.iterrows():
    a = index + 1
    df_slice = df[a:]
    if df_slice["Sell"].max() - row["Buy"] > 0:
        max_profit_buy_positions += df_slice["Sell"].max() - row["Buy"]
        max_profit_buy_counter += 1
    for index1, row1 in df_slice.iterrows():
        if row["Buy"] < row1["Sell"]  :
            buy_time += ole(row1["Date"])- ole(row["Date"])
            profit_buy_counter += 1
            break
    else:
            no_profit_buy_counter += 1

#comparing to sell
for index, row in df.iterrows():
    a = index + 1
    df_slice = df[a:]
    if  row["Sell"] - df_slice["Buy"].min() > 0:
        max_profit_sell_positions += row["Sell"] - df_slice["Buy"].min()
        max_profit_sell_counter += 1
    for index2, row2 in df_slice.iterrows():
        if row["Sell"] > row2["Buy"] :
            sell_time += ole(row2["Date"])- ole(row["Date"])
            profit_sell_counter += 1
            break
    else:
        no_profit_sell_counter += 1

num_rows = len(df.index)

buy_avg_time = buy_time/num_rows
sell_avg_time = sell_time/num_rows

if max_profit_buy_counter == 0:
    avg_max_profit_buy = "There is no profitable buy positions"
else:
    avg_max_profit_buy = max_profit_buy_positions/max_profit_buy_counter

if max_profit_sell_counter == 0:
    avg_max_profit_sell = "There is no profitable sell positions"
else:
   avg_max_profit_sell = max_profit_sell_positions/max_profit_sell_counter

The code works fine for 10K-20K lines but for a larger amount (276K) it take a long time (more than 10 hrs)

What can I do in order to improve it?

Is there any "Pythonic" way to compare each value in a data frame to all following values?

note - the dates in the CSV are in OLE so I need to convert it to Datetime.

File for testing:
Thanks for your comment.
Here you can find the file that I used:

Body:
First, I'd want to create the cumulative maximum/minimum values for Sell and Buy per row, so it's easy to compare to. pandas has cummax and cummin, but they go the wrong way. So we'll do:

df['Max Sell'] = df[::-1]['Sell'].cummax()[::-1]
df['Min Buy'] = df[::-1]['Buy'].cummin()[::-1]

Now, we can just compare each row:

df['Buy Profit'] = df['Max Sell'] - df['Buy']
df['Sell Profit'] = df['Sell'] - df['Min Buy']

I'm positive this isn't exactly what you want as I don't perfectly understand what you're trying to do, but hopefully it leads you in the right direction.

After comparing your function and mine, there is a slight difference, as your a is offset one off the index. Removing that offset, you'll see that my method produces the same results as yours, only in vastly shorter time:

for index, row in df.iterrows():
    a = index
    df_slice = df[a:]
    assert (df_slice["Sell"].max() - row["Buy"]) == df['Max Sell'][a] - df['Buy'][a]
else:
    print("All assertions passed!")

Note this will still take the very long time required by your function. Note that this can be fixed with shift, but I don't want to run your function for long enough to figure out what way to shift it.


问:
C# UWP The property was not found in viewmodel
My CollectionViewSource gets a underline in VS with the following message: "Property 'Courses' was not found in MainPageViewModel" and I can't seem to find out why it won't be found, so I'm looking for help. My MainPage.xaml looks like this:

```<code><Page x:Class="CourseStudent.UWP.Views.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
      xmlns:controls="using:Template10.Controls"
      xmlns:converters="using:Template10.Converters"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="using:CourseStudent.UWP.Views"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:vm="using:CourseStudent.UWP.ViewModels" mc:Ignorable="d">

    <Page.DataContext>
        <vm:MainPageViewModel x:Name="ViewModel" />
    </Page.DataContext>
    <Page.Resources>
        <converters:StringFormatConverter x:Key="CoursesHeaderConverter" Format="Courses ({0})"/>

        <!-- Collection of courses displayed by this page -->
        <CollectionViewSource
            x:Name="coursesViewSource"
            Source="{x:Bind ViewModel.Courses}"
            d:Source="{d:DesignData /SampleData/CoursesSampleData.xaml}"/>
    </Page.Resources>

    <RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <controls:PageHeader x:Name="pageHeader" Content="Main Page"
                             RelativePanel.AlignLeftWithPanel="True"
                             RelativePanel.AlignRightWithPanel="True"
                             RelativePanel.AlignTopWithPanel="True" />

        <TextBlock x:Name="mainTextBlock" Margin="16,12,0,0"
                   RelativePanel.AlignLeftWithPanel="True"
                   RelativePanel.Below="pageHeader" Text="Courses" />

    </RelativePanel>

</Page>
</code>```

And my MainPageViewModel.cs looks like this

```<code>using CourseStudent.Model;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;

namespace CourseStudent.UWP.ViewModel
{
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            { }
        }

        ObservableCollection<Course> courses;
        public ObservableCollection<Course> Courses { get { return courses; } set { Set(ref courses, value); } }

        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
        {
            if (Courses == null) // get courses from the data API
            {
                Courses = new ObservableCollection<Course>
                {
                    new Course() { CourseName = "blabla"},
                    new Course() { CourseName = "bloblo"},
                    new Course() { CourseName = "jojo"},

                };
            }

            if (suspensionState.Any())
            {
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
        {
            if (suspending)
            {
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
        {
            args.Cancel = false;
            await Task.CompletedTask;
        }
    }
}
</code>```

I'm wondering if there's anyone here who can see where I've gone wrong?

答:
Firstly, the namespace for the MainPageViewModel is CourseStudent.UWP.ViewModel on your side, but what you reference is using:CourseStudent.UWP.ViewModels which has additional s added. You could try to check this firstly.

Beside this, I cannot reproduce your issue on my side. Since your code snippet is not the completed, so I provide a minimal worked demo you could reference.

MainPage.xaml

```<code><Page.DataContext>
    <local:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>
<Page.Resources>
    <!--  Collection of courses displayed by this page  -->
    <CollectionViewSource x:Name="coursesViewSource" Source="{x:Bind ViewModel.Courses}" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemsSource="{Binding Source={StaticResource coursesViewSource}}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Course">
                <TextBlock Text="{x:Bind CourseName}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>
</code>```

MainPageViewModel

```<code>public class MainPageViewModel
{
    public MainPageViewModel()
    {
        courses = new ObservableCollection<Course>()
        {
            new Course() { CourseName = "blabla"},
            new Course() { CourseName = "bloblo"},
            new Course() { CourseName = "jojo"}
        };
    }
    ObservableCollection<Course> courses;
    public ObservableCollection<Course> Courses { get => courses; set => courses = value; }
}

public class Course
{
    public string CourseName { get; set; }
}
</code>```

Try to add more code on a working small demo to narrow the issue. If you still have issues, please provide the minimal reproduced project.

Body:
My CollectionViewSource gets a underline in VS with the following message: "Property 'Courses' was not found in MainPageViewModel" and I can't seem to find out why it won't be found, so I'm looking for help. My MainPage.xaml looks like this:

<Page x:Class="CourseStudent.UWP.Views.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
      xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
      xmlns:controls="using:Template10.Controls"
      xmlns:converters="using:Template10.Converters"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="using:CourseStudent.UWP.Views"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:vm="using:CourseStudent.UWP.ViewModels" mc:Ignorable="d">

    <Page.DataContext>
        <vm:MainPageViewModel x:Name="ViewModel" />
    </Page.DataContext>
    <Page.Resources>
        <converters:StringFormatConverter x:Key="CoursesHeaderConverter" Format="Courses ({0})"/>

        <CollectionViewSource
            x:Name="coursesViewSource"
            Source="{x:Bind ViewModel.Courses}"
            d:Source="{d:DesignData /SampleData/CoursesSampleData.xaml}"/>
    </Page.Resources>

    <RelativePanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <controls:PageHeader x:Name="pageHeader" Content="Main Page"
                             RelativePanel.AlignLeftWithPanel="True"
                             RelativePanel.AlignRightWithPanel="True"
                             RelativePanel.AlignTopWithPanel="True" />

        <TextBlock x:Name="mainTextBlock" Margin="16,12,0,0"
                   RelativePanel.AlignLeftWithPanel="True"
                   RelativePanel.Below="pageHeader" Text="Courses" />

    </RelativePanel>

</Page>

And my MainPageViewModel.cs looks like this

using CourseStudent.Model;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;

namespace CourseStudent.UWP.ViewModel
{
    public class MainPageViewModel : ViewModelBase
    {
        public MainPageViewModel()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            { }
        }

        ObservableCollection<Course> courses;
        public ObservableCollection<Course> Courses { get { return courses; } set { Set(ref courses, value); } }

        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
        {
            if (Courses == null) // get courses from the data API
            {
                Courses = new ObservableCollection<Course>
                {
                    new Course() { CourseName = "blabla"},
                    new Course() { CourseName = "bloblo"},
                    new Course() { CourseName = "jojo"},

                };
            }

            if (suspensionState.Any())
            {
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
        {
            if (suspending)
            {
            }
            await Task.CompletedTask;
        }

        public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
        {
            args.Cancel = false;
            await Task.CompletedTask;
        }
    }
}

I'm wondering if there's anyone here who can see where I've gone wrong?

Body:
Firstly, the namespace for the MainPageViewModel is CourseStudent.UWP.ViewModel on your side, but what you reference is using:CourseStudent.UWP.ViewModels which has additional s added. You could try to check this firstly.

Beside this, I cannot reproduce your issue on my side. Since your code snippet is not the completed, so I provide a minimal worked demo you could reference.

MainPage.xaml

<Page.DataContext>
    <local:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>
<Page.Resources>
    <!--  Collection of courses displayed by this page  -->
    <CollectionViewSource x:Name="coursesViewSource" Source="{x:Bind ViewModel.Courses}" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView ItemsSource="{Binding Source={StaticResource coursesViewSource}}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Course">
                <TextBlock Text="{x:Bind CourseName}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

MainPageViewModel

public class MainPageViewModel
{
    public MainPageViewModel()
    {
        courses = new ObservableCollection<Course>()
        {
            new Course() { CourseName = "blabla"},
            new Course() { CourseName = "bloblo"},
            new Course() { CourseName = "jojo"}
        };
    }
    ObservableCollection<Course> courses;
    public ObservableCollection<Course> Courses { get => courses; set => courses = value; }
}

public class Course
{
    public string CourseName { get; set; }
}

Try to add more code on a working small demo to narrow the issue. If you still have issues, please provide the minimal reproduced project.


问:
Login program from external text file
I'm having issues with a code where I have to get a user to type details about themselves, which saves to a text file. When the user tries to log in, it will check the text file for their details. Here is my code below. It works at first, where the user is granted access, but whenever I do a restart to my computer, or Python itself, it only grants the last user access. Some help would be appreciated, thank you:

This is what it looks like in the text file:

```<code>Adam16,adam123,Adam,Sunderland,16
Johnny18,johnny150,Johnny,Vane,18
</code>```

This is the source code:

```<code>import csv

import sys

def register():

    firstname = input("First name: ")
    surname = input("Surname: ")
    age = int(input("Age: "))
    password = input("Password: ")

    username = firstname[:3] + str(age)

    with open("account.txt","a",newline="") as myfile:
        writer = csv.writer(myfile)
        writer.writerow([username,password,firstname,surname,age])
        myfile.close()

    menu()

def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")

    for line in file:
        details = line.split(",")

    if user0 == details[0] and pass0 == details[1]:
        print("Correct!")
    else:
        print("Fail")

    menu()

def menu():

    selection = int(input("1 or 2: "))

    if selection == 1:
        register()
    else:
        login()

menu()
</code>```

答:
Your main problem is identation - your if user0 == details[0] and pass0 == details[1]: is on the same indentation as the for line in file:- meaning it is executed after the for-loop not inside it and for each details. You are currently only ever checking the last detail you parse from your file.

You can fix this by indenting it correctly.

This would then lead to multiple outputs - if your user is on line 100 it will print 99 fails and 1 correct - thats why I would put the printing outside the for loop. You can use break to abort the loop as soon as you found the correct user.

Changing your login to this will accomplish that:

```<code>def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")
    foundOne = False

    for line in file:
        details = line.split(",")
        # execute Check on each line, not only on last line
        if user0 == details[0] and pass0 == details[1]:
            foundOne = True
            break # this will instantly leave the for loop of line checkings

    if foundOne == True:
        print("Correct!")
    else:
        print("Fail")

    menu()
</code>```

I indented the if ... so it is done for each line instead of only once. I also set a status to avoid printing Fail for each checked line.

Make sure to use the correct username - it is a combination of firstname and age

Title: Login program from external text file

Body:
I'm having issues with a code where I have to get a user to type details about themselves, which saves to a text file. When the user tries to log in, it will check the text file for their details. Here is my code below. It works at first, where the user is granted access, but whenever I do a restart to my computer, or Python itself, it only grants the last user access. Some help would be appreciated, thank you:

This is what it looks like in the text file:

Adam16,adam123,Adam,Sunderland,16
Johnny18,johnny150,Johnny,Vane,18

This is the source code:

import csv

import sys

def register():

    firstname = input("First name: ")
    surname = input("Surname: ")
    age = int(input("Age: "))
    password = input("Password: ")

    username = firstname[:3] + str(age)

    with open("account.txt","a",newline="") as myfile:
        writer = csv.writer(myfile)
        writer.writerow([username,password,firstname,surname,age])
        myfile.close()

    menu()

def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")

    for line in file:
        details = line.split(",")

    if user0 == details[0] and pass0 == details[1]:
        print("Correct!")
    else:
        print("Fail")

    menu()

def menu():

    selection = int(input("1 or 2: "))

    if selection == 1:
        register()
    else:
        login()

menu()

Body:
Your main problem is identation - your if user0 == details[0] and pass0 == details[1]: is on the same indentation as the for line in file:- meaning it is executed after the for-loop not inside it and for each details. You are currently only ever checking the last detail you parse from your file.

You can fix this by indenting it correctly.

This would then lead to multiple outputs - if your user is on line 100 it will print 99 fails and 1 correct - thats why I would put the printing outside the for loop. You can use break to abort the loop as soon as you found the correct user.

Changing your login to this will accomplish that:

def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")
    foundOne = False

    for line in file:
        details = line.split(",")
        # execute Check on each line, not only on last line
        if user0 == details[0] and pass0 == details[1]:
            foundOne = True
            break # this will instantly leave the for loop of line checkings

    if foundOne == True:
        print("Correct!")
    else:
        print("Fail")

    menu()

I indented the if ... so it is done for each line instead of only once. I also set a status to avoid printing Fail for each checked line.

Make sure to use the correct username - it is a combination of firstname and age


问:
How to get all sub folders and its files - UWP
I have a fixed folder in desktop called student_names. it contains sub folders and each sub folders contains its files. Now I want to store those sub folders and its corresponding file names in an array list. how is it possible?</p>

答:
UWP Applications cannot directly access a folder (except application folders) without the user explicitly providing access to the folder (atleast once).

So in order to always be able to read/write to a specific folder you need to first ask user to select the specific folder. Once the user selects a folder you may save it to FutureAccessList which will provide you with a token to directly get access to the folder(without user intervention) for future use..

```<code> var picker = new FolderPicker();
 picker.FileTypeFilter.Add("*");
 var folder = await picker.PickSingleFolderAsync();
 //add selected folder to FutureAccessList
StorageApplicationPermissions.FutureAccessList.AddOrReplace("futureAccessToken", folder);
</code>```

From next launch (or any logic that you implement) you can access the folder and list its contents

```<code> var folder = await StorageApplicationPermissions.FutureAccessList.
                 GetFolderAsync("futureAccessToken");
 IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
</code>```

So, you just need to provide access to the parent folder (which in your case is student_names) then you will be able to access its sub folders and files.

Hope this helps..

Body:
UWP Applications cannot directly access a folder (except application folders) without the user explicitly providing access to the folder (atleast once).

So in order to always be able to read/write to a specific folder you need to first ask user to select the specific folder. Once the user selects a folder you may save it to FutureAccessList which will provide you with a token to directly get access to the folder(without user intervention) for future use..

 var picker = new FolderPicker();
 picker.FileTypeFilter.Add("*");
 var folder = await picker.PickSingleFolderAsync();
 //add selected folder to FutureAccessList
StorageApplicationPermissions.FutureAccessList.AddOrReplace("futureAccessToken", folder);

From next launch (or any logic that you implement) you can access the folder and list its contents

 var folder = await StorageApplicationPermissions.FutureAccessList.
                 GetFolderAsync("futureAccessToken");
 IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();

So, you just need to provide access to the parent folder (which in your case is student_names) then you will be able to access its sub folders and files.

Hope this helps..


问:
In ReactiveExtensions how to select element from enumberable of elements?
As usual its difficult to explain my Rx question so ill let the code do the talking:

```<code>public class Feature
{
    public ReactiveProperty<bool> IsRunning = new ReactiveProperty<bool>(false);
}

public class MyHelpers
{
    public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
    {
        // How do I return the latest running feature?
        // AND support disposing so no memory leaks
    }
}

public class TestMyHelpers
{
    public void Tests()
    {
        var features = new List<Feature>() {new Feature(), new Feature(), new Feature()};
        var running = MyHelpers.GetRunningFeature(features);

        features[1].IsRunning.Value = true;
        Assert.AreEqual(features[1], running.Value);

        features[2].IsRunning.Value = true;
        Assert.AreEqual(features[2], running.Value);

        features[2].IsRunning.Value = false;
        Assert.AreEqual(features[1], running.Value);

        features[1].IsRunning.Value = false;
        Assert.AreEqual(null, running.Value);
    }
}
</code>```

Basically I want a solution that returns me the latest running feature given an initial input of IEnumerable of features and do it in a way that doesnt leak memory?

Anyone have any ideas?

答:
Ahh I think I found the answer but if anyone knows of a better way of doing it im open to suggestions:</p>

```<code>public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
        {
            return Observable.Create<Feature>(obs =>
                {
                    var disposables = new CompositeDisposable();

                    foreach (var feature in features)
                        feature.IsRunning.Subscribe(_ =>
                                obs.OnNext(features.First(f => f.IsRunning.Value)))
                            .AddTo(disposables);

                    return Disposable.Create(() => disposables.Dispose());
                })
                .ToReadOnlyReactiveProperty();
        }
</code>```

Body:
As usual its difficult to explain my Rx question so ill let the code do the talking:

public class Feature
{
    public ReactiveProperty<bool> IsRunning = new ReactiveProperty<bool>(false);
}

public class MyHelpers
{
    public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
    {
        // How do I return the latest running feature?
        // AND support disposing so no memory leaks
    }
}

public class TestMyHelpers
{
    public void Tests()
    {
        var features = new List<Feature>() {new Feature(), new Feature(), new Feature()};
        var running = MyHelpers.GetRunningFeature(features);

        features[1].IsRunning.Value = true;
        Assert.AreEqual(features[1], running.Value);

        features[2].IsRunning.Value = true;
        Assert.AreEqual(features[2], running.Value);

        features[2].IsRunning.Value = false;
        Assert.AreEqual(features[1], running.Value);

        features[1].IsRunning.Value = false;
        Assert.AreEqual(null, running.Value);
    }
}

Basically I want a solution that returns me the latest running feature given an initial input of IEnumerable of features and do it in a way that doesnt leak memory?

Anyone have any ideas?

Body:
Ahh I think I found the answer but if anyone knows of a better way of doing it im open to suggestions:

public static ReadOnlyReactiveProperty<Feature> GetRunningFeature(IEnumerable<Feature> features)
        {
            return Observable.Create<Feature>(obs =>
                {
                    var disposables = new CompositeDisposable();

                    foreach (var feature in features)
                        feature.IsRunning.Subscribe(_ =>
                                obs.OnNext(features.First(f => f.IsRunning.Value)))
                            .AddTo(disposables);

                    return Disposable.Create(() => disposables.Dispose());
                })
                .ToReadOnlyReactiveProperty();
        }


答:
Make the .btn-group positioned relative and the ul positioned absolute. You may want to change the absolute positioning according to your liking.

The z-index can be removed.

.btn-group {
  position: relative;
}

ul.dropdown-menu.pull-right {
  position: absolute;
  top: 0;
  left: -160px;
  width: 160px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
  <thead>
    <tr>
      <th>Sr.No</th>
      <th>LeadCreated DateTime</th>
      <th>RetailerName</th>
      <th>ShopName</th>
      <th>Mobile</th>
      <th>Address</th>
      <th>City</th>
      <th>Pincode</th>
      <th>Status</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr class="odd gradeX">
      <td>1</td>
      <td>10-10-2017</td>
      <td>Test</td>
      <td>Test</td>
      <td>9904773479</td>
      <td>Surat</td>
      <td>Surat</td>
      <td>304230</td>
      <td style="background: <?php if ($row->Status == 'InProcess') echo 'green';if ($row->Status == 'Closed') echo 'orange';if ($row->Status == 'Dead') echo 'black'; ?>;color: #FFFFFF">
        <?= $row->Status ?>
      </td>
      <td class="pbutton">
        <div class="btn-group">
          <!-- Button trigger modal -->
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                                                Action <span class="caret"></span>
                                                            </button>
          <ul class="dropdown-menu pull-right " role="menu">
            <li>LeadId ?>" data-toggle="modal" data-target="#viewleadmodal"><span class="glyphicon glyphicon-fullscreen"></span> View</li>
            <li><span class="fa fa-edit"></span> Add Lead Update</li>
            <li><span class="fa fa-edit"></span> Edit</li>
            <li><span class="glyphicon glyphicon-trash"></span> Delete</li>
          </ul>
        </div>
      </td>
    </tr>

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

Title: unable to open div box as layer using z-index

Body:
I am trying to open action div box as layer in but unable to do that.

when i click on action button div box will open within that  only. it should be open as layer.

Code:

ul {
  z-index: 2
}

table {
  z-index: 1
}

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Sr.No
      LeadCreated DateTime
      RetailerName
      ShopName
      Mobile
      Address
      City
      Pincode
      Status
      Action

      1
      10-10-2017
      Test
      Test
      9904773479
      Surat
      Surat
      304230
      <td style="background: <?php if ($row->Status == 'InProcess') echo 'green';if ($row->Status == 'Closed') echo 'orange';if ($row->Status == 'Dead') echo 'black'; ?>;color: #FFFFFF">
        <?= $row->Status ?>

          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                                                Action
                                                            </button>

<a href="#viewleadmodal" data-id="<?= $row->LeadId ?>" data-toggle="modal" data-target="#viewleadmodal"> View

 Add Lead Update

 Edit

 Delete

Body:
Make the .btn-group positioned relative and the ul positioned absolute. You may want to change the absolute positioning according to your liking.

The z-index can be removed.

.btn-group {
  position: relative;
}

ul.dropdown-menu.pull-right {
  position: absolute;
  top: 0;
  left: -160px;
  width: 160px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
  <thead>
    <tr>
      <th>Sr.No</th>
      <th>LeadCreated DateTime</th>
      <th>RetailerName</th>
      <th>ShopName</th>
      <th>Mobile</th>
      <th>Address</th>
      <th>City</th>
      <th>Pincode</th>
      <th>Status</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr class="odd gradeX">
      <td>1</td>
      <td>10-10-2017</td>
      <td>Test</td>
      <td>Test</td>
      <td>9904773479</td>
      <td>Surat</td>
      <td>Surat</td>
      <td>304230</td>
      <td style="background: <?php if ($row->Status == 'InProcess') echo 'green';if ($row->Status == 'Closed') echo 'orange';if ($row->Status == 'Dead') echo 'black'; ?>;color: #FFFFFF">
        <?= $row->Status ?>
      </td>
      <td class="pbutton">
        <div class="btn-group">
          <!-- Button trigger modal -->
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                                                Action <span class="caret"></span>
                                                            </button>
          <ul class="dropdown-menu pull-right " role="menu">
            <li><a href="#viewleadmodal" data-id="<?= $row->LeadId ?>" data-toggle="modal" data-target="#viewleadmodal"><span class="glyphicon glyphicon-fullscreen"></span>&nbsp;View</a></li>
            <li><a href="followup.php?LeadId=1"><span class="fa fa-edit"></span>&nbsp;Add Lead Update</a></li>
            <li><a href="leadedit.php"><span class="fa fa-edit"></span>&nbsp;Edit</a></li>
            <li><a href="javascript:void(0)" onclick="check_perform_sdelete('14');"><span class="glyphicon glyphicon-trash"></span>&nbsp;Delete</a></li>
          </ul>
        </div>
      </td>
    </tr>

  </tbody>
</table>


问:
Entity Framework sending parameters as unicode causing performance problems
We have built a EF1 model over a legacy SQL Database.

In this database there are columns with non-unicode strings. These columns are also used as keys.

We had a problem with performance with one specific query. We noticed that EF was sending the parameter as Unicode.

We then rewrote this part of the code to run a SQL statement directly, and send the parameter as a non-unicode string.

The difference was as follows:

With EF : 23000 ms

Without EF: 90 ms

What appears to be happening is that SQL server takes the field from each of the 50000 rows converts it to Unicode to compare it with the parameter being sent in.

Anyone know how to get EF to send the parameter as a non-unicode string? Or any other way to fix this.

答: That [and many other issues impacting performance] is fixed in EFv4. Your best bet is to use EFv4 (Entity Framework in .net 4.0) instead of EFv1 (Entity Framework in .net 3.5).</p>


问:
android studio new project can't see src folder
After the reinstall of android studio , I have created a new project: MyapplicationProject

In Windows explorer I see all the folders :

```
MyapplicationProject
   \Myapplication
      \libs
      \src
       ...
```

In android studio I don't see the src, libs, res folders!

See http://img89.imageshack.us/img89/3880/owi7.png

When I import an old project ==> ok.  I don't understand.  I don't find properties of the project.

答: If you are using latest android studio, you can change the view. see the attached imageChange View from drop down</p>

Body:
After the reinstall of android studio , I have created a new project: MyapplicationProject

In Windows explorer I see all the folders :

MyapplicationProject
   \Myapplication
      \libs
      \src
       ...

In android studio I don't see the src, libs, res folders!

See http://img89.imageshack.us/img89/3880/owi7.png

When I import an old project ==> ok.  I don't understand.  I don't find properties of the project.


问:
Enable press effect on RecyclerView's item in android
I have RecyclerView with list of data:

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/categoriesList"
        android:layout_width="368dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clickable="true"
        android:focusable="true"
        android:foreground="?android:attr/selectableItemBackground"
        android:background="?android:selectableItemBackground"/>
</code>```

When I tap to any items in this list, I wait pressing effect. I do not have a click handler, but in the standard ListView, any click on an element is visible. And I look like there's nothing to react

I need next:

答:
This is your answer: How can I give an imageview click effect like a button on Android?

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:drawable="@drawable/img_down" />
    <item android:state_selected="false"
        android:drawable="@drawable/img_up" />
</selector>
</code>```

You can customized it and use it as per your choice of colour.

Body:
I have RecyclerView with list of data:

<android.support.v7.widget.RecyclerView
        android:id="@+id/categoriesList"
        android:layout_width="368dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clickable="true"
        android:focusable="true"
        android:foreground="?android:attr/selectableItemBackground"
        android:background="?android:selectableItemBackground"/>

When I tap to any items in this list, I wait pressing effect. I do not have a click handler, but in the standard ListView, any click on an element is visible. And I look like there's nothing to react

I need next:

Body:
This is your answer: How can I give an imageview click effect like a button on Android?

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:drawable="@drawable/img_down" />
    <item android:state_selected="false"
        android:drawable="@drawable/img_up" />
</selector>

You can customized it and use it as per your choice of colour.


问:
too many imports cause `pub serve` to hang
When I run pub -v serve web for my AngularDart app, pub always hangs here:

```<code>% pub -v serve web
FINE: Pub 1.25.0-dev.16.4
FINE: Loading asset environment...
FINE: Initializing barback...
FINE: Serving packages on localhost:0.
MSG : Loading source assets...
FINE: Providing sources for ordreset|lib.
FINE: Loading source assets finished (0.053s).
FINE: Provided sources.
FINE: Loading transformers...
FINE: Transformer dependencies:
    | angular: -
    | test/pub_serve: -
    | dart_to_js_script_rewriter: -
FINE: Using cached transformer snapshot.
MSG : Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
FINE: Loading transformers from [angular, test/pub_serve, dart_to_js_script_rewriter]
FINE: Spawning isolate from ./.pub/transformers/transformers.snapshot.
FINE: Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers finished (0.151s).
FINE: Transformers from angular: {group of [[BuilderTransformer: Instance of 'TemplatePlaceholderBuilder'], [ReflectionRemover], [StylesheetCompiler, BuilderTransformer: Instance of 'LibraryBuilder']]}
FINE: Transformers from test/pub_serve: {PubServe}
FINE: Transformers from dart_to_js_script_rewriter: {DartToJsScriptRewriter}
FINE: Loading transformers finished (0.649s).
FINE: Initializing barback finished (0.763s).
FINE: Loading asset environment finished (1.062s).
FINE: Providing sources for ordreset|web.
FINE: Bound "web" to localhost:8080.
MSG : Serving ordreset web on http://localhost:8080
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 50 ms on ordreset|lib/src/dashboard_component.css
FINE: [Fine from StylesheetCompiler on ordreset|lib/src/dashboard_component.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 30 ms on ordreset|web/main.css
FINE: [Fine from StylesheetCompiler on ordreset|web/main.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'TemplatePlaceholderBuilder' on ordreset|primary]:
    | Took 0.4s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 10.0s
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 20.0s
</code>```

I noticed that when removing all import 'package:xml/xml.dart' as xml; statements, that pub serve doesn't hang anymore then. But I did observe the same behaviour in the past, that removing all import 'package:angular_components/angular_components.dart'; fixed the problem as well. Hence I actually doubt that it's a problem with either the xml or the angular_components package but that the problem might be related to an import limitation of source_gen, similar to this issue from the past.

I've uploaded my AngularDart project here. You can run pub get and then pub -v serve web yourself to see how pub hangs.

PS: I've emptied all AngularDart HTML template files before pushing the code to the public GitHub repo for privacy reasons but that shouldn't change the fact that pub serve should still succeed.

答:
https://github.com/thosakwe/pub_mediator (web version is currently down :-/)

reveales

```<code>$ mediator
✗ Found 1 dependency conflict:
Found 2 mismatching dependencies on package:build:
  * angular requires  ^0.10.0
  * angular->build_barback requires  ^0.11.0
</code>```

You can try to add

```<code>dependency_overrides:
  build: ^0.11.0
</code>```

See also https://github.com/dart-lang/pub/issues/912

Body:
When I run pub -v serve web for my AngularDart app, pub always hangs here:

% pub -v serve web
FINE: Pub 1.25.0-dev.16.4
FINE: Loading asset environment...
FINE: Initializing barback...
FINE: Serving packages on localhost:0.
MSG : Loading source assets...
FINE: Providing sources for ordreset|lib.
FINE: Loading source assets finished (0.053s).
FINE: Provided sources.
FINE: Loading transformers...
FINE: Transformer dependencies:
    | angular: -
    | test/pub_serve: -
    | dart_to_js_script_rewriter: -
FINE: Using cached transformer snapshot.
MSG : Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers...
FINE: Loading transformers from [angular, test/pub_serve, dart_to_js_script_rewriter]
FINE: Spawning isolate from ./.pub/transformers/transformers.snapshot.
FINE: Loading angular, test/pub_serve and dart_to_js_script_rewriter transformers finished (0.151s).
FINE: Transformers from angular: {group of [[BuilderTransformer: Instance of 'TemplatePlaceholderBuilder'], [ReflectionRemover], [StylesheetCompiler, BuilderTransformer: Instance of 'LibraryBuilder']]}
FINE: Transformers from test/pub_serve: {PubServe}
FINE: Transformers from dart_to_js_script_rewriter: {DartToJsScriptRewriter}
FINE: Loading transformers finished (0.649s).
FINE: Initializing barback finished (0.763s).
FINE: Loading asset environment finished (1.062s).
FINE: Providing sources for ordreset|web.
FINE: Bound "web" to localhost:8080.
MSG : Serving ordreset web on http://localhost:8080
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 50 ms on ordreset|lib/src/dashboard_component.css
FINE: [Fine from StylesheetCompiler on ordreset|lib/src/dashboard_component.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from StylesheetCompiler]:
    | [processStylesheet] took 30 ms on ordreset|web/main.css
FINE: [Fine from StylesheetCompiler on ordreset|web/main.css]:
    | Took 0.2s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'TemplatePlaceholderBuilder' on ordreset|primary]:
    | Took 0.4s (0.0s awaiting secondary inputs).
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 10.0s
FINE: [Fine from BuilderTransformer: Instance of 'LibraryBuilder' on ordreset|primary]:
    | Not yet complete after 20.0s

I noticed that when removing all import 'package:xml/xml.dart' as xml; statements, that pub serve doesn't hang anymore then. But I did observe the same behaviour in the past, that removing all import 'package:angular_components/angular_components.dart'; fixed the problem as well. Hence I actually doubt that it's a problem with either the xml or the angular_components package but that the problem might be related to an import limitation of source_gen, similar to this issue from the past.

I've uploaded my AngularDart project here. You can run pub get and then pub -v serve web yourself to see how pub hangs.

PS: I've emptied all AngularDart HTML template files before pushing the code to the public GitHub repo for privacy reasons but that shouldn't change the fact that pub serve should still succeed.

Body:
https://github.com/thosakwe/pub_mediator (web version is currently down :-/)

reveales

$ mediator
✗ Found 1 dependency conflict:
Found 2 mismatching dependencies on package:build:
  * angular requires  ^0.10.0
  * angular->build_barback requires  ^0.11.0

You can try to add

dependency_overrides:
  build: ^0.11.0

See also https://github.com/dart-lang/pub/issues/912


问:
How can I set the title of the Delete view with AOR?
I see the Delete component takes a Title prop but how would one pass such prop to it for a given resource?</p>

答: You can find a good example in the demo source code: https://github.com/marmelab/admin-on-rest-demo/blob/master/src/visitors/index.js#L116</p>


问:
How to get the last executed SQL statement in HANA?
I am inside a SQLScript procedure and would like to return the last SQL Statement from this procedure, like the last rowcount:

```<code>/********* Begin Procedure Script ************/
BEGIN
    select 1 as "my_data" from dummy;
    select '::last_SQL' as "last executed sql" from dummy;
    select ::ROWCOUNT as "rowcount" from dummy;
END;
 /********* End Procedure Script ************/
</code>```

The column "last executed SQL" should be populated with select 1 as "my_data" from dummy in this case. Is there any variable holding the last statement (or any easy way to retrieve the query plan)?

答:
Maybe you can query sys.m_sql_plan_cache system view

Please check following SELECT statement

```<code>select
    statement_string, last_execution_timestamp
from SYS.M_SQL_PLAN_CACHE
where user_name = 'KODYAZ'
order by last_execution_timestamp desc;
</code>```

I believe you can improve the query by introducing new filter criteria.

ContentLicense: CC BY-SA 4.0

Body:
I am inside a SQLScript procedure and would like to return the last SQL Statement from this procedure, like the last rowcount:

/********* Begin Procedure Script ************/
BEGIN
    select 1 as "my_data" from dummy;
    select '::last_SQL' as "last executed sql" from dummy;
    select ::ROWCOUNT as "rowcount" from dummy;
END;
 /********* End Procedure Script ************/

The column "last executed SQL" should be populated with select 1 as "my_data" from dummy in this case. Is there any variable holding the last statement (or any easy way to retrieve the query plan)?

Body:
Maybe you can query sys.m_sql_plan_cache system view

Please check following SELECT statement

select
    statement_string, last_execution_timestamp
from SYS.M_SQL_PLAN_CACHE
where user_name = 'KODYAZ'
order by last_execution_timestamp desc;

I believe you can improve the query by introducing new filter criteria.


问:
Could not find Id of Hidden Text in javascript
This is my aspx page

```<code><telerik:GridTemplateColumn SortExpression="PrintColumn" DataField="PrintColumn" HeaderText=""
    HeaderStyle-Font-Bold="true">
    <ItemTemplate>
        <asp:HiddenField ClientIDMode="Static" ID="lblIDSIDPrint" runat="server" Value='<%# Eval("DSID") %>'/>
        <asp:HiddenField ID="lblDataDSPrint" runat="server" Value='<%# Eval("DataDS")%>'/>
        <asp:LinkButton Style="text-align: right; float: right;" ID="lbDSPrint" runat="server"
            OnClientClick="popWin">Print</asp:LinkButton>
    </ItemTemplate>
</telerik:GridTemplateColumn>
</code>```

This is my javascript

```<code>function popWin() {
    var Dsid = document.getElementById('<%=lblIDSIDPrint.ClientID %>').value;
    var DataDs = document.getElementById('<%=lblDataDSPrint.ClientID %>').value;
    alert(Dsid);
    alert(DataDs);
}
</code>```

But I am getting an error

"CS0103: The name 'lblIDSIDPrint' does not exist in the current context"

Any suggestions on this.

Body:
This is my aspx page

<telerik:GridTemplateColumn SortExpression="PrintColumn" DataField="PrintColumn" HeaderText=""
    HeaderStyle-Font-Bold="true">
    <ItemTemplate>
        <asp:HiddenField ClientIDMode="Static" ID="lblIDSIDPrint" runat="server" Value='<%# Eval("DSID") %>'/>
        <asp:HiddenField ID="lblDataDSPrint" runat="server" Value='<%# Eval("DataDS")%>'/>
        <asp:LinkButton Style="text-align: right; float: right;" ID="lbDSPrint" runat="server"
            OnClientClick="popWin">Print</asp:LinkButton>
    </ItemTemplate>
</telerik:GridTemplateColumn>

This is my javascript

function popWin() {
    var Dsid = document.getElementById('<%=lblIDSIDPrint.ClientID %>').value;
    var DataDs = document.getElementById('<%=lblDataDSPrint.ClientID %>').value;
    alert(Dsid);
    alert(DataDs);
}

But I am getting an error

"CS0103: The name 'lblIDSIDPrint' does not exist in the current context"

Any suggestions on this.

Body: try using $(document).find("#lblIDSIDPrint").val();


问:
add or union single object based on keys in an array of objects using lodash
I have created an array of object from the data from database. I wanted to plot data on pie chart but I am facing difficulties to make such format.

Below is the final result, I created so far:

```<code>let natinalityBreakdown = [
{Omani: Array(2), Pakistani: Array(2), Indian: Array(3), Test: Array(1)},
{Omani: Array(6), Chinese: Array(1)},
{Omani: Array(51), OMANi: Array(1), Pakistani: Array(5)}
];
</code>```

using below code:

```<code>let natinalityBreakdowna = [];
        _.forEach(company, function(company) {
          const linkedCompanyUsers= _(driver)
              .filter(d => d.companyId === company.companyId)
              .value();
           console.log(linkedCompanyUsers);
           let nationalityBreakdown = _.groupBy(linkedCompanyUsers, "nationality");
           console.log(nationalityBreakdown);
           nationalityBreakdown = _.omit(nationalityBreakdown, "undefined");
           console.log(nationalityBreakdown);
           natinalityBreakdowna.push(nationalityBreakdown);
        });
        console.log(natinalityBreakdowna);
</code>```

I wanted such result in object as below:

```<code>{Omani: Array(59), Pakistani: Array(7), Indian: Array(3), Test: Array(1), Chinese: Array(1), OMANi: Array(1)}
</code>```

Thanks

答:
You can use array#reduce to add the people of same nationality in same group using array#concat in an object.

```<code>var result = natinalityBreakdown.reduce(function(res, obj){
  Object.keys(obj).forEach(function(k){
    res[k] = res[k] || [];
    res[k] = res[k].concat(obj[k]);
 });
 return res;
},{});
</code>```

Body:
I have created an array of object from the data from database. I wanted to plot data on pie chart but I am facing difficulties to make such format.

Below is the final result, I created so far:

let natinalityBreakdown = [
{Omani: Array(2), Pakistani: Array(2), Indian: Array(3), Test: Array(1)},
{Omani: Array(6), Chinese: Array(1)},
{Omani: Array(51), OMANi: Array(1), Pakistani: Array(5)}
];

using below code:

let natinalityBreakdowna = [];
        _.forEach(company, function(company) {
          const linkedCompanyUsers= _(driver)
              .filter(d => d.companyId === company.companyId)
              .value();
           console.log(linkedCompanyUsers);
           let nationalityBreakdown = _.groupBy(linkedCompanyUsers, "nationality");
           console.log(nationalityBreakdown);
           nationalityBreakdown = _.omit(nationalityBreakdown, "undefined");
           console.log(nationalityBreakdown);
           natinalityBreakdowna.push(nationalityBreakdown);
        });
        console.log(natinalityBreakdowna);

I wanted such result in object as below:

{Omani: Array(59), Pakistani: Array(7), Indian: Array(3), Test: Array(1), Chinese: Array(1), OMANi: Array(1)}

Thanks

Body:
You can use array#reduce to add the people of same nationality in same group using array#concat in an object.

var result = natinalityBreakdown.reduce(function(res, obj){
  Object.keys(obj).forEach(function(k){
    res[k] = res[k] || [];
    res[k] = res[k].concat(obj[k]);
 });
 return res;
},{});