问:
Gulp destination relative to source
I am trying to parse all SCSS files in all folders, and I need them to be in relative destinations to the original file.

Here is the representation of folder structure I want (basically, scss files in scss folders need to be saved as css files in css folder next to the original scss folder) and rogue scss files (not in scss folder) should have css file saved in same destination as the scss file.

```<code>html
│   README.md
│
└───app_abc
│   │   index.php
│   │   something_else.php
│   │
│   └───styles
│       └───scss
│       │       _mixins.scss
│       │       layout.scss
│       │       content.scss
│       │
│       └───css
│               layout.css
│               content.css
│
└───app_def
│   │   index.php
│   │   something_else.php
│   │   rogue.scss
│   │   rogue.css
│   │
│   └───styles
│       └───scss
│       │       _mixins.scss
│       │       layout.scss
│       │       content.scss
│       │
│       └───css
│               layout.css
│               content.css
└───app_ghi
    ...
</code>```

I tried playing with it for hours yesterday and today, but to no avail. I can make it to create the CSS file in the same folder, but that's not what I want.

Here is my gulpfile.js (there is a lot of "debug" stuff in it).

```<code>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    path = require('path'),
    through = require('through2');

const debug = require('gulp-debug');

const sassFiles = './html/**/[^_]*.scss';

function parsePath() {
    return through.obj(function (file, enc, cb) {
        console.log(file.base);
        console.log(file.cwd);
        console.log(file.path);
        console.log(file.name);
        console.log(path.relative(file.cwd, file.path));
        console.log(path.relative(path.join(file.cwd, file.base), file.path))
        console.log(path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css'))
        console.log(file.path.replace(file.name, '').replace('scss', 'css'))
        cb();
    });
}

gulp.task('sass', function(){
  return gulp.src(sassFiles)
    .pipe(debug({title: 'test:', minimal: false}))
    .pipe(parsePath())
    .pipe(sass().on('error', sass.logError))
    //.pipe(gulp.dest('css'))
    //.pipe(gulp.dest(function (file) {
        //return file.path.replace('scss', 'css');
        //return path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css');
    //}))
    .pipe(gulp.dest(function (file) {
        console.log(file.base);
        return file.base;
    }));
});

gulp.task('watch', ['sass'], function(){
  gulp.watch(sassFiles, ['sass']);
})
</code>```

Thanks for any help.

Ps.: In any case it was needed, I am running on Debian Jessie x64.

Pps.: I did google and read quite a lot of stackoverflow threads, but none of them had a solution to my problem (well, if it had, it didn't work for me).

答:
This is working.  It handles your rogueSASS files correctly and creates a css folder where you want it with the css files in there.

IMPORTANT : The gulp.src files are relative to where your gulpfile.js is located.  For this code I have it in the HTML folder - at the same level as the app_xxx folders.  If you put it somewhere else you will have to modify the sassFiles and rogueSassFiles declarations.

```<code>var gulp = require("gulp");
var sass = require("gulp-sass");

// flatten can be useful to solve tricky long directory changes
// var flatten = require("gulp-flatten");

var rename = require("gulp-rename");
// var using = require("gulp-using");

const sassFiles = './**/styles/scss/*.scss';
const rogueSassFiles = ['./**/*.scss', '!./**/styles/**'];

gulp.task('watch', ['sass', 'rogueSASS'], function () {
  gulp.watch( sassFiles, ['sass']);
  gulp.watch( rogueSassFiles, ['rogueSASS']);
})

gulp.task('sass', function () {

  return gulp.src(sassFiles)
    .pipe(sass().on('error', sass.logError))

       // remove the "scss" folder name from the end of the directory list

    .pipe(rename(function (path) {
       var temp = path.dirname.slice(0, -4);
       path.dirname = temp + "css";
    }))

    .pipe(gulp.dest('.'))
})

gulp.task('rogueSASS', function () {

  return gulp.src(rogueSassFiles)
      //   gulp-using shows which files are getting through gulp.src !!
      //  .pipe(using())
   .pipe(sass().on('error', sass.logError))
   .pipe(gulp.dest('.'))
})
</code>```

These could be made into one task.

Title: Gulp destination relative to source

Body:
I am trying to parse all SCSS files in all folders, and I need them to be in relative destinations to the original file.

Here is the representation of folder structure I want (basically, scss files in scss folders need to be saved as css files in css folder next to the original scss folder) and rogue scss files (not in scss folder) should have css file saved in same destination as the scss file.

html
│   README.md
│
└───app_abc
│   │   index.php
│   │   something_else.php
│   │
│   └───styles
│       └───scss
│       │       _mixins.scss
│       │       layout.scss
│       │       content.scss
│       │
│       └───css
│               layout.css
│               content.css
│
└───app_def
│   │   index.php
│   │   something_else.php
│   │   rogue.scss
│   │   rogue.css
│   │
│   └───styles
│       └───scss
│       │       _mixins.scss
│       │       layout.scss
│       │       content.scss
│       │
│       └───css
│               layout.css
│               content.css
└───app_ghi
    ...

I tried playing with it for hours yesterday and today, but to no avail. I can make it to create the CSS file in the same folder, but that's not what I want.

Here is my gulpfile.js (there is a lot of "debug" stuff in it).

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    path = require('path'),
    through = require('through2');

const debug = require('gulp-debug');

const sassFiles = './html/**/[^_]*.scss';

function parsePath() {
    return through.obj(function (file, enc, cb) {
        console.log(file.base);
        console.log(file.cwd);
        console.log(file.path);
        console.log(file.name);
        console.log(path.relative(file.cwd, file.path));
        console.log(path.relative(path.join(file.cwd, file.base), file.path))
        console.log(path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css'))
        console.log(file.path.replace(file.name, '').replace('scss', 'css'))
        cb();
    });
}

gulp.task('sass', function(){
  return gulp.src(sassFiles)
    .pipe(debug({title: 'test:', minimal: false}))
    .pipe(parsePath())
    .pipe(sass().on('error', sass.logError))
    //.pipe(gulp.dest('css'))
    //.pipe(gulp.dest(function (file) {
        //return file.path.replace('scss', 'css');
        //return path.relative(path.join(file.cwd, file.base), file.path).replace('scss', 'css');
    //}))
    .pipe(gulp.dest(function (file) {
        console.log(file.base);
        return file.base;
    }));
});

gulp.task('watch', ['sass'], function(){
  gulp.watch(sassFiles, ['sass']);
})

Thanks for any help.

Ps.: In any case it was needed, I am running on Debian Jessie x64.

Pps.: I did google and read quite a lot of stackoverflow threads, but none of them had a solution to my problem (well, if it had, it didn't work for me).

Body:
This is working.  It handles your rogueSASS files correctly and creates a css folder where you want it with the css files in there.

IMPORTANT : The gulp.src files are relative to where your gulpfile.js is located.  For this code I have it in the HTML folder - at the same level as the app_xxx folders.  If you put it somewhere else you will have to modify the sassFiles and rogueSassFiles declarations.

var gulp = require("gulp");
var sass = require("gulp-sass");

// flatten can be useful to solve tricky long directory changes
// var flatten = require("gulp-flatten");

var rename = require("gulp-rename");
// var using = require("gulp-using");

const sassFiles = './**/styles/scss/*.scss';
const rogueSassFiles = ['./**/*.scss', '!./**/styles/**'];

gulp.task('watch', ['sass', 'rogueSASS'], function () {
  gulp.watch( sassFiles, ['sass']);
  gulp.watch( rogueSassFiles, ['rogueSASS']);
})

gulp.task('sass', function () {

  return gulp.src(sassFiles)
    .pipe(sass().on('error', sass.logError))

       // remove the "scss" folder name from the end of the directory list

    .pipe(rename(function (path) {
       var temp = path.dirname.slice(0, -4);
       path.dirname = temp + "css";
    }))

    .pipe(gulp.dest('.'))
})

gulp.task('rogueSASS', function () {

  return gulp.src(rogueSassFiles)
      //   gulp-using shows which files are getting through gulp.src !!
      //  .pipe(using())
   .pipe(sass().on('error', sass.logError))
   .pipe(gulp.dest('.'))
})

These could be made into one task.


来源: stackexchange

问:
why do I need to poll message hub?
I am looking at the node-js express example for message-hub on blue mix and am puzzled for why I need to poll message hub from my server. I thought that the whole idea behind a pub-sub model is that I don't have to (over) load my server polling the message service to find out if new messages exist for me to consume. In the example provided, lines 211-213 in the app.js file contain the following: </p>

```<code>  // Set up an interval which will poll Message Hub for
  // new messages on the 'livechat' topic.
  produceInterval = setInterval(function() { ...},250);
</code>```

<p>This now has my server polling message hub every 250 mSec when what I want is to completely avoid a polling model and be notified by message hub when a message exists for me to consume. </p>

答:
With KafkaConsumer the poll() function means that your app is polling the client buffer, not necessarily polling across the network to the Kafka broker. Kafka clients often prefetch and cache data in this client side buffer for better performance, lower latency, and better network efficiency.

If you want an async callback style interface that "pushes" data to your app then it's very easy to wrap the polling interface and make it look like a push. Ultimately every push API has something hidden under the covers that is calling poll on a tcp socket.

ContentLicense: CC BY-SA 3.0

Title: why do I need to poll message hub?

Body:
I am looking at the node-js express example for message-hub on blue mix and am puzzled for why I need to poll message hub from my server. I thought that the whole idea behind a pub-sub model is that I don't have to (over) load my server polling the message service to find out if new messages exist for me to consume. In the example provided, lines 211-213 in the app.js file contain the following:

  // Set up an interval which will poll Message Hub for
  // new messages on the 'livechat' topic.
  produceInterval = setInterval(function() { ...},250);

This now has my server polling message hub every 250 mSec when what I want is to completely avoid a polling model and be notified by message hub when a message exists for me to consume.


问:
In Typescript, define a type for an array where the first element is more specific than the rest
I would like to define a type for an array whose first element is a specific type (e.g. Function), and the remaining elements are the empty type. For example:

```<code>type FAs = [Function, {}, {}, {}, ...]; // pseudo code
</code>```

Is such a thing possible?

The purpose is to provide a single-argument function like this:

```<code>const myCaller = ([fun, ...args]: FAs) => fun.apply(args);
</code>```

An alternative approach would be to use two arguments to myCaller, like this:

```<code>const myCaller = (fun: Function, args: any[]) => fun.apply(args);
</code>```

but for aesthetic reasons I would prefer to use a single argument. I also wonder if the type system supports what is arguably an arbitrary-length tuple. Maybe such a thing is undesirable for computer science reasons I don't understand.

答:
I'm pretty sure this is the best you can do as of Typescript 2.3. You can see typings like this in lodash for example.</p>

```<code>interface IMyCaller {
  <R>([fn]: [() => R]): R;
  <R,A>([fn, a]: [(a: A) => R, A]): R;
  <R,A,B>([fn, a, b]: [(a: A, b: B) => R, A, B]): R;
  <R,A,B,C>([fn, a, b, c]: [(a: A, b: B, c: C) => R, A, B, C]): R;
  // keep adding these until you get tired
}

const myCaller: IMyCaller = ([fun, ...args]) => fun.apply(args);
</code>```

Body:
I would like to define a type for an array whose first element is a specific type (e.g. Function), and the remaining elements are the empty type. For example:

type FAs = [Function, {}, {}, {}, ...]; // pseudo code

Is such a thing possible?

The purpose is to provide a single-argument function like this:

const myCaller = ([fun, ...args]: FAs) => fun.apply(args);

An alternative approach would be to use two arguments to myCaller, like this:

const myCaller = (fun: Function, args: any[]) => fun.apply(args);

but for aesthetic reasons I would prefer to use a single argument. I also wonder if the type system supports what is arguably an arbitrary-length tuple. Maybe such a thing is undesirable for computer science reasons I don't understand.

Body:
I'm pretty sure this is the best you can do as of Typescript 2.3. You can see typings like this in lodash for example.

interface IMyCaller {
  <R>([fn]: [() => R]): R;
  <R,A>([fn, a]: [(a: A) => R, A]): R;
  <R,A,B>([fn, a, b]: [(a: A, b: B) => R, A, B]): R;
  <R,A,B,C>([fn, a, b, c]: [(a: A, b: B, c: C) => R, A, B, C]): R;
  // keep adding these until you get tired
}

const myCaller: IMyCaller = ([fun, ...args]) => fun.apply(args);


问:
Is asynchronous call of JavaScript function possible in Windows Script Host?
Imagine you have a simple function in Windows Script Host (JScript) environment:

```<code>function say(text) {
    WScript.Sleep(5000);
    WScript.Echo(text);
}
</code>```

Is it possible to call say() asynchronously?

Note: Such browser-based methods as setInterval() or setTimeout are not available in WSH.

答:
No, Windows Script Host doesn't support calling script functions asynchronously. You'll have to run two scripts simultaneously to achieve this effect:</p>

```<code>// [main.js]
var oShell = new ActiveXObject("WScript.Shell");
oShell.Run(WScript.FullName + " say.js Hello");

WScript.Echo("Hello from main");
</code>```

<p> </p>

```<code>// [say.js]
WScript.Sleep(5000);
WScript.Echo(WScript.Arguments.Item(0));
</code>```

Body:
Imagine you have a simple function in Windows Script Host (JScript) environment:

function say(text) {
    WScript.Sleep(5000);
    WScript.Echo(text);
}

Is it possible to call say() asynchronously?

Note: Such browser-based methods as setInterval() or setTimeout are not available in WSH.

Body:
No, Windows Script Host doesn't support calling script functions asynchronously. You'll have to run two scripts simultaneously to achieve this effect:

// [main.js]
var oShell = new ActiveXObject("WScript.Shell");
oShell.Run(WScript.FullName + " say.js Hello");

WScript.Echo("Hello from main");

// [say.js]
WScript.Sleep(5000);
WScript.Echo(WScript.Arguments.Item(0));

ContentLicense: CC BY-SA 2.5


问:
Apps Script - Send Email - Make content in email bold - Format result of Array.toString in bold
My code sends email notifications every time a Google Form is submitted.  It works, but I want the collected form data as bold in the email.</p>

```<code>for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

function sendFormByEmail(e)
{
  var s = SpreadsheetApp.getActiveSheet();
  var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var message = "";
  var data = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var subject = "";

  //Get active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var numRows = emails.getLastRow();
  var emailTo = emails.getRange(2, 2, numRows, 1).getValues();

  // The variable e holds all the form values in an array.
  // Loop through the array and append values to the body.

  for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

  // Insert variables from the spreadsheet into the subject.
  // In this case, I wanted the part number as part of the
  // email subject. These are the 3rd and 16th columns in my form.
  // This creates an email subject like "Parts Inquiry Submission: 729302"
  subject += e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail(emailTo, subject, message);

  // Based off of a script originally posted by Amit Agarwal - www.labnol.org
  // Credit to Henrique Abreu for fixing the sort order
}
</code>```

答:
First of all, you must use the advanced parameter htmlBody in the 4th parameter of sendEmail() and you need to make the body parameter and empty string.

sendEmail(recipient, subject, body, options)

Code:

```<code>message = "<strong>" + message + "</strong>";//Wrap message in bold tags

var options = {
  "htmlBody":message
}

// Send the email
MailApp.sendEmail(emailTo, subject, "",options);//Make email body empty string
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My code sends email notifications every time a Google Form is submitted.  It works, but I want the collected form data as bold in the email.

for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

function sendFormByEmail(e)
{
  var s = SpreadsheetApp.getActiveSheet();
  var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var message = "";
  var data = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
  var subject = "";

  //Get active Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  //Get Sheet called 'Form responses 1'
  var fr1 = ss.getSheetByName("Form responses 1");

  //Get all emails from 'Emails' tab
  var emails = ss.getSheetByName("Emails");
  var numRows = emails.getLastRow();
  var emailTo = emails.getRange(2, 2, numRows, 1).getValues();

  // The variable e holds all the form values in an array.
  // Loop through the array and append values to the body.

  for(var i in headers)
    message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";

  // Insert variables from the spreadsheet into the subject.
  // In this case, I wanted the part number as part of the
  // email subject. These are the 3rd and 16th columns in my form.
  // This creates an email subject like "Parts Inquiry Submission: 729302"
  subject += e.namedValues[headers[1]].toString();

  // Send the email
  MailApp.sendEmail(emailTo, subject, message);

  // Based off of a script originally posted by Amit Agarwal - www.labnol.org
  // Credit to Henrique Abreu for fixing the sort order
}

Body:
First of all, you must use the advanced parameter htmlBody in the 4th parameter of sendEmail() and you need to make the body parameter and empty string.

sendEmail(recipient, subject, body, options)

Code:

message = "<strong>" + message + "</strong>";//Wrap message in bold tags

var options = {
  "htmlBody":message
}

// Send the email
MailApp.sendEmail(emailTo, subject, "",options);//Make email body empty string


问:
How to set setContentView(); to GONE
I have my main layout which is, setContentView(R.layout.activity_detail),

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
</code>```

how do i set the visibility of my layout as GONE within the below code

```<code>   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }
</code>```

答:
Please do your operation like below. </p>

```<code>if (extras.get("NAME").equals("Blog")) {
    Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
    blog.putExtra("URL", "url");
    blog.putExtra("filename", "Blog");
    startActivity(blog);

    // I want to Perform the operation here...

    //Get the root view and hide...

    findViewById(android.R.id.content).setVisibility(View.GONE);
}
</code>```

Title: How to set setContentView(); to GONE

Body:
I have my main layout which is, setContentView(R.layout.activity_detail),

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

how do i set the visibility of my layout as GONE within the below code

   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }

Body:
Please do your operation like below.

if (extras.get("NAME").equals("Blog")) {
    Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
    blog.putExtra("URL", "url");
    blog.putExtra("filename", "Blog");
    startActivity(blog);

    // I want to Perform the operation here...

    //Get the root view and hide...

    findViewById(android.R.id.content).setVisibility(View.GONE);
}


问:
Manifest Merger failed with multiple errors in Android Studio
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs
</code>```

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

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

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}
</code>```

This is my AndroidManifest :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code>package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>
</code>```

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules

答:
If after you add a Android Library Module and you get this error.

You can fix it by simple remove the android:label="@string/app_name" from the AndroidManifest.xml of your Android Library Module

Body:
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error.

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

I found some solutions here and tried to implement them, but it did not work.

This is my build.gradle :

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
    applicationId "com.example.rohan.petadoptionthing"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
}

This is my AndroidManifest :

<?xml version="1.0" encoding="utf-8"?>

package="com.example.rohan.petadoptionthing" >

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Second"
        />

    <activity android:name=".third"/>
    <activity android:name=".MainActivity"/>

</application>

This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules


问:
EF one to one relationship, the property cannot be configured
An applicant has a notification, a notification has an applicant.

I am trying to implement this in EF, but I receive the following error:

"The property 'ApplicantID' cannot be configured as a navigation
  property. The property must be a valid entity type and the property
  should have a non-abstract getter and setter. For collection
  properties the type must implement ICollection where T is a valid
  entity type."

Not sure, what I am doing wrong.

Applicant

```<code>[Index]
[Key]
public int ApplicantID { get; set; }
public string ApplicantTitle { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Postcode { get; set; }
//fk
public int ApplicantNotificationID { get; set; }
public ApplicantNotification Notification { get; set; }
</code>```

ApplicantNotification

```<code>        [Index]
        public int ApplicantNotificationID { get; set; }
        public bool FirstNotification { get; set; }
        public bool SecondtNotification { get; set; }
        public bool ThirdNotification { get; set; }
        public bool FinalNotification { get; set; }
        public DateTime ReminderDate { get; set; }
        public int ReminderFrequency { get; set; }
        [DataType(DataType.Date)]
        public DateTime FirstNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime SecondNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime ThirdNotificationDate { get; set; }
        public bool IsArchive { get; set; }
        //FK
        public int ApplicantID { get; set; }

        //navigation property
        public Applicant Applicant { get; set; }
</code>```

答:
The error originated from absence of ForeignKeyAttribute annotation on the second table definition, even each table has navigation property for other table. Try setting the foreign key attribute on ApplicantNotification and mark navigation property on both tables as virtual like this:

```<code>[Table("Applicant")]
public class Applicant
{
    [Index]
    [Key]
    public int ApplicantID { get; set; }

    // other properties

    public virtual ApplicantNotification Notification { get; set; }
}

[Table("ApplicantNotification")]
public class ApplicantNotification
{
    [Index]
    [Key, ForeignKey("Applicant")]
    public int ApplicantNotificationID { get; set; }

    // other properties

    public virtual Applicant Applicant { get; set; }
}
</code>```

The purpose of one-to-one relationship is Applicant can be saved either with or without ApplicantNotification but ApplicantNotification requires Applicant to be exist when saving it (from tutorial).

Similar issue:

Entity framework Code First One-to-One relationship

Body:
An applicant has a notification, a notification has an applicant.

I am trying to implement this in EF, but I receive the following error:

"The property 'ApplicantID' cannot be configured as a navigation
  property. The property must be a valid entity type and the property
  should have a non-abstract getter and setter. For collection
  properties the type must implement ICollection where T is a valid
  entity type."

Not sure, what I am doing wrong.

Applicant

[Index]
[Key]
public int ApplicantID { get; set; }
public string ApplicantTitle { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Postcode { get; set; }
//fk
public int ApplicantNotificationID { get; set; }
public ApplicantNotification Notification { get; set; }

ApplicantNotification

        [Index]
        public int ApplicantNotificationID { get; set; }
        public bool FirstNotification { get; set; }
        public bool SecondtNotification { get; set; }
        public bool ThirdNotification { get; set; }
        public bool FinalNotification { get; set; }
        public DateTime ReminderDate { get; set; }
        public int ReminderFrequency { get; set; }
        [DataType(DataType.Date)]
        public DateTime FirstNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime SecondNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime ThirdNotificationDate { get; set; }
        public bool IsArchive { get; set; }
        //FK
        public int ApplicantID { get; set; }

        //navigation property
        public Applicant Applicant { get; set; }

Body:
The error originated from absence of ForeignKeyAttribute annotation on the second table definition, even each table has navigation property for other table. Try setting the foreign key attribute on ApplicantNotification and mark navigation property on both tables as virtual like this:

[Table("Applicant")]
public class Applicant
{
    [Index]
    [Key]
    public int ApplicantID { get; set; }

    // other properties

    public virtual ApplicantNotification Notification { get; set; }
}

[Table("ApplicantNotification")]
public class ApplicantNotification
{
    [Index]
    [Key, ForeignKey("Applicant")]
    public int ApplicantNotificationID { get; set; }

    // other properties

    public virtual Applicant Applicant { get; set; }
}

The purpose of one-to-one relationship is Applicant can be saved either with or without ApplicantNotification but ApplicantNotification requires Applicant to be exist when saving it (from tutorial).

Similar issue:

Entity framework Code First One-to-One relationship


问:
Can't connect to MySQL Workbench server with XAMPP installed
I was using MySQL Workbench 5.7 about a year ago, and since then I have used XAMPP. 1.8.3 and Microsoft Management Sever 2017. Recently, I updated to workbench 6.3

I can't get the server started on workbench even though I am using port 3307 and the phpMyAdmin for is using port 3306. When I start the instance on workbench and try to start the server I get

```<code>Can't connect to MySQL server on '127.0.0.1' (10061) (2003)
</code>```

There is no password because in the XAMPP > mysql > bin the my.ini file looks like this:

```<code># password       = your_password
 port            = 3306
 socket          = "C:/xampp/mysql/mysql.sock"
</code>```

I can't find a similar file in the program files for workbench.

答: I found a solution to the problem. I switched to port 3306 on MySQL workbench and used the password for MySQL in XAMPP and then start the server on XAMPP. </p>

Body:
I was using MySQL Workbench 5.7 about a year ago, and since then I have used XAMPP. 1.8.3 and Microsoft Management Sever 2017. Recently, I updated to workbench 6.3

I can't get the server started on workbench even though I am using port 3307 and the phpMyAdmin for is using port 3306. When I start the instance on workbench and try to start the server I get

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

There is no password because in the XAMPP > mysql > bin the my.ini file looks like this:

# password       = your_password
 port            = 3306
 socket          = "C:/xampp/mysql/mysql.sock"

I can't find a similar file in the program files for workbench.


问:
Position of two closest points on the lines
I have found algorithm to calculate shortest distance between two lines in 3D and rewrite it in Python.But also I would like to enchanced it that it could return not only distance,but also the postion of closest points.

```<code>def line2line(-0.073455669 4.9843092 0.26107353 0.0 0.0 -1.0 -3.85838175 12.1999998 -4.50372314 0.405142069 -0.76723671 0.497199893):
    epsilon = 0.00000001
    L1P0 = np.array([xbeam,ybeam,zbeam]) #position of P0 on first line
    L2P0= np.array([xout,yout,zout]) #position of P0 on first line
    L1P1 = np.array([xbeam + ubeam ,ybeam + vbeam ,zbeam + wbeam]) #ubeam,vbeam and wbeam are direction cosines
    L2P1 = np.array([xout + cx,yout + cy,zout + cz]) #cx,cy,cz are direction cosines
    u = L1P1 - L1P0
    v = L2P1 - L2P0
    w = L1P0 - L2P0
    a = np.dot(u,u)
    b = np.dot(u,v)
    c = np.dot(v,v)
    d = np.dot(u,w)
    e = np.dot(v,w)
    D = a*c - b*b
    if D < epsilon:
        sc = 0.0
        tc = d/b if b>c else e/c
    else:
        sc = (b*e - c*d) / D
        tc = (a*e - b*d) / D
    dP = w + (sc * u) - (tc * v)
    return np.linalg.norm(dP)
</code>```

It returns around 0.049 which is correct but when I tried to print
    w + (sc * u) or
    (tc * v) what I was thinking it was position,it printed me:

```<code>0.        ,   0.        , -19.82274615
3.8142822 , -7.22328672,  4.68097699
</code>```

It's not correct.Coordinates I'm looking for for one of these points are:

```<code>-0.073455669 4.9843092 0.26107353
</code>```

Algorithm I have found here

答:
dP is difference vector. But you need absolute coordinates of the closest points

I cannot open linked page, but seems that sc is parameter for the first line parametric equation and tc is parameter for the second line. In this case

```<code>ClosestPointAtFirst = L1P0 + sc * u
ClosestPointAtSecond = L2P0 + tc * v
</code>```

Body:
I have found algorithm to calculate shortest distance between two lines in 3D and rewrite it in Python.But also I would like to enchanced it that it could return not only distance,but also the postion of closest points.

def line2line(-0.073455669 4.9843092 0.26107353 0.0 0.0 -1.0 -3.85838175 12.1999998 -4.50372314 0.405142069 -0.76723671 0.497199893):
    epsilon = 0.00000001
    L1P0 = np.array([xbeam,ybeam,zbeam]) #position of P0 on first line
    L2P0= np.array([xout,yout,zout]) #position of P0 on first line
    L1P1 = np.array([xbeam + ubeam ,ybeam + vbeam ,zbeam + wbeam]) #ubeam,vbeam and wbeam are direction cosines
    L2P1 = np.array([xout + cx,yout + cy,zout + cz]) #cx,cy,cz are direction cosines
    u = L1P1 - L1P0
    v = L2P1 - L2P0
    w = L1P0 - L2P0
    a = np.dot(u,u)
    b = np.dot(u,v)
    c = np.dot(v,v)
    d = np.dot(u,w)
    e = np.dot(v,w)
    D = a*c - b*b
    if D < epsilon:
        sc = 0.0
        tc = d/b if b>c else e/c
    else:
        sc = (b*e - c*d) / D
        tc = (a*e - b*d) / D
    dP = w + (sc * u) - (tc * v)
    return np.linalg.norm(dP)

It returns around 0.049 which is correct but when I tried to print
    w + (sc * u) or
    (tc * v) what I was thinking it was position,it printed me:

0.        ,   0.        , -19.82274615
3.8142822 , -7.22328672,  4.68097699

It's not correct.Coordinates I'm looking for for one of these points are:

-0.073455669 4.9843092 0.26107353

Algorithm I have found here

Body:
dP is difference vector. But you need absolute coordinates of the closest points

I cannot open linked page, but seems that sc is parameter for the first line parametric equation and tc is parameter for the second line. In this case

ClosestPointAtFirst = L1P0 + sc * u
ClosestPointAtSecond = L2P0 + tc * v


问:
How do I forcefully close a connection from a connection pool when it's taking too much time to close?
There are times closing connections takes a lot of time, like more than 10 minutes upto 1 hour, or worse, even for indefinite time, depending on how heavy or slow the query was.

In a situation where the client cancels the query because it has been taking too much time, I would want to free up the underlying connection used as soon as possible.

I tried cancelling the PreparedStatement, closing it, then closing the resultset, and then finally closing the connection. Cancelling took almost instantly. Closing the PreparedStatement and ResultSet took too much time that I had to wrap it in a Callable with timeout to skip that process in due time and proceed with closing the connection itself. I haven't got any much luck on what else to try out.

How do I deal with this? I can't simply let the connections unclosed and I can't let the users wait for 10 minutes before they can make another similar query.

Also, what's causing the closure of connection to take too much time? Is there anything else I could do? Do you think Oracle query hints would help?

I'm using Oracle JDBC via thin type of driver by the way.

UPDATE:

Apparently, it's possible to close the connection forcefully by configuring TimeToLive property in the connectionCacheProperties which closes the connection for a specific amount of time. However, what I need is on as-needed basis. This is worth mentioning because this proves that it is possible to forcefully close it as the Connection Pool just did. In fact, I even got the following message on my logs.

```<code>ORA-01013: user requested cancel..
</code>```

答:
Main function:

```<code>  String g_sid = "";
</code>```

Thread 1:

```<code>  String sql = ...;
  Connection conn = ...your connection func...;

  Statement stmt = conn.createStatement();
  ResultSet rset = stmt.executeQuery( "SELECT sid from v$mystat");
  if (rset.next()) g_sid = rset.getString("sid");
  rset.close();
  // now to the actual long-running SQL
  ResultSet rset = stmt.executeQuery( sql );
  //
  stmt.close();
</code>```

Thread 2:

```<code>  String serialN = "";
  Connection conn = ...your admin connection func...

  Statement stmt = conn.createStatement();
  ResultSet rset = stmt.executeQuery( "SELECT serial# serialN from v$session where sid=" + g_sid );
  if (rset.next()) {
    serialN = rset.getString("serialN");
    stmt.execute("alter system kill session '" + g_sid + "," + serialN + "'");
  }
  stmt.close();
  // probably keep the admin connection open for further maintenance
  //
</code>```

Body:
There are times closing connections takes a lot of time, like more than 10 minutes upto 1 hour, or worse, even for indefinite time, depending on how heavy or slow the query was.

In a situation where the client cancels the query because it has been taking too much time, I would want to free up the underlying connection used as soon as possible.

I tried cancelling the PreparedStatement, closing it, then closing the resultset, and then finally closing the connection. Cancelling took almost instantly. Closing the PreparedStatement and ResultSet took too much time that I had to wrap it in a Callable with timeout to skip that process in due time and proceed with closing the connection itself. I haven't got any much luck on what else to try out.

How do I deal with this? I can't simply let the connections unclosed and I can't let the users wait for 10 minutes before they can make another similar query.

Also, what's causing the closure of connection to take too much time? Is there anything else I could do? Do you think Oracle query hints would help?

I'm using Oracle JDBC via thin type of driver by the way.

UPDATE:

Apparently, it's possible to close the connection forcefully by configuring TimeToLive property in the connectionCacheProperties which closes the connection for a specific amount of time. However, what I need is on as-needed basis. This is worth mentioning because this proves that it is possible to forcefully close it as the Connection Pool just did. In fact, I even got the following message on my logs.

ORA-01013: user requested cancel..

Body:
Main function:

  String g_sid = "";

Thread 1:

  String sql = ...;
  Connection conn = ...your connection func...;

  Statement stmt = conn.createStatement();
  ResultSet rset = stmt.executeQuery( "SELECT sid from v$mystat");
  if (rset.next()) g_sid = rset.getString("sid");
  rset.close();
  // now to the actual long-running SQL
  ResultSet rset = stmt.executeQuery( sql );
  //
  stmt.close();

Thread 2:

  String serialN = "";
  Connection conn = ...your admin connection func...

  Statement stmt = conn.createStatement();
  ResultSet rset = stmt.executeQuery( "SELECT serial# serialN from v$session where sid=" + g_sid );
  if (rset.next()) {
    serialN = rset.getString("serialN");
    stmt.execute("alter system kill session '" + g_sid + "," + serialN + "'");
  }
  stmt.close();
  // probably keep the admin connection open for further maintenance
  //


问:
javascript modify css class property while knowing only the class' name
Here's my css class:

```<code>.my-css-class-name
{
    display: block;
}
</code>```

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.

答: Some newer browsers support document.getElementsByClassName right out of the box. Older browsers do not and you have to use a function that loops through the elements of the page.</p>

Body:
Here's my css class:

.my-css-class-name
{
    display: block;
}

And I have one element at my webpage that uses this class. I want to modify this element's "display" property.

I would happily do this by getting a handle to that element and then modifying what I need, BUT, I don't know the element's name - it's being randomly generated (it's a third-party extension).

So I figured I'm gonna have to get a handle to ".my-css-class-name" and modify that property directly.

How do I get there, cross-browser (major ones) solution?

Edit #1:

I'm looking for compatibility with newer browsers.


问:
Does storing Uploaded Files in Azure Web Applications FS harmpers multiples instaces deploy?
I heard a lot that Azure Web Applications uploaded content such as images or any files should be stored in Azure Storage service, not in the app File System.
But I would like to keep the solution simple and store those files into local file system.

Does storing images or any files on the application's local file system hampers somehow the application deployment with more than one instance?

答:
By storing files on the Web application, you're limiting your ability to scale.

The web server/app should do one thing: process your request and output the HTML.  Everything else should be handled elsewhere if you truly want to take advantage of cloud computing.  So for this instance you should store any files off the web app.

Now if you want to keep this as simple as possible and you're not overly concerned with achieving scale, there's really nothing wrong with your approach.  It's my understanding that Web Apps, don't actually spin up new virtual machines for you, or if they do, they replicate exactly what is on the VM.  For instance think about this -- if you had all your files stored on one VM and you spun up two new ones, you'd have to copy all those files over to the next two, and now you'd have to create a way to sync all the uploaded files among all your VMs.

I don't actually think you'd run into this problem with Azure Web Apps, but it i a problem that can arise if you're handling the VMs yourself or through an auto-scaling policy. You'll definitely run into the issue if you decide to spin up new web apps in different regions (Say the Ireland region to your EU customers get better performance - you'd now have two different locations where files could be uploaded to and you'd need to sync them as opposed to uploading them to Azure storage all along and keepin them centrally located)


问:
Running travis tests on remote server, synching with github
I'm working on a package which includes functionality to process large data sets (~TB) and generate intermediate data products (~10s GB) which our group uses for analysis.  I want to integrate travis-ci tests to this package, but obviously downloading all of that data is impossible; there also isn't any API for the travis servers to poke at it.  It is possible to have the travis tests run on our server instead of on travis; but to still update the status online and synch with github (i.e. the little travis badge/icon)?

答:
Would it suit your purposes to just test a small subset of your data? If that was the case you could just upload some extracts to Travis for testing?

If you want to test with all your data, you might be able to use Travis Enterprise for this, as it runs on your own infrastructure.

The build images that Travis Enterprise uses can be customised, so they could be configured to mount your data to perform testing.


问:
Finding pattern in string using indexof
Can someone tell me why this is an infinte loop?    </p>

```<code>private void splitBody()    {
        bodyparts=new Vector();
        String body = "<br />testtestest<br />fefefefefefefefefef<br />qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("<br />",previousIndex)!=-1) {
            int index=body.indexOf("<br />",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }
</code>```

答:
Change the last line to:</p>

```<code>previousIndex = index + 1;
</code>```

Title: Finding pattern in string using indexof

Body:
Can someone tell me why this is an infinte loop?

private void splitBody()    {
        bodyparts=new Vector();
        String body = "
testtestest
fefefefefefefefefef
qqqqqqqqqqqq";

        int previousIndex=0;
        while(body.indexOf("
",previousIndex)!=-1) {
            int index=body.indexOf("
",previousIndex);
            System.out.println(body.substring(previousIndex, index));
            bodyparts.addElement(body.substring(previousIndex, index));
            previousIndex=index;
        }
    }

Body:
Change the last line to:

previousIndex = index + 1;


问:
WCF Timeout issue?
I have a somewhat long-taking WCF-based process.  WCF service runs in Azure if its of any help.  The issue I believe has to do with timeouts:

1) Winforms client has the following .config setting in the binding section:

```<code> <wsHttpBinding>
  <binding name="XXX" closeTimeout="00:05:00" openTimeout="00:05:00"
   receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false"
   transactionFlow="false" hostNameComparisonMode="StrongWildcard"
   maxBufferPoolSize="10000000" maxReceivedMessageSize="10000000"
   messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
   allowCookies="false">
   <readerQuotas maxDepth="255" maxStringContentLength="8192" maxArrayLength="16384"
    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
   <reliableSession ordered="true" inactivityTimeout="00:10:00"
    enabled="false" />
   <security mode="TransportWithMessageCredential">
    <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
    <message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="false"/>
   </security>
  </binding>
 </wsHttpBinding>
</code>```

2) WCF service has the following binding section in the web.config

```<code>   <wsHttpBinding>
    <binding name="XXX" maxReceivedMessageSize="10000000" sendTimeout="00:10:00" receiveTimeout="00:10:00" closeTimeout="00:10:00" openTimeout="00:10:00">
     <security mode="TransportWithMessageCredential">
      <message clientCredentialType="UserName" establishSecurityContext="false" />
     </security>
     <readerQuotas maxArrayLength="2000000" maxBytesPerRead="10000000" maxStringContentLength="10000000" maxDepth="255" />
    </binding>

   </wsHttpBinding>
</code>```

3) I have one long-running method in WCF (generally 2 minutes).  Clients call the method, and those that execute for longer then 1 minute are getting thrown out with an exception. This is the most inner exception:

```<code>  <InnerException>
    <Type>System.Net.Sockets.SocketException</Type>
    <Message>An existing connection was forcibly closed by the remote host</Message>
    <StackTrace>
      <Frame>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</Frame>
    </StackTrace>
  </InnerException>
</InnerException>
</code>```

4) The WCF call itself completed successfully, however (I have both Start/End logged on server side).  How do I avoid the exception?

Thank you!

答:
Updated answer:

Azure load balancer terminates idle connections after 4 minutes. If you're interested in increasing/decreasing timeout value, check this article:

https://azure.microsoft.com/en-us/blog/new-configurable-idle-timeout-for-azure-load-balancer/

Title: WCF Timeout issue?

Body:
I have a somewhat long-taking WCF-based process.  WCF service runs in Azure if its of any help.  The issue I believe has to do with timeouts:

1) Winforms client has the following .config setting in the binding section:

 <wsHttpBinding>
  <binding name="XXX" closeTimeout="00:05:00" openTimeout="00:05:00"
   receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false"
   transactionFlow="false" hostNameComparisonMode="StrongWildcard"
   maxBufferPoolSize="10000000" maxReceivedMessageSize="10000000"
   messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
   allowCookies="false">
   <readerQuotas maxDepth="255" maxStringContentLength="8192" maxArrayLength="16384"
    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
   <reliableSession ordered="true" inactivityTimeout="00:10:00"
    enabled="false" />
   <security mode="TransportWithMessageCredential">
    <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
    <message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="false"/>
   </security>
  </binding>
 </wsHttpBinding>

2) WCF service has the following binding section in the web.config

   <wsHttpBinding>
    <binding name="XXX" maxReceivedMessageSize="10000000" sendTimeout="00:10:00" receiveTimeout="00:10:00" closeTimeout="00:10:00" openTimeout="00:10:00">
     <security mode="TransportWithMessageCredential">
      <message clientCredentialType="UserName" establishSecurityContext="false" />
     </security>
     <readerQuotas maxArrayLength="2000000" maxBytesPerRead="10000000" maxStringContentLength="10000000" maxDepth="255" />
    </binding>

   </wsHttpBinding>

3) I have one long-running method in WCF (generally 2 minutes).  Clients call the method, and those that execute for longer then 1 minute are getting thrown out with an exception. This is the most inner exception:

  <InnerException>
    <Type>System.Net.Sockets.SocketException</Type>
    <Message>An existing connection was forcibly closed by the remote host</Message>
    <StackTrace>
      <Frame>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</Frame>
    </StackTrace>
  </InnerException>
</InnerException>

4) The WCF call itself completed successfully, however (I have both Start/End logged on server side).  How do I avoid the exception?

Thank you!


问:
Implementing custom adapter within a fragment in android
I have a fragment in which I want to include a List of items. This item list must contain an image view and text view. Therefore I need a custom array adapter.
I am familiar with custom array adapter when used with Activities. As the activity java class can just extend the custom array adapter.

Since I am using fragments now, and the fragment java class extends 'Fragment' or "List Fragment" and Java does not support multiple inheritance, how do I use my custom array adapter withing my Fragment?

Couldn't find anything helpful online. please help if you know an easy way to do this!

答:
Use recycler view inside fragment and create one another class for recyclerview adapter.
Then attach the object of that class to recyclerview.
Here is how to use recyclerview : Recyclerview - Androidhive</p>


问:
Why does pushing to one array affect another?
Consider the following code snippet:

var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.reverse();
console.log(arr1); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'n', 'h', 'o', 'j', [ 'j', 'o', 'n', 'e', 's' ] ]```

In the last console.log, why does pushing to arr2 affect arr1? Why does arr1 change when it's not modified, only arr2 is modified?

答:
```<code>var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.slice().reverse();
console.log(arr2); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1);  // [ 'j', 'o', 'h', 'n' ]
console.log(arr2);  // [ 'n', 'h', 'o', 'j', ['j','o','n','e','s'] ]
</code>```

split() function return a new array.

reverse() function does not return a new array. So, arr1 is arr2.

push() function does not return a new array. So, arr1 and arr2 have added the arr3 as the last element.

Use slice() function to make a copy of your array.

References:

split function

reverse function

push function

Body:
Consider the following code snippet:

var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.reverse();
console.log(arr1); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1); // [ 'n', 'h', 'o', 'j', [ 'j', 'o', 'n', 'e', 's' ] ]

In the last console.log, why does pushing to arr2 affect arr1? Why does arr1 change when it's not modified, only arr2 is modified?

Body:
var arr1 = "john".split('');
console.log(arr1); // [ 'j', 'o', 'h', 'n' ]
var arr2 = arr1.slice().reverse();
console.log(arr2); // [ 'n', 'h', 'o', 'j' ]
var arr3 = "jones".split('');
arr2.push(arr3);
console.log(arr1);  // [ 'j', 'o', 'h', 'n' ]
console.log(arr2);  // [ 'n', 'h', 'o', 'j', ['j','o','n','e','s'] ]

split() function return a new array.

reverse() function does not return a new array. So, arr1 is arr2.

push() function does not return a new array. So, arr1 and arr2 have added the arr3 as the last element.

Use slice() function to make a copy of your array.

References:

split function

reverse function

push function


问:
Why a timezone aware datetime's tzinfo does not equal the timezone?
```<code>>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False
</code>```

What's the reason for these to differ?

```<code>>>> dt_aware.tzinfo
<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>
</code>```

答:
The key that determines the timezone from pytz is the string you passed to create the object: 'America/Chicago'. That key is available through the .zone attribute.

```<code>>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False
>>> tz.zone
'America/Chicago'
>>> dt_aware.tzinfo.zone == tz.zone
True
</code>```

Body:
>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False

What's the reason for these to differ?

>>> dt_aware.tzinfo
<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>

Body:
The key that determines the timezone from pytz is the string you passed to create the object: 'America/Chicago'. That key is available through the .zone attribute.

>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False
>>> tz.zone
'America/Chicago'
>>> dt_aware.tzinfo.zone == tz.zone
True


问:
Print (2) columns from powershell array
I created this array with:

```<code>$arecords = Get-DnsServerResourceRecord -ZoneName "mydomain.local" -RRType "A"
</code>```

If I do $arecords.HostName I get a list of the hostnames. If I do $arecords.RecordData I get a list of the IP's. How can print both columns AWK style? Like $arecords.Hostname.RecordData?

答:
The A records are CIM objects, and the default output formatting provided with the DnsServer module must know how to format them, but converting them to string just gets you the DnsServerResourceRecordA text.

You need to get the .RecordData.IPv4Address property out, with a calculated property, e.g.

```<code>$arecords| Select-Object -Property hostname, @{name='IP'; Expression={ $_.RecordData.IPv4Address }}
</code>```

aka

```<code>$arecords| select hostname, @{n='IP';E={$_.RecordData.IPv4Address}}
</code>```

Title: Print (2) columns from powershell array

Body:
I created this array with:

$arecords = Get-DnsServerResourceRecord -ZoneName "mydomain.local" -RRType "A"

If I do $arecords.HostName I get a list of the hostnames. If I do $arecords.RecordData I get a list of the IP's. How can print both columns AWK style? Like $arecords.Hostname.RecordData?

Body:
The A records are CIM objects, and the default output formatting provided with the DnsServer module must know how to format them, but converting them to string just gets you the DnsServerResourceRecordA text.

You need to get the .RecordData.IPv4Address property out, with a calculated property, e.g.

$arecords| Select-Object -Property hostname, @{name='IP'; Expression={ $_.RecordData.IPv4Address }}

aka

$arecords| select hostname, @{n='IP';E={$_.RecordData.IPv4Address}}


问:
ASP.NET Session identifier
I'm trying to make a session code for each client on my site. In the Session_Start of the global asax I have this code:

```<code>private static long codSesion = 0;
private static object codSesionLocker = new object();
protected void Session_Start(object sender, EventArgs e)
{
    if (Session["CodSesion"] == null)
    {
        lock (codSesionLocker)
        {
            if (Session["CodSesion"] == null)
            {
                if (codSesion == 9999)
                    codSesion = 0;
                codSesion++;
                Session["CodSesion"] = codSesion;
            }
        }

    }
}
</code>```

When I monitor this it seems to be perfect. After some time of inactivity starts the problems. One of the thing that happens is that too many times starts over from 1 (without reaching 9999 and without IIS rebouting). And recently, even worst than taht: I'd used the codes 1 and 2. I stop using the server (leting the IIS without activity). After almost 1 hour (50 minutes) I tried again. The code the IIS gave me was 2 (in a different PC than the last code 2).

Please I'd realy apreciate any help with this.

答:
After a certain period of inactivity, IIS will stop your application. Once somebody visits, the site will start again. Combine that with the fact that you're probably using In Processes Session State and that is why you are seeing the value reset.

You could try to use SqlServer to store the Session as described here so that the data is persisted:

MSDN - ASP.NET Session State

Even if that works, trying to use Session in this fashion is a bad idea. Depending on what you're trying to achieve, there is a better way to handle things.

Title: ASP.NET Session identifier

Body:
I'm trying to make a session code for each client on my site. In the Session_Start of the global asax I have this code:

private static long codSesion = 0;
private static object codSesionLocker = new object();
protected void Session_Start(object sender, EventArgs e)
{
    if (Session["CodSesion"] == null)
    {
        lock (codSesionLocker)
        {
            if (Session["CodSesion"] == null)
            {
                if (codSesion == 9999)
                    codSesion = 0;
                codSesion++;
                Session["CodSesion"] = codSesion;
            }
        }

    }
}

When I monitor this it seems to be perfect. After some time of inactivity starts the problems. One of the thing that happens is that too many times starts over from 1 (without reaching 9999 and without IIS rebouting). And recently, even worst than taht: I'd used the codes 1 and 2. I stop using the server (leting the IIS without activity). After almost 1 hour (50 minutes) I tried again. The code the IIS gave me was 2 (in a different PC than the last code 2).

Please I'd realy apreciate any help with this.


问:
How to make raycast ignore Trigger colliders?
I have a function that checks if a game object can see another game object without anything blocking its view:

```<code>public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?

答:
Layer mask operation is not required for this. You don't have to use layers if this is only to ignore Colliders marked as triggers. This operation is now built in with Unity 5.2 and above.

1.For 3D, pass QueryTriggerInteraction.Ignore to the Physics.Raycast function.

```<code>int layer = 1 << LayerMask.NameToLayer("Default");
Physics.Raycast(cameraRay, out hit, distance, layer, QueryTriggerInteraction.Ignore);
</code>```

2.For 2D, set Physics2D.queriesHitTriggers to false if you don't want it to detect triggers. Set it to true when you want it to detect triggers once again. Make sure to set it before calling the Physics2D.Raycast function.

Don't detect triggers:

```<code>Physics2D.queriesHitTriggers = false;
</code>```

Detect triggers:

```<code>Physics2D.queriesHitTriggers = true;
</code>```

Your are looking for the 2D version.

Note:

I have seen reports of this not working on some certain version of Unity which is a bug but I assume it is now fixed. If not then use layers as described by l1sten.

Body:
I have a function that checks if a game object can see another game object without anything blocking its view:

public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?

Body:
Layer mask operation is not required for this. You don't have to use layers if this is only to ignore Colliders marked as triggers. This operation is now built in with Unity 5.2 and above.

1.For 3D, pass QueryTriggerInteraction.Ignore to the Physics.Raycast function.

int layer = 1 << LayerMask.NameToLayer("Default");
Physics.Raycast(cameraRay, out hit, distance, layer, QueryTriggerInteraction.Ignore);

2.For 2D, set Physics2D.queriesHitTriggers to false if you don't want it to detect triggers. Set it to true when you want it to detect triggers once again. Make sure to set it before calling the Physics2D.Raycast function.

Don't detect triggers:

Physics2D.queriesHitTriggers = false;

Detect triggers:

Physics2D.queriesHitTriggers = true;

Your are looking for the 2D version.

Note:

I have seen reports of this not working on some certain version of Unity which is a bug but I assume it is now fixed. If not then use layers as described by l1sten.


问:
Row highlighting based on due date using php
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

```<code>//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}
</code>```

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?

答:
$diffThree->format('%d')

will return a string instead of an integer. In order to compare it correctly with other numbers (3 and 1 in your case) you need to convert it to an int:

(int) $diffThree->format('%d')
and

(int) $diffOne->format('%d')

Body:
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?


问:
Compare each column's contents with all other columns' contents and present matrix of match counts
Given this table:

I'd like to derive this table:

...sort of like a mileage chart in a map book.

I'm trying to create a cross-table comparison of the words in each of the columns, against all of the other columns' words, to show how many matches there are between them.

For instance, comparing Column 1 against Column2 might yield 4 matches. The yellow, bold outlined cells are the matches.

And here's how I count them:

I'm thinking there might be an 'easy' way to accomplish this using Power Query. Is there?

(Oh...and by the way...the solution I'm looking for should not expect a static number of input columns: i.e., it should accommodate for more columns or less columns to be used in the input comparison set.)

Thanks.

答:
No, there is no easy way, but it can be done.
However, I get different results. My interpretation of your logic is: for each column combination, the number of occurrences of each common word in 1 column must be multiplied with the number of occurrences in the other column.
These are my results:

And this is my query code:

```<code>let
    Source = Table1,
    ColumnNames = Table.ColumnNames(Source),
    Tabled = Table.FromColumns({ColumnNames}, type table[Columns = text]),
    AddedColumns2 = Table.AddColumn(Tabled, "Columns2", each ColumnNames, type {text}),
    ExpandedColumns2 = Table.ExpandListColumn(AddedColumns2, "Columns2"),
    CommonWords =
        Table.AddColumn(ExpandedColumns2,
                        "DistinctIntersect",
                        each if [Columns] = [Columns2]
                           then {}
                           else List.Distinct(List.Intersect({Table.Column(Source,[Columns]),
                                                              Table.Column(Source,[Columns2])}))),
    AddedCount =
        Table.AddColumn(CommonWords,
                        "Count",
                        (This) => List.Sum({0}&List.Transform(This[DistinctIntersect],
                                                   each List.Count(List.PositionOf(Table.Column(Source,This[Columns]),_,2)) *
                                                        List.Count(List.PositionOf(Table.Column(Source,This[Columns2]),_,2)))),
                       Int64.Type),
    RemovedColumns = Table.RemoveColumns(AddedCount,{"DistinctIntersect"}),
    PivotedColumn = Table.Pivot(RemovedColumns, List.Distinct(RemovedColumns[Columns2]), "Columns2", "Count")
in
    PivotedColumn
</code>```

Body:
No, there is no easy way, but it can be done.
However, I get different results. My interpretation of your logic is: for each column combination, the number of occurrences of each common word in 1 column must be multiplied with the number of occurrences in the other column.
These are my results:

And this is my query code:

let
    Source = Table1,
    ColumnNames = Table.ColumnNames(Source),
    Tabled = Table.FromColumns({ColumnNames}, type table[Columns = text]),
    AddedColumns2 = Table.AddColumn(Tabled, "Columns2", each ColumnNames, type {text}),
    ExpandedColumns2 = Table.ExpandListColumn(AddedColumns2, "Columns2"),
    CommonWords =
        Table.AddColumn(ExpandedColumns2,
                        "DistinctIntersect",
                        each if [Columns] = [Columns2]
                           then {}
                           else List.Distinct(List.Intersect({Table.Column(Source,[Columns]),
                                                              Table.Column(Source,[Columns2])}))),
    AddedCount =
        Table.AddColumn(CommonWords,
                        "Count",
                        (This) => List.Sum({0}&List.Transform(This[DistinctIntersect],
                                                   each List.Count(List.PositionOf(Table.Column(Source,This[Columns]),_,2)) *
                                                        List.Count(List.PositionOf(Table.Column(Source,This[Columns2]),_,2)))),
                       Int64.Type),
    RemovedColumns = Table.RemoveColumns(AddedCount,{"DistinctIntersect"}),
    PivotedColumn = Table.Pivot(RemovedColumns, List.Distinct(RemovedColumns[Columns2]), "Columns2", "Count")
in
    PivotedColumn


问:
How to put a UIView in a UITableView and It will be pinned on the bottom
I am trying to build a UITableView Controller, which will be my app's ABOUT information session.

At the bottom of the view, it will be reserved as circle menu. So I need a UIView with height of 200 there, when I drag a UIView to the controller, it always sit as a table cell.

As you can see, the red area always sit under the last table cell group, how to pin it on the bottom of the View Controller.

Thanks in advance.

答: Get UIView controller and put tableview instead of UITableViewController.  From side inspector drop UIView out of tqbleview.  And in inspector menu for UIView set auto resizing mask for UIView according. </p>


问:
Output text if there is no SKU in Woocommerce
I have a Woocommerce site. Some products have SKU and others don't. I found the code below online and it helps me with displaying the text when visitors arrive at my single product page.

Once there, they can select from the drop-down menus to see specific info, including SKU, for each product variation.

Some of my products don't have SKU.  How can I modify the code to display text (in the same place that SKU would have displayed) like "Please call us for part number".

```<code><div class="product_meta">

<?php do_action( 'woocommerce_product_meta_start' ); ?>

<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
    <span class="sku_wrapper"><?php esc_html_e( 'VSI Part Number:', 'woocommerce' ); ?> <span class="sku"><?php echo ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'Choose option(s) to display part number.', 'woocommerce' ); ?></span></span>

<?php endif; ?>

<?php echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>

<?php echo wc_get_product_tag_list( $product->get_id(), ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>

<?php do_action( 'woocommerce_product_meta_end' ); ?>
</code>```

答:
this is how to add custom fields after SKU in single product page.

```<code>/**
     * woocommerce_single_product_summary hook
     *
     * @hooked woocommerce_template_single_title - 5
     * @hooked woocommerce_template_single_price - 10
     * @hooked woocommerce_template_single_excerpt - 20
     * @hooked woocommerce_template_single_add_to_cart - 30
     * @hooked woocommerce_template_single_meta - 40
     * @hooked woocommerce_template_single_sharing - 50
 */
</code>```

The "in Stock" or "SKU" data is displayed by woocommerce_template_single_meta which have a priority of 40. Now you need to display your customs fields values just after. Then you can chose a priority of 45 for that purpose

Here is the code that is going to output your custom fields values in
  product pages under "SKU":

```<code>///////////////////////////////
add_action('woocommerce_single_product_summary', 'woo_display_custom_general_fields_values', 45);
    function woo_display_custom_general_fields_values() {
        global $product;

    echo '<span class="sku_wrapper">'. esc_html_e( 'VSI Part Number:', 'woocommerce' ); . '<span class="sku">'. ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'Choose option(s) to display part number.', 'woocommerce' ); .'</span></span>';
}
//////////////////////////////
</code>```

Body:
I have a Woocommerce site. Some products have SKU and others don't. I found the code below online and it helps me with displaying the text when visitors arrive at my single product page.

Once there, they can select from the drop-down menus to see specific info, including SKU, for each product variation.

Some of my products don't have SKU.  How can I modify the code to display text (in the same place that SKU would have displayed) like "Please call us for part number".

<?php do_action( 'woocommerce_product_meta_start' ); ?>

<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
    <?php esc_html_e( 'VSI Part Number:', 'woocommerce' ); ?> <?php echo ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'Choose option(s) to display part number.', 'woocommerce' ); ?>

<?php endif; ?>

<?php echo wc_get_product_category_list( $product->get_id(), ', ', '' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '' ); ?>

<?php echo wc_get_product_tag_list( $product->get_id(), ', ', '' . _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'woocommerce' ) . ' ', '' ); ?>

<?php do_action( 'woocommerce_product_meta_end' ); ?>

Body:
this is how to add custom fields after SKU in single product page.

/**
     * woocommerce_single_product_summary hook
     *
     * @hooked woocommerce_template_single_title - 5
     * @hooked woocommerce_template_single_price - 10
     * @hooked woocommerce_template_single_excerpt - 20
     * @hooked woocommerce_template_single_add_to_cart - 30
     * @hooked woocommerce_template_single_meta - 40
     * @hooked woocommerce_template_single_sharing - 50
 */

The "in Stock" or "SKU" data is displayed by woocommerce_template_single_meta which have a priority of 40. Now you need to display your customs fields values just after. Then you can chose a priority of 45 for that purpose

Here is the code that is going to output your custom fields values in
  product pages under "SKU":

///////////////////////////////
add_action('woocommerce_single_product_summary', 'woo_display_custom_general_fields_values', 45);
    function woo_display_custom_general_fields_values() {
        global $product;

    echo '<span class="sku_wrapper">'. esc_html_e( 'VSI Part Number:', 'woocommerce' ); . '<span class="sku">'. ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'Choose option(s) to display part number.', 'woocommerce' ); .'</span></span>';
}
//////////////////////////////


问:
Remove focus from Iframe on page load
I have an Iframe embedded like this:

```<code><iframe id="foo" src="http://www.something.com" style="width: 90%; height: 300px"></iframe>
</code>```

Each time the page loads focus gets lost from the top of the page and switches to this Iframe that is in the footer.I was wondering how can i remove the focus from this and make the page load "normally"?

Thanks!

Update: Yes, iframe is being loaded from another source (not the same domain)

答:
Well there is too much things we can do, for example on window load we scroll to the top with scrollTop function, ...etc
But with such methods, where we take off the focus and move back to the top  when the window is completely loaded, it will come with a glitch and no well effect.
After a while of thinking, and experiences, i come with that:

We remove the iframe with display:none, when the dom is ready. Next when the window is completely loaded, we bring it back. To do that efficienly, we write a style class like that:

```<code>    .display_none{
         display:none;
     }
</code>```

and we will add this class to our iframe, when the document is ready, and remove this class when the window is fully loaded. There is the code :

```<code>$(document).ready(function(){
    $("#myFrame").addClass("display_none");
    $(window).load(function(){
        $("#myFrame").removeClass("display_none");
    });
});
</code>```

Now there is a situation where this will not work! if the iframe is created and added with another script, then the dom may be loaded but not the iframe element itself (because the script may not have create it yet)! And that was the case in my case .

SOLUTION:
put the iframe in a container, let say a div container, and apply the method above to this container. All should work nickel! On dom load the div is hidden, next when the window is fully loaded, it restore it back! and you get your iframe, which will be loaded and get displayed. No glitch, and efficient.

Title: Remove focus from Iframe on page load

Body:
I have an Iframe embedded like this:

Each time the page loads focus gets lost from the top of the page and switches to this Iframe that is in the footer.I was wondering how can i remove the focus from this and make the page load "normally"?

Thanks!

Update: Yes, iframe is being loaded from another source (not the same domain)

Body:
Well there is too much things we can do, for example on window load we scroll to the top with scrollTop function, ...etc
But with such methods, where we take off the focus and move back to the top  when the window is completely loaded, it will come with a glitch and no well effect.
After a while of thinking, and experiences, i come with that:

We remove the iframe with display:none, when the dom is ready. Next when the window is completely loaded, we bring it back. To do that efficienly, we write a style class like that:

    .display_none{
         display:none;
     }

and we will add this class to our iframe, when the document is ready, and remove this class when the window is fully loaded. There is the code :

$(document).ready(function(){
    $("#myFrame").addClass("display_none");
    $(window).load(function(){
        $("#myFrame").removeClass("display_none");
    });
});

Now there is a situation where this will not work! if the iframe is created and added with another script, then the dom may be loaded but not the iframe element itself (because the script may not have create it yet)! And that was the case in my case .

SOLUTION:
put the iframe in a container, let say a div container, and apply the method above to this container. All should work nickel! On dom load the div is hidden, next when the window is fully loaded, it restore it back! and you get your iframe, which will be loaded and get displayed. No glitch, and efficient.


问:
What's an efficient way to perform operations with NA values in R?
I would like to perform operation on a data frame which ignores lines with NA values (However, I don't want to remove the rows with NA values, I still want them in the data frame). I have actually already managed to do this, but I am after a more computationally efficient method since mine is very, very slow.

Let's say for instance we have a data frame as follows:

```<code>Number    |   Object
  10      |   Car
  11      |   Book
  12      |   Pen
  13      |   Door
  NA      |   Computer
  14      |   Cup
  15      |   Book
</code>```

I wish to perform an operation on this data frame where I would like to access the previous/next Object in the data frame but only on the condition that the Number column does not have an NA value for that index. For example, let's say I am at index 4 in the Number column (which means that the 'Number' is 13 and the Object is Door), and I want to access the next object such that there is no NA value in the Number column. This means that since index 5 has NA in the Number column, I would instead go to index 6 since it has 14 in the Number column and therefore I will have Cup as the object instead of computer.

Now, as mentioned above, I've actually already implemented one such method to perform this task through basically using a combination of functions such as which() and min() and max() etc. but I am after a method/function which is much more computationally efficient since I have a lot of data to work with (the method I am using is very slow and inefficient since it needs to check through a large number of values). Is there a more computationally efficient way to accomplish this task? Thanks in advance.

答:
You can try:

```<code>a$Object[!is.na(a$Number)][i+1]
</code>```

where a is your dataframe and i is the index you are currently at.

Body:
I would like to perform operation on a data frame which ignores lines with NA values (However, I don't want to remove the rows with NA values, I still want them in the data frame). I have actually already managed to do this, but I am after a more computationally efficient method since mine is very, very slow.

Let's say for instance we have a data frame as follows:

Number    |   Object
  10      |   Car
  11      |   Book
  12      |   Pen
  13      |   Door
  NA      |   Computer
  14      |   Cup
  15      |   Book

I wish to perform an operation on this data frame where I would like to access the previous/next Object in the data frame but only on the condition that the Number column does not have an NA value for that index. For example, let's say I am at index 4 in the Number column (which means that the 'Number' is 13 and the Object is Door), and I want to access the next object such that there is no NA value in the Number column. This means that since index 5 has NA in the Number column, I would instead go to index 6 since it has 14 in the Number column and therefore I will have Cup as the object instead of computer.

Now, as mentioned above, I've actually already implemented one such method to perform this task through basically using a combination of functions such as which() and min() and max() etc. but I am after a method/function which is much more computationally efficient since I have a lot of data to work with (the method I am using is very slow and inefficient since it needs to check through a large number of values). Is there a more computationally efficient way to accomplish this task? Thanks in advance.

Body:
You can try:

a$Object[!is.na(a$Number)][i+1]

where a is your dataframe and i is the index you are currently at.


问:
compare the information between two matrices R
I have two matrices, one is generated out of the other by deleting some rows. For example:

```<code>m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]
</code>```

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

```<code>1, 3, 6
</code>```

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

答:
A possible way is to represent each row as a string:

```<code>x1 <- apply(m, 1, paste0, collapse = ';')
x2 <- apply(m1, 1, paste0, collapse = ';')
which(!x1 %in% x2)
# [1] 1 3 6
</code>```

Some benchmark with a large matrix using my solution and G. Grothendieck's solutions:

```<code>set.seed(123)
m <- matrix(rnorm(20000 * 5000), nrow = 20000)
m1 <- m[-sample.int(20000, 1000), ]

system.time({
    which(tail(!duplicated(rbind(m1, m)), nrow(m)))
})
#    user  system elapsed
# 339.888   2.368 342.204
system.time({
    x1 <- apply(m, 1, paste0, collapse = ';')
    x2 <- apply(m1, 1, paste0, collapse = ';')
    which(!x1 %in% x2)
})
#    user  system elapsed
# 395.428   0.568 395.955

system({
    n <- nrow(m); n1 <- nrow(m1)
    tm <- t(m); tm1 <- t(m1)

    match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
    setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
})
# > 15 min, not finish

system({
    i <- interaction(as.data.frame(m))
    i1 <- interaction(as.data.frame(m1))
    match(setdiff(i, i1), i)
})
# run out of memory. My 32G RAM machine crashed.
</code>```

Body:
I have two matrices, one is generated out of the other by deleting some rows. For example:

m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

1, 3, 6

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

Body:
A possible way is to represent each row as a string:

x1 <- apply(m, 1, paste0, collapse = ';')
x2 <- apply(m1, 1, paste0, collapse = ';')
which(!x1 %in% x2)
# [1] 1 3 6

Some benchmark with a large matrix using my solution and G. Grothendieck's solutions:

set.seed(123)
m <- matrix(rnorm(20000 * 5000), nrow = 20000)
m1 <- m[-sample.int(20000, 1000), ]

system.time({
    which(tail(!duplicated(rbind(m1, m)), nrow(m)))
})
#    user  system elapsed
# 339.888   2.368 342.204
system.time({
    x1 <- apply(m, 1, paste0, collapse = ';')
    x2 <- apply(m1, 1, paste0, collapse = ';')
    which(!x1 %in% x2)
})
#    user  system elapsed
# 395.428   0.568 395.955

system({
    n <- nrow(m); n1 <- nrow(m1)
    tm <- t(m); tm1 <- t(m1)

    match_indexes <- function(i) which(colSums(tm1[, i] == tm) == n1)
    setdiff(1:n, unlist(lapply(1:n1, match_indexes)))
})
# > 15 min, not finish

system({
    i <- interaction(as.data.frame(m))
    i1 <- interaction(as.data.frame(m1))
    match(setdiff(i, i1), i)
})
# run out of memory. My 32G RAM machine crashed.


答: I'm not sure if this explains all of the behavior you listed above, but by default, the application pool in IIS will recycle after a period of inactivity (these settings can be changed in IIS for each application pool).  When the application pool recycles, then the new instance of the pool will be completely reinitialized.</p>

Title: ASP.NET Session identifier


问:
Android ListView in Fragment not scrolling
I have a listView inside of a Fragment of my MainActivity that is rendered by a custom ArrayAdapter. The problem is that the listview cannot scroll for some reason.

My XML MainActivity:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:screenOrientation="portrait"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="#f1f1f1">

</FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    design:menu="@menu/navigation" />
</LinearLayout>
</code>```

My XML Fragment:

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="portrait"
    tools:context=".Friends">

<Button
    android:id="@+id/newfriendbutton"
    android:layout_width="0dp"
    android:layout_height="66dp"
    android:text="@string/new_friend"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintRight_creator="1"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintRight_toRightOf="parent"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView6"
    android:layout_width="395dp"
    android:layout_height="wrap_content"
    android:text="@string/instruct"
    android:textAlignment="center"
    app:layout_constraintTop_toBottomOf="@+id/newfriendbutton"
    tools:ignore="MissingConstraints"
    tools:layout_editor_absoluteX="8dp" />

<ListView
    android:id="@+id/friendListView"
    android:layout_width="match_parent"
    android:layout_height="592dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView6"
    tools:ignore="MissingConstraints"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1" />
</android.support.constraint.ConstraintLayout>
</code>```

答:
Are you sure that the ListView is full? It will only let you scroll if you have more options in the View than what can fit with the given constraints. It might work best to use a RelativeLayout in this case.   </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="portrait"
    tools:context=".Friends">

    <Button
        android:id="@+id/newfriendbutton"
        android:layout_height="66dp"
        android:text="@string/new_friend"
        android:layout_width="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/instruct"
        android:textAlignment="center"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/newfriendbutton"/>

    <ListView
        android:id="@+id/friendListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView6"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"/>
</RelativeLayout>
</code>```

Body:
I have a listView inside of a Fragment of my MainActivity that is rendered by a custom ArrayAdapter. The problem is that the listview cannot scroll for some reason.

My XML MainActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:screenOrientation="portrait"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="#f1f1f1">

</FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    design:menu="@menu/navigation" />
</LinearLayout>

My XML Fragment:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="portrait"
    tools:context=".Friends">

<Button
    android:id="@+id/newfriendbutton"
    android:layout_width="0dp"
    android:layout_height="66dp"
    android:text="@string/new_friend"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintRight_creator="1"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintRight_toRightOf="parent"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView6"
    android:layout_width="395dp"
    android:layout_height="wrap_content"
    android:text="@string/instruct"
    android:textAlignment="center"
    app:layout_constraintTop_toBottomOf="@+id/newfriendbutton"
    tools:ignore="MissingConstraints"
    tools:layout_editor_absoluteX="8dp" />

<ListView
    android:id="@+id/friendListView"
    android:layout_width="match_parent"
    android:layout_height="592dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView6"
    tools:ignore="MissingConstraints"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1" />
</android.support.constraint.ConstraintLayout>

Body:
Are you sure that the ListView is full? It will only let you scroll if you have more options in the View than what can fit with the given constraints. It might work best to use a RelativeLayout in this case.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="portrait"
    tools:context=".Friends">

    <Button
        android:id="@+id/newfriendbutton"
        android:layout_height="66dp"
        android:text="@string/new_friend"
        android:layout_width="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/instruct"
        android:textAlignment="center"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/newfriendbutton"/>

    <ListView
        android:id="@+id/friendListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView6"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"/>
</RelativeLayout>