问:
iOS Swift 3 WKWebView Progress Bar Not Displaying
I'm trying to create an iOS WebView app that loads a site and allows users to log in and make purchases. I'm trying to have a progress bar display when loading pages but the progress doesn't display at all and I'm not sure where I'm going wrong. I also have a pull to refresh view but without a progress bar I can't be sure this is working either. This is my code, any help would be much appreciated!</p>

```<code>import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
// Define Views
var webView: WKWebView!
var progressView: UIProgressView!

override func loadView() {
    // Load Initial WebView
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Create Progress View
    progressView = UIProgressView(progressViewStyle: .default)
    progressView.sizeToFit()
    let progressButton = UIBarButtonItem(customView: progressView)
    toolbarItems = [progressButton]
    navigationController?.isToolbarHidden = false
    //Set and Load Initial URL
    let url = URL(string: "https://shop.nygmarose.com/")!
    webView.load(URLRequest(url: url))
    // Set WebView Config
    webView.allowsBackForwardNavigationGestures = true
    webView.scrollView.isScrollEnabled = true
    webView.scrollView.bounces = true
    // Allow Scroll to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(ViewController.refreshWebView), for: UIControlEvents.valueChanged)
    webView.scrollView.addSubview(refreshControl)
    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}

func refreshWebView() {
    // On Scroll to Refresh, Reload Current Page
    webView.reload()
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    // Display Progress Bar While Loading Pages
    if keyPath == "estimatedProgress" {
        progressView.progress = Float(webView.estimatedProgress)
    }
}

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

答:
I have checked your code and it's working perfect, check here is the output

let me know for more.

Body:
I'm trying to create an iOS WebView app that loads a site and allows users to log in and make purchases. I'm trying to have a progress bar display when loading pages but the progress doesn't display at all and I'm not sure where I'm going wrong. I also have a pull to refresh view but without a progress bar I can't be sure this is working either. This is my code, any help would be much appreciated!

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
// Define Views
var webView: WKWebView!
var progressView: UIProgressView!

override func loadView() {
    // Load Initial WebView
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Create Progress View
    progressView = UIProgressView(progressViewStyle: .default)
    progressView.sizeToFit()
    let progressButton = UIBarButtonItem(customView: progressView)
    toolbarItems = [progressButton]
    navigationController?.isToolbarHidden = false
    //Set and Load Initial URL
    let url = URL(string: "https://shop.nygmarose.com/")!
    webView.load(URLRequest(url: url))
    // Set WebView Config
    webView.allowsBackForwardNavigationGestures = true
    webView.scrollView.isScrollEnabled = true
    webView.scrollView.bounces = true
    // Allow Scroll to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(ViewController.refreshWebView), for: UIControlEvents.valueChanged)
    webView.scrollView.addSubview(refreshControl)
    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}

func refreshWebView() {
    // On Scroll to Refresh, Reload Current Page
    webView.reload()
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    // Display Progress Bar While Loading Pages
    if keyPath == "estimatedProgress" {
        progressView.progress = Float(webView.estimatedProgress)
    }
}

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


来源: stackexchange

问:
How to set text to go over an image strictly in HTML?
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

```<code><!--Footer-->
                        <tr id="footer">
                        <td id="footer" style="font-family: 'Titillium Web', sans-serif;;-webkit-text-size-adjust:none;background-image: url" img url"" templates\uuaemail-foot.jpg";padding-left:="" 20px;padding-right:="" 20px;padding-top:="" 10px;padding-bottom:="" 20px;"="">
                        <table height="101" width="602">
                        <tbody>
                            <tr>
                                <td id="footer" style="font-size: 10px;color:white;" height="95" valign="top" width="600" align="center"><p><br></p><p class="style3"><strong><span style="font-size: 12px;">admissions.rutgers.edu<br></span></strong></p><p class="style3"><span class="style7"><span style="font-size: 8px;"><strong> University Undergraduate Admissions</strong>, Operations Center<br>©2017 , an equal opportunity, affirmative action institution.</span></span></p></td>
                            </tr>
                        </tbody>
                    </table>
                </td>
</code>```

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.

答:
HTML is a markup language, it does neither add functonality or style by itself.

There are tags there the browser places default values.

Eg.

```<code><footer> </footer>
</code>```

The most browser add automaticly:

```<code>footer {
    display: block;
}
</code>```

Or the h tag

```<code><h1></h1>
</code>```

The most browser set the default values like:

```<code>h1 {
    display: block;
    font-size: 2em;
    margin-top: 0.67em;
    margin-bottom: 0.67em;
    margin-left: 0;
    margin-right: 0;
    font-weight: bold;
}
</code>```

Every other style change has to be done by your self with css. You can also work with inline stlyes like:

```<code><h1 style="color:red;"> A red big text </h1>
</code>```

A good way to find more about default values and inline styles is: https://www.w3schools.com/

ContentLicense: CC BY-SA 3.0

Body:
I am writing an emailed newsletter, and need to set an image as the footer, with a few clickable links over it. I have figured it out using both HTML and CSS, but no matter where I searched I could not find a way to do this strictly using HTML. Can anyone help me out?

admissions.rutgers.edu

 University Undergraduate Admissions, Operations Center
©2017 , an equal opportunity, affirmative action institution.

Is what I currently have (with CSS styling)

update: My issue is that the email is widely sent to Ms Outlook 2016, which I have both heard and seen through testing that it does not process CSS styles very well. When I opened this code in Outlook, it showed the CSS styling commands at the top of the message, and did not apply it at all.

Body:
HTML is a markup language, it does neither add functonality or style by itself.

There are tags there the browser places default values.

Eg.

<footer> </footer>

The most browser add automaticly:

footer {
    display: block;
}

Or the h tag

<h1></h1>

The most browser set the default values like:

h1 {
    display: block;
    font-size: 2em;
    margin-top: 0.67em;
    margin-bottom: 0.67em;
    margin-left: 0;
    margin-right: 0;
    font-weight: bold;
}

Every other style change has to be done by your self with css. You can also work with inline stlyes like:

<h1 style="color:red;"> A red big text </h1>

A good way to find more about default values and inline styles is: https://www.w3schools.com/


问:
Joomla URL canonicalisation
Could somebody suggest the best way to redirect the non-www to the www in Joomla? I would normally do this in the .htaccess file but I'm unsure if it's the best way to do it with dynamic websites.

Many thanks
Shaun

答: i would do this via the .htaccess file its the best way as then Google will just index your www.xxx site.</p>

ContentLicense: CC BY-SA 2.5

Title: Joomla URL canonicalisation


问:
SSIS/SSAS How can I show Month.Year as time dimension?
I am building a database for some data to build a cube (SSAS) after. Until now everything is fine and works but I want to modify my time dimension. Since now I have a table with year, month and day and use it as dimension. But for my use it would be nice if the hierarchy is not just like (2016-->5-->20); instead I want to show month.year at the month level (in this example: 05.2016). I had no problems separating the date but I can`t find a solution to show this part or to combine the two columns in SSIS. Is there any possibility to do so or can I create this in SSAS while setting up the cube?

What I´ve found out is that with the cast and datepart command I can show the things I want in the SQL Server Manager but I am a newbie in MS SQL and don`t know how to save the calculations in a new column.

答: Add a MonthYear column to your dimension table and populate it with a derived column transformation in SSIS that concatenates the month and year columns.</p>

ContentLicense: CC BY-SA 4.0


问:
How to Bulk Insert from XLSX file extension?
Can anyone advise how to bulk insert from .xlsx file?

I tried the below query already:

```<code>BULK INSERT #EVB FROM 'C:\Users\summer\Desktop\Sample\premise.xlsx'
WITH (FIELDTERMINATOR = '\t', ROWTERMINATOR = '\n', FIRSTROW = 2);

SELECT * FROM #EVB
</code>```

I also tried with FIELDTERMINATOR like "**\t**",   "**,**",   "**;**",   "**|**", but this doesn't work either.

Unfortunately, there is no error message.

答: It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

Body:
Can anyone advise how to bulk insert from .xlsx file?

I tried the below query already:

BULK INSERT #EVB FROM 'C:\Users\summer\Desktop\Sample\premise.xlsx'
WITH (FIELDTERMINATOR = '\t', ROWTERMINATOR = '\n', FIRSTROW = 2);

SELECT * FROM #EVB

I also tried with FIELDTERMINATOR like "**\t**",   "**,**",   "**;**",   "**|**", but this doesn't work either.

Unfortunately, there is no error message.


问:
Unable to integrate OpenCV in android studio
I am trying to integrate openCV in Android studio for my latest project. I followed the following steps:

Imported new module ..\OpenCV-android-sdk\java\

Added dependancy OpenCVLibrary320

Changed compilesdk and targetsdk versions to 23 and buildToolsVersion to 25.0.0 in the build.gradle of OpenCVLibrary320

Copied the contents of ..\OpenCV-android-sdk\sdk\native to app\main\src\jniLibs (After creating a jni folder)

Wrote a snippet of code to test if it was working

But I got the error:

Error:Execution failed for task ':app:compileDebugNdk'.
     Error: Your project contains C++ files but it is not using a supported native build system.
  Consider using CMake or ndk-build integration with the stable Android Gradle plugin:
   https://developer.android.com/studio/projects/add-native-code.html
  or use the experimental plugin:
   https://developer.android.com/studio/build/experimental-plugin.html.

How can I fix this problem?

Note: In step 4, I created the jniLibs folder but it did not show up in the 'Android' view so I had to copy the contents to the jniLibs folder in the 'Project' view.

答:
Manualy add the jar file in the lib folder,

app -> libs ->  xyz.jar

This will also create duplicate jar issue, remove from the previous folder, because it gets compiled twice if you do not remove


问:
how to send on socket a vector<unsigned char>
Im trying to do a simple client tcp (I have a server already working).
I have defined 2 variables:

std::vector<unsigned char> buffer(1000);

std::vector<std::vector<unsigned char>> buff;
buffer I use it ot read chains of unsigned characters, when reading is done i store it on buff and I start reading again.
I have defined all the process of adress, port, etc and when it comes to send strings of buffer I have problems.
Here's what i tried so far:

```<code>while(!buff.empty()){
    // Sockets Layer Call: send(
    n = send(sockfd, buff.back(), buff.back.size(), 0);
    std::this_thread::sleep_for(std::chrono::milliseconds(delay)) ;
    buff.pop_back();

    if (n < 0){
        std::cout<<"ERROR writting to socket"<<std::endl;
        exit(1);
    }
}
</code>```

I tried adding (char *) , also reinterpret_cast, but noithing seems to work. Any clue?

Thanks

答:
Here's one way you could do it:</p>

```<code>   std::vector<std::vector<unsigned char>> buff;
   //...
   for (std::vector<std::vector<unsigned char>> i = buff.begin();
        i != buff.end(); ++i)
   {
     std::vector<char>::iterator next = i->begin();
     while (next != i->end())
     {
       // if you don't have std::distance, use i->end() - next
       n = send(sockfd, &(*next), std::distance(next, i->end()), 0);
       if (n < 0)
       {
         std::cout<<"ERROR writing to socket"<<std::endl;
           exit(1);
       }
       next += n;
       if (n != i->end())
       {
         std::this_thread::yield();
       }
     }
   }
</code>```

Body:
Im trying to do a simple client tcp (I have a server already working).
I have defined 2 variables:

std::vector<unsigned char> buffer(1000);

std::vector<std::vector<unsigned char>> buff;
buffer I use it ot read chains of unsigned characters, when reading is done i store it on buff and I start reading again.
I have defined all the process of adress, port, etc and when it comes to send strings of buffer I have problems.
Here's what i tried so far:

while(!buff.empty()){
    // Sockets Layer Call: send(
    n = send(sockfd, buff.back(), buff.back.size(), 0);
    std::this_thread::sleep_for(std::chrono::milliseconds(delay)) ;
    buff.pop_back();

    if (n < 0){
        std::cout<<"ERROR writting to socket"<<std::endl;
        exit(1);
    }
}

I tried adding (char *) , also reinterpret_cast, but noithing seems to work. Any clue?

Thanks

Body:
Here's one way you could do it:

   std::vector<std::vector<unsigned char>> buff;
   //...
   for (std::vector<std::vector<unsigned char>> i = buff.begin();
        i != buff.end(); ++i)
   {
     std::vector<char>::iterator next = i->begin();
     while (next != i->end())
     {
       // if you don't have std::distance, use i->end() - next
       n = send(sockfd, &(*next), std::distance(next, i->end()), 0);
       if (n < 0)
       {
         std::cout<<"ERROR writing to socket"<<std::endl;
           exit(1);
       }
       next += n;
       if (n != i->end())
       {
         std::this_thread::yield();
       }
     }
   }


问:
How to create gmail business user account using google API with PHP
I want to create a new gmail business user account in gmail using PHP.  When I run this code it will shows some message like Open the following link in your browser: with URL and asking for verification code. If I run the link in browser it will generate some random string. I got 403 error when I paste the random string in terminal for verification. Here is my code.

```<code><?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}
</code>```

My error

Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Not Authorized to access this resource/api" } ], "code": 403, "message": "Not Authorized to access this resource/api" } }

答:
Fatal error: Uncaught Google_Service_Exception:

```<code>{
   "error":{
      "errors":[
         {
            "domain":"global",
            "reason":"forbidden",
            "message":"Not Authorized to access this resource/api"
         }
      ],
      "code":403,
      "message":"Not Authorized to access this resource/api"
   }
}
</code>```

Means that the user you are authenticating with does not have access to an admin directory account

The Directory API lets you perform administrative operations on users, groups, organizational units, and devices in your account.

Solution: Login with a user who has access to the G suite account.

Body:
I want to create a new gmail business user account in gmail using PHP.  When I run this code it will shows some message like Open the following link in your browser: with URL and asking for verification code. If I run the link in browser it will generate some random string. I got 403 error when I paste the random string in terminal for verification. Here is my code.

<?php
require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

My error

Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Not Authorized to access this resource/api" } ], "code": 403, "message": "Not Authorized to access this resource/api" } }

Body:
Fatal error: Uncaught Google_Service_Exception:

{
   "error":{
      "errors":[
         {
            "domain":"global",
            "reason":"forbidden",
            "message":"Not Authorized to access this resource/api"
         }
      ],
      "code":403,
      "message":"Not Authorized to access this resource/api"
   }
}

Means that the user you are authenticating with does not have access to an admin directory account

The Directory API lets you perform administrative operations on users, groups, organizational units, and devices in your account.

Solution: Login with a user who has access to the G suite account.


问:
import error trying to install a package
When I try to install a package for python, the setup.py has the following lines:

```<code>import os, sys, platform
from distutils.core import setup, Extension
import subprocess
from numpy import get_include
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from Cython.Compiler.Options import get_directive_defaults
</code>```

and I tried to run python setup.py install in terminal but I received the following error:

Traceback (most recent call last):
File "setup.py", line  9, in <module>
from Cython.Compiler.Options import get_directive_defaults
ImportError: cannot import name 'get_directive_defaults'
```

I would really appreciate if you could let me know how to fix this.

答:
The setup.py file is using some fairly recent feature (Cython 0.25). Update Cython and you should be fine.

If you have doubts about how to update Cython, ask away.

Body:
When I try to install a package for python, the setup.py has the following lines:

import os, sys, platform
from distutils.core import setup, Extension
import subprocess
from numpy import get_include
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from Cython.Compiler.Options import get_directive_defaults

and I tried to run python setup.py install in terminal but I received the following error:

Traceback (most recent call last):
File "setup.py", line  9, in <module>
from Cython.Compiler.Options import get_directive_defaults
ImportError: cannot import name 'get_directive_defaults'

I would really appreciate if you could let me know how to fix this.


问:
Google Drive API statusCode=SIGN_IN_REQUIRED
I have problem with Google Drive.
After I'm clicking on dialog with email Im getting error:

```<code>statusCode=SIGN_IN_REQUIRED
</code>```

I resolved this problem by adding in gradle

```<code> debug {
            signingConfig signingConfigs.config
    }

signingConfigs {
    config {
        keyAlias '******'
        keyPassword '******'
        storeFile file('C:/Users/.android/debug.keystore')
        storePassword '******'
    }
}
</code>```

But the question is it is possible to work without this file and this options in gradle?

I'm pushing this code to repository and tests are failed in case of missing debug.keystore file.

Code will be published and I'm not sure can also share this debug.keystore file?

I know the easiest is to add this file in to directory app and change the path.

But maybe someone know better solution?

答:
You may want to check Authorizing and Using REST APIs which shows how to authorize with Google and use Google REST APIs when you want your app to access Google APIs with the user's Google account over HTTP. There are also given approaches that you may try for your app.

Check the following to authorize your Android app:

Configure build dependencies in your app's root-level build.gradle file.

Use the Google-Provided authorization UI for REST API access. Use the Auth.GoogleSignInApi method to give users of your Android app a Google-provided authorization UI that handles all of this.

Specify scopes by creating a GoogleSignInOptions object with the new scopes that you want to request by calling GoogleSignInOptions.Builder.requestScopes.

You can get an Android Account object as part of your Google Sign-In result, and you can later instantiate a GoogleAccountCredential object with it.

Use GoogleAccountCredential  and the client library for REST API access.

For more information, please also see Authorizing Android Apps.

Body:
I have problem with Google Drive.
After I'm clicking on dialog with email Im getting error:

statusCode=SIGN_IN_REQUIRED

I resolved this problem by adding in gradle

 debug {
            signingConfig signingConfigs.config
    }

signingConfigs {
    config {
        keyAlias '******'
        keyPassword '******'
        storeFile file('C:/Users/.android/debug.keystore')
        storePassword '******'
    }
}

But the question is it is possible to work without this file and this options in gradle?

I'm pushing this code to repository and tests are failed in case of missing debug.keystore file.

Code will be published and I'm not sure can also share this debug.keystore file?

I know the easiest is to add this file in to directory app and change the path.

But maybe someone know better solution?


问:
Custom directive is overriding scope
I have a custom directive as defined below (if you need controller let me know)

```<code>module.exports = angular.module('aah-yes-no-directive-module', [
  require('./yes-no.controller').name,
]).directive('aahYesNo', [function YesNoDirective() {

  return {
    restrict: 'A',
    templateUrl: 'partials/yes-no.template.html',
    require: ['aahYesNo', 'ngModel'],
    controller: 'aahYesNoController',
    controllerAs: 'ctrl',
    link: (scope, el, attrs, ctrls) => {
      let ctrl = ctrls[0],
        ngModelCtrl = ctrls[1];

      ctrl.init(ngModelCtrl, attrs.onValue, attrs.offValue);

      angular.element(el).children().addClass(attrs.size || '');
    },
    scope: {}
  };
}]);
</code>```

Why question is, why does it not update the $modelValue when it changes in the parent controller, or when $viewValue changes?

it is always undefined?

if i take out scope: {} it works, but seems to override the entire parent scope (?!)

答:
I have it working, I'm not sure exactly what I changed to fix it, but unfortunately wasn't either of the suggested reasons.

It was not working properly with scope: false, I suspect I had a typo somewhere and have ended up starting again and voila....thanks for the help though!

Title: Custom directive is overriding scope

Body:
I have a custom directive as defined below (if you need controller let me know)

module.exports = angular.module('aah-yes-no-directive-module', [
  require('./yes-no.controller').name,
]).directive('aahYesNo', [function YesNoDirective() {

  return {
    restrict: 'A',
    templateUrl: 'partials/yes-no.template.html',
    require: ['aahYesNo', 'ngModel'],
    controller: 'aahYesNoController',
    controllerAs: 'ctrl',
    link: (scope, el, attrs, ctrls) => {
      let ctrl = ctrls[0],
        ngModelCtrl = ctrls[1];

      ctrl.init(ngModelCtrl, attrs.onValue, attrs.offValue);

      angular.element(el).children().addClass(attrs.size || '');
    },
    scope: {}
  };
}]);

Why question is, why does it not update the $modelValue when it changes in the parent controller, or when $viewValue changes?

it is always undefined?

if i take out scope: {} it works, but seems to override the entire parent scope (?!)


问:
correct way to convert mysql to xml file with specific format
I'm very new to Mysql and want to convert a database table to xml format like this

```<code><Table_Name>
    <table_data id="1" file_path="d:\...." />
    <table_data id="2" file_path="d:\..." />
</Table_Name>
</code>```

I have tried this by using the below query but, I'm getting few row in the table.

```<code>SELECT   CONCAT('<Table_Name>',
   GROUP_CONCAT('<table_data id="', t.id, '" file_path="', t.path, '"/>'  SEPARATOR ''),
   '</Table_Name>')
        FROM Table_Name t
</code>```

答:
You can follow the procedures from this web site as was able to do so by following the steps but it uses php .
Link:http://www.mightywebdeveloper.com/coding/mysql-to-xml-php/

Body:
I'm very new to Mysql and want to convert a database table to xml format like this

<Table_Name>
    <table_data id="1" file_path="d:\...." />
    <table_data id="2" file_path="d:\..." />
</Table_Name>

I have tried this by using the below query but, I'm getting few row in the table.

SELECT   CONCAT('<Table_Name>',
   GROUP_CONCAT('<table_data id="', t.id, '" file_path="', t.path, '"/>'  SEPARATOR ''),
   '</Table_Name>')
        FROM Table_Name t


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
```<code>//...
public static void main(String[] args) {
        // TODO Auto-generated method stub

            String x = "yourstring";
            String pattern = "0123456789";
            String piece  = "";
            StringBuilder num = new StringBuilder();
           if(startsWithDigit(x)){
               for(int i = 0; i < x.length(); i++) {
                    piece = x.substring(i,i+1);
               if (pattern.indexOf(piece) >0){
                   num.append(piece) ;
               }
               else
                   break;
               }
          }
           System.out.println(num.toString());
          }
          static boolean startsWithDigit(String s) {
            return Pattern.compile("^[0-9]").matcher(s).find();
    }
</code>```

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}


答:
EDIT: I missed the fact that you were using mysql; this solution will not work in MySQL as MySQL does not support window functions; sorry about that.

I believe you can achieve the result you want using the OVER clause and a windowed function.

```<code>SELECT tasks, [shift], worker_ID,
    (ROW_NUMBER() OVER (PARTITION BY [shift], worker_ID ORDER BY tasks, [shift])) -1 AS num_occ
FROM Tasks
ORDER BY tasks;
</code>```

I don't actually understand the output table that you showed in your example, but this code does achieve that same result.

Title: count occurrences of values in a column conditioned to values in another column

Body:
I have a table with three columns: tasks, shift and worker_ID. A task in tasks can be performed by several workers in worker_ID.

tasks | shift | worker_ID
------|-------|----------
111   | 127   | 233
111   | 127   | 34
111   | 127   | 455
333   | 127   | 444
333   | 127   | 34
333   | 127   | 200
333   | 127   | 100
444   | 127   | 34
444   | 127   | 567
444   | 127   | 888
666   | 125   | 100
666   | 125   | 200
666   | 125   | 345
666   | 125   | 100
555   | 125   | 34
555   | 125   | 100
555   | 125   | 457

I would like to create an sql query to count the occurrences of each worker_ID in each specific shift to return the following additional column (num_occ):

tasks | shift | worker_ID | num_occ
------|-------|-----------|--------
111   | 127   | 233       |  0
111   | 127   | 34        |  0
111   | 127   | 455       |  0
333   | 127   | 444       |  0
333   | 127   | 34        |  1
333   | 127   | 200       |  0
333   | 127   | 100       |  0
444   | 127   | 34        |  2
444   | 127   | 567       |  0
444   | 127   | 888       |  0
666   | 125   | 100       |  0
666   | 125   | 200       |  0
666   | 125   | 345       |  0
666   | 125   | 100       |  1
555   | 125   | 34        |  0
555   | 125   | 100       |  2
555   | 125   | 457       |  0

Any help would be greatly appreciated.
Thanks

Body:
EDIT: I missed the fact that you were using mysql; this solution will not work in MySQL as MySQL does not support window functions; sorry about that.

I believe you can achieve the result you want using the OVER clause and a windowed function.

SELECT tasks, [shift], worker_ID,
    (ROW_NUMBER() OVER (PARTITION BY [shift], worker_ID ORDER BY tasks, [shift])) -1 AS num_occ
FROM Tasks
ORDER BY tasks;

I don't actually understand the output table that you showed in your example, but this code does achieve that same result.


问:
how to pass json encoded php variable as parameter in onclick event function in codeigniter
I have my code like this but the jquery is not giving response which writen in the bottom of the page in

```<code>    <tr><th>Hindu</th>
        <td><a href="javascript:void(0)" onclick="getIdies('<?php echo json_encode(explode(",",
                     $count[1 ]->OBCHinduOBC)); ?>')"><?php echo $count[1 ]->HinduOBC;?>
            </a></td>
   </tr>
</code>```

This is my jquery

```<code><sript>
function getIdies(values){
    $.each(values,function(key,value){
        alert(value);
    });
}
</script>
</code>```

The below  line gives output like

```<code><?php echo json_encode(explode(",", $count[1 ]->OBCHinduOBC)); ?>
output:   ["200","500","700","675","54","567","678","867"]
</code>```

答: Try putting explode(",", $count[1 ]->OBCHinduOBC) as a new variable before encoding it with json.</p>

Body:
I have my code like this but the jquery is not giving response which writen in the bottom of the page in

Hindu
        <a href="javascript:void(0)" onclick="getIdies('<?php echo json_encode(explode(",",
                     $count[1 ]->OBCHinduOBC)); ?>')"><?php echo $count[1 ]->HinduOBC;?>

This is my jquery

<sript>
function getIdies(values){
    $.each(values,function(key,value){
        alert(value);
    });
}
</script>

The below  line gives output like

<?php echo json_encode(explode(",", $count[1 ]->OBCHinduOBC)); ?>
output:   ["200","500","700","675","54","567","678","867"]


答:
if you're trying to send all vectors within a vector, you're more or less on the right track... your loop however will never terminate as you never pop the last element from buff

```<code>while(!buff.empty()){
    // Sockets Layer Call: send(
    n = send(sockfd, &(buff.back()[0]), buff.back().size(), 0);
    buff.pop_back();   // need to remove what you just sent?
    std::this_thread::sleep_for(std::chrono::milliseconds(delay)) ;

    if (n < 0){
        std::cout<<"ERROR writting to socket"<<std::endl;
        exit(1);
    }
}
</code>```

Title: how to send on socket a vector<unsigned char>

Body:
if you're trying to send all vectors within a vector, you're more or less on the right track... your loop however will never terminate as you never pop the last element from buff

while(!buff.empty()){
    // Sockets Layer Call: send(
    n = send(sockfd, &(buff.back()[0]), buff.back().size(), 0);
    buff.pop_back();   // need to remove what you just sent?
    std::this_thread::sleep_for(std::chrono::milliseconds(delay)) ;

    if (n < 0){
        std::cout<<"ERROR writting to socket"<<std::endl;
        exit(1);
    }
}


问:
jQuery and iframes and weird positioning: is there a workaround?
I've got a draggable thing outside an iframe, and a droppable target inside it. Here I've shown the iframe as containing a snippet of the HTML that is loaded by its src attribute.

```<code><div id="draggables">
  <img src="drag-me.gif">
</div>

<iframe src="iframe-src.html" id="iframe">
  <!-- HTML gubbins -->

  <div id="droppable"> </div>

  <!-- More HTML gubbins -->
</iframe>
</code>```

I use some jQuery (UI draggable/droppable) to do stuff:

```<code>$("#iframe").load(function() {
    var $this = $(this);
    var contents = $this.contents();

    contents.find('#droppable').droppable({
        drop: function (event, ui) { alert('dropped'); }
    });
    $('#draggables img').draggable();
});
</code>```

The draggables become draggable and the droppable is successfully a drop target. The problem is that the landing zone for the drop area is not where it is displayed on the screen. That is, the alert is fired when the draggable is dropped somewhere above the drop target, and not on the target itself.

A few tests I did suggest that the difference between where the target is on screen and where jQuery thinks it is is related to the vertical position of the iframe on the page, but I can't find a direct correlation. Does anyone know whether this problem has been investigated by anyone anywhere and, perchance, solved?

Failing that, can anyone suggest a way I may be able to load an external HTML file into my page without using an iframe and without the two pages' structures and styles interfering with one another? I'm considering loading the inner page directly and using javascript to draw page controls around it.

TIA
Altreus

答:
You're trying to access the parent element from within the child iframe.  I haven't personally tested it, but try to set context for your jquery selector.  Otherwise, it'll look only inside the current iFrame.</p>

```<code>$('#draggables img', parent).draggable();
</code>```

Body:
I've got a draggable thing outside an iframe, and a droppable target inside it. Here I've shown the iframe as containing a snippet of the HTML that is loaded by its src attribute.

I use some jQuery (UI draggable/droppable) to do stuff:

$("#iframe").load(function() {
    var $this = $(this);
    var contents = $this.contents();

    contents.find('#droppable').droppable({
        drop: function (event, ui) { alert('dropped'); }
    });
    $('#draggables img').draggable();
});

The draggables become draggable and the droppable is successfully a drop target. The problem is that the landing zone for the drop area is not where it is displayed on the screen. That is, the alert is fired when the draggable is dropped somewhere above the drop target, and not on the target itself.

A few tests I did suggest that the difference between where the target is on screen and where jQuery thinks it is is related to the vertical position of the iframe on the page, but I can't find a direct correlation. Does anyone know whether this problem has been investigated by anyone anywhere and, perchance, solved?

Failing that, can anyone suggest a way I may be able to load an external HTML file into my page without using an iframe and without the two pages' structures and styles interfering with one another? I'm considering loading the inner page directly and using javascript to draw page controls around it.

TIA
Altreus

Body:
You're trying to access the parent element from within the child iframe.  I haven't personally tested it, but try to set context for your jquery selector.  Otherwise, it'll look only inside the current iFrame.

$('#draggables img', parent).draggable();


问:
How can I specify units other than pixels in javascript using scrollTo, scrollTop etc.?
I have an entire website built using REMs instead of pixels.

The site is built to be 40% wider than the window, so 20% of the page is hidden on either side.

Consequently, I need to find a way to scroll horizontally when the page is loaded so that it will be centered.

The page is 140 rem wide, the window is 100rem wide.

So I could set scrollLeft to 20% or 20rem, but when I use:

```<code>document.body.scrollLeft = '20rem';
</code>```

it doesn't work. I've tried many other things with no luck.

Is it possible to use units other than pixels to control scrolling?

I would really prefer not to add an object to the page and have to scroll to the object.

答: Write a converter that takes REM values and converts them to pixels. Then just get the pixel value for a given REM value and throw the pixel value into the scroll function.</p>

Body:
I have an entire website built using REMs instead of pixels.

The site is built to be 40% wider than the window, so 20% of the page is hidden on either side.

Consequently, I need to find a way to scroll horizontally when the page is loaded so that it will be centered.

The page is 140 rem wide, the window is 100rem wide.

So I could set scrollLeft to 20% or 20rem, but when I use:

document.body.scrollLeft = '20rem';

it doesn't work. I've tried many other things with no luck.

Is it possible to use units other than pixels to control scrolling?

I would really prefer not to add an object to the page and have to scroll to the object.


问:
Can we change IONiC 3 badge icon style
I developed a hybrid app with IONIC 3 and I want to change the badge push notification ion of the app. Is it possible to change badge icon styling as showing in the sample Facebook icon?

Facebook sample badge icon:

答:
I think you are able to change the color of the badge in Android. iOS won't let you modify the badge at all. This is to be cohesive with their entire platform look.

This will let you work on badges in the application:
https://ionicframework.com/docs/components/#badges

This will let you work on the badges on the icon:

https://stackoverflow.com/a/41888608/5144902

Title: Can we change IONiC 3 badge icon style


问:
How do we implement in-app purchasing when the documentation is so inconsistent?
The official documentation is incredibly unclear when it comes how you’re supposed to be handling in-app billing.

For starters there are two versions of TrivialDrive:

github.com/googlesamples/android-play-billing

And then from the official docs:

developer.android.com/google/play/billing/billing_integrate.html

(here it says to import the IInAppBillingService.aidl file and use ServiceConnections / IInAppBillingService)

developer.android.com/training/play-billing-library/preparing-iab-app.html

(here it says to look at Trivial Drive v2, and also use compile 'com.android.billingclient:billing:dp-1' instead of importing the .aidl file, and to use BillingManager)

developer.android.com/training/in-app-billing/preparing-iab-app.html

(here it says to look at Trivial Drive, import the .aidl file, and use the IabHelper + associated listeners for everything instead)

Can anyone clarify why such a crucial part of the Android platform has different explanations for things all over the place? What's the intended / latest framework we need to be using? Which pieces are outdated? Which TrivialDrive should I be referencing?

答:
As discussed in In-app Billing Version Notes, In-app Billing API is versioned with each version offering additional features to your app. With this, you may want to first check for your In-app Billing version.

At run time, your app can query the Google Play Store app to determine what version of the API it supports and what features are available.

If you are using in-app billing version 3 or later, the version information is not directly returned by Google Play. Instead, you can check if Google Play supports the version of the In-app Billing API that you are using by sending an isBillingSupported request.

If the In-app Billing API version that you are using is earlier than version 3, the version information is returned in the API_VERSION key of the Bundle object passed in the sendBillingRequest method. For more information, see In-app Billing Service Interface.

If you're using In-app Billing version 3 API, use this TrivialDrive for the Version 3 API as stated in In-app Billing Overview. Otherwise, see migration considerations wherein it was stated that,

The In-app Billing Version 2 API was discontinued in January 2015. If you have an existing In-app Billing implementation that uses API Version 2 or earlier, you must migrate to In-app Billing Version 3.

Lastly, this documentation is a preview release of the Play Billing Library. For In-app Billing Version 3 API, you may want to use this as reference instead.

Hope that helps in clearing things up.


问:
How to get raw android camera sensor image data using JNI+OpenCV+NDK?
I am using camera2 api for my app which is based on Camera2Raw.

```<code>mRawImageReader = ImageReader.newInstance(largestRaw.getWidth(),
       largestRaw.getHeight(),ImageFormat.RAW_SENSOR, /*maxImages*/
</code>```

I have image from ImageReader.OnImageAvailableListener, Instead of saving DNG file,  I am passing its byte array to my native opencv function to process:

```<code>int w = image.getWidth();
int h = image.getHeight();
ByteBuffer buffer = planes[0].getBuffer();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
addShot(w, h, data);
image.close();
</code>```

and C++ function:

```<code>JNIEXPORT jboolean JNICALL addShot(JNIEnv* env, jobject obj, jint width, jint height, jbyteArray p_data)
   {
       jbyte* _p_data= env->GetByteArrayElements(p_data, 0);
       Mat srcBGR(height, width, CV_8UC3);
       Mat mdata(height, width, CV_8UC3, (unsigned char *)_p_data);
//        Mat tmp_mat= imdecode(mdata,1);
       cvtColor(mdata, srcBGR, CV_RGB2BGR);
       env->ReleaseByteArrayElements(p_data, _p_data, 0);
   }
</code>```

First. for making sure, I am trying to save as JPEG in c++ side. But The result has many green colors.

I think there is missing part in my c++ code.

Can anyone help for this?

答:
After capturing RAW image data, using simple OpenCV function reads from the buffer memory.

```<code>Mat mImageMat;
mImageMat = Imgcodecs.imdecode(new MatOfByte(data), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
</code>```

where, mImageMat is Mat class of Image Container.

Then, processing the image becomes simple.

Body:
I am using camera2 api for my app which is based on Camera2Raw.

mRawImageReader = ImageReader.newInstance(largestRaw.getWidth(),
       largestRaw.getHeight(),ImageFormat.RAW_SENSOR, /*maxImages*/

I have image from ImageReader.OnImageAvailableListener, Instead of saving DNG file,  I am passing its byte array to my native opencv function to process:

int w = image.getWidth();
int h = image.getHeight();
ByteBuffer buffer = planes[0].getBuffer();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
addShot(w, h, data);
image.close();

and C++ function:

JNIEXPORT jboolean JNICALL addShot(JNIEnv* env, jobject obj, jint width, jint height, jbyteArray p_data)
   {
       jbyte* _p_data= env->GetByteArrayElements(p_data, 0);
       Mat srcBGR(height, width, CV_8UC3);
       Mat mdata(height, width, CV_8UC3, (unsigned char *)_p_data);
//        Mat tmp_mat= imdecode(mdata,1);
       cvtColor(mdata, srcBGR, CV_RGB2BGR);
       env->ReleaseByteArrayElements(p_data, _p_data, 0);
   }

First. for making sure, I am trying to save as JPEG in c++ side. But The result has many green colors.

I think there is missing part in my c++ code.

Can anyone help for this?

Body:
After capturing RAW image data, using simple OpenCV function reads from the buffer memory.

Mat mImageMat;
mImageMat = Imgcodecs.imdecode(new MatOfByte(data), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);

where, mImageMat is Mat class of Image Container.

Then, processing the image becomes simple.


问:
How to replace a html tag with nsattribute in swift?
For eg. replace a  tag with bold font. So that it can be applied as attributed text to label, textfield or textview

答:
Try this extension. It will convert HTML string into NSAttributtedString. I also has the 0.75 ratio applied because of the fact that the default conversion increases all the font size

```<code>extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        html.beginEditing()
        html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: .init(rawValue: 0)) {
            (value, range, stop) in
            if let font = value as? UIFont {
                let resizedFont = font.withSize(font.pointSize * 0.75)
                html.addAttribute(NSFontAttributeName,
                                         value: resizedFont,
                                         range: range)
            }
        }
        html.endEditing()
        return html
    }
}
</code>```

Body:
Try this extension. It will convert HTML string into NSAttributtedString. I also has the 0.75 ratio applied because of the fact that the default conversion increases all the font size

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        html.beginEditing()
        html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: .init(rawValue: 0)) {
            (value, range, stop) in
            if let font = value as? UIFont {
                let resizedFont = font.withSize(font.pointSize * 0.75)
                html.addAttribute(NSFontAttributeName,
                                         value: resizedFont,
                                         range: range)
            }
        }
        html.endEditing()
        return html
    }
}


问:
Remove DIV dynamically with JQuery
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

```<code>$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
                        '<i class="fa fa-times" aria-hidden="true"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });
</code>```

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

```<code>$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});
</code>```

So my ask is: How can i insert between the square brackets the right identifier of the div?

答:
https://codepen.io/vino4all/pen/vZrQEX

Try this code.

```<code><button id="aggiungi">Click</button>
<div id="corsi"></div>
</code>```

Add a class attribute to the  tag.

```<code>var $count = 0;
$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default delBtn" id="eliminacorso['+$count+']" aria-label="Elimina"><span>X</span>' +
                        '<i class="fa fa-times" aria-hidden="false"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });

$('#corsi').on('click', '.delBtn', function() {
console.log('this :'+$(this));
  $count --;

  $(this).parent().parent().remove();
    });
</code>```

Notice the usage of on function.
It should be like below

```<code>$('#corsi').on('click', '.delBtn', fun);
</code>```

Title: Remove DIV dynamically with JQuery

Body:
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '
' +
                'Corso ' + $count +'' +
                '
' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '' +
                        '' +
                    '' +
                '
' +
            '
' +
        '');
    });

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});

So my ask is: How can i insert between the square brackets the right identifier of the div?

Body:
https://codepen.io/vino4all/pen/vZrQEX

Try this code.

<button id="aggiungi">Click</button>
<div id="corsi"></div>

Add a class attribute to the <a> tag.

var $count = 0;
$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default delBtn" id="eliminacorso['+$count+']" aria-label="Elimina"><span>X</span>' +
                        '<i class="fa fa-times" aria-hidden="false"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });

$('#corsi').on('click', '.delBtn', function() {
console.log('this :'+$(this));
  $count --;

  $(this).parent().parent().remove();
    });

Notice the usage of on function.
It should be like below

$('#corsi').on('click', '.delBtn', fun);


问:
Using more than 6 symbols available as default in ggplot2
I have 8 variables that I would like to plot on a PCAplot using ggplot. Ggplot will only let me use 6 by default.

I am aware of the function scale_shape_manual but I would like to find a way to change the ggplot setting so that it automatically apply to every plot.

I would like to avoid having to insert a "scale_shape_manual" specification for each of my plot. Is there a way to do that?

答:
Make your own function. For example,

```<code>my_ggplot <- function(...) {
  ggplot(...) + scale_color_distiller(palette = 2)
}

ggplot(mtcars, aes(qsec, hp, col = cyl)) + geom_point(size = 5)
</code>```

```<code>my_ggplot(mtcars, aes(qsec, hp, col = cyl)) + geom_point(size = 5)
</code>```

Body:
Make your own function. For example,

my_ggplot <- function(...) {
  ggplot(...) + scale_color_distiller(palette = 2)
}

ggplot(mtcars, aes(qsec, hp, col = cyl)) + geom_point(size = 5)

my_ggplot(mtcars, aes(qsec, hp, col = cyl)) + geom_point(size = 5)


问:
How to create two triangles with overlaying?
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.
</div>

<div class="shape">
  <div class="shape--1"></div>
  <div class="shape--2"></div>
</div>

<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.
</div></code>```

答:
Here I made a jsfiddle take a look   just with your answer I made some css changes. Hope it helps.</p>

```<code>.shape-1{
  width: 0;
  height: 0;
  border-top: 0 solid transparent;
  border-bottom: 160px solid transparent;
  border-left: 0vw solid green;
  border-right: 97vw solid green;
  position:relative;
  top: -130px;
}

.shape-2{
    width: 0;
    height: 0;
    border-top: 0 solid transparent;
    border-bottom:  130px solid transparent;
    border-left: 42vw solid yellow;
    border-right: 0vw solid yellow;
    position:relative;
    top:0px;
}

.header{
    position: absolute;
    z-index: 1;
}

<div class="shape">
  <div class="header">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam
    accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod?
  </div>
  <div class="shape-2"></div>
  <div class="shape-1"></div>
</div>
</code>```

Body:
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.

Body:
Here I made a jsfiddle take a look   just with your answer I made some css changes. Hope it helps.

.shape-1{
  width: 0;
  height: 0;
  border-top: 0 solid transparent;
  border-bottom: 160px solid transparent;
  border-left: 0vw solid green;
  border-right: 97vw solid green;
  position:relative;
  top: -130px;
}

.shape-2{
    width: 0;
    height: 0;
    border-top: 0 solid transparent;
    border-bottom:  130px solid transparent;
    border-left: 42vw solid yellow;
    border-right: 0vw solid yellow;
    position:relative;
    top:0px;
}

.header{
    position: absolute;
    z-index: 1;
}

<div class="shape">
  <div class="header">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam
    accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod?
  </div>
  <div class="shape-2"></div>
  <div class="shape-1"></div>
</div>


问:
Backtracking with Particle Filter
I have just implemented a particle filter for Indoor Tracking. It looks good but at some points the particles go in a room and are trapped there.

What's a smart way to do backtracking? I save the state of the particles for their last 10 movements.

Thank you

答:
It is completely normal that particles get distributed everywhere. Otherwise it is not a probabilistic approach. In addition, note that the particles are sampled based on the posterior probability at time t-1 and the current motion distribution. However, even if it is not recommended in filtering but you can restrict your research space in the sampling step.

For backtracking, you may use at each time t the same approach of fortracking, with changing only the direction of the velocity (on all axies). You can start from the state which maximise the probability distribution. Finaly, you compare the obtained trajectories (result of for/backtracking) and you decide based on the result which further filtering is needed to get the best result.

Title: Backtracking with Particle Filter


问:
R: adding an argument to match.call output
Say I have the following function in R:

```<code>tst <- function(x,y){
  foo <- match.call()
  print(foo)
}

tst(4,5)
</code>```

This gives tst(x = 4, y = 5). Awesome. Now, I want to add an argument.

```<code>tst <- function(x,y){
  foo <- match.call()
  foo[[length(foo)+1]] <- 6
  print(foo)
}

tst(4,5)
</code>```

This prints tst(x = 4, y = 5, 6), which is great. However, I need to add an argument name so that the function knows what to do with it. For example, I want it to be tst(x = 4, y = 5, z = 6). I tried simply foo[[length(foo)+1]] <- "z = 6", but that clearly doesn't work. I've also toyed with parse and eval without success. Any suggestions?

答:
You can actually treat the call like a list and give it a named argument:</p>

```<code>> tst =
function(x,y){
 foo = match.call()
 foo[["this"]] ="that"
 print(foo)
}
> tst(x=2,y=3)
tst(x = 2, y = 3, this = "that")
</code>```

Body:
Say I have the following function in R:

tst <- function(x,y){
  foo <- match.call()
  print(foo)
}

tst(4,5)

This gives tst(x = 4, y = 5). Awesome. Now, I want to add an argument.

tst <- function(x,y){
  foo <- match.call()
  foo[[length(foo)+1]] <- 6
  print(foo)
}

tst(4,5)

This prints tst(x = 4, y = 5, 6), which is great. However, I need to add an argument name so that the function knows what to do with it. For example, I want it to be tst(x = 4, y = 5, z = 6). I tried simply foo[[length(foo)+1]] <- "z = 6", but that clearly doesn't work. I've also toyed with parse and eval without success. Any suggestions?

Body:
You can actually treat the call like a list and give it a named argument:

> tst =
function(x,y){
 foo = match.call()
 foo[["this"]] ="that"
 print(foo)
}
> tst(x=2,y=3)
tst(x = 2, y = 3, this = "that")


问:
What is the correct "Document Name" of an Access ADP/MDB to use in the GetObject("Document Name") call?
According to http://support.microsoft.com/kb/288902/en-us

You can attach to a specific instance
if you know the name of an open
document in that instance. For
example, if an instance of Excel is
running with an open workbook named
Book2, the following code attaches
successfully to that instance even if
it is not the earliest instance that
was launched:

```<code>Set xlApp = GetObject("Book2").Application
</code>```

Th example works for Excel, mainly because the "Document Name" is nearly the same as the filename. I need to get this to work for Access.

I have users running multiple instances of different Access Applications (.ADP) and I need to get one with a specific name. I do NOT know the complete filepath, otherwise I could do a simple

```<code>Set app = GetObject("c:\my\app\myapp.adp", "Access.Application")
</code>```

Currently, I go with calling

```<code>Set app = GetObject(, "Access.Application")
</code>```

and check the returned Application.Name. If it's good, I use it to call some functions on it, if not it fails. I have heard about the Running Objects Table, but since I have to get the object inside a VBScript, it's a bit too much API-calls.

Bottom Line:
What is the correct "Document Name" of an Access ADP to use in the GetObject("Document Name") call and what type of object does it return?

答:
You probably want to read this: http://support.microsoft.com/kb/147816

Unfortunately, it looks like "Document Name" has to be the mdb file, so if you don't know the file path, you're not going to be able to use "Document Name".

In addition to the fact that Excel can have multiple documents per instance, Excel also prevents you from opening two documents with the same name, even if they are in different folders and you are opening them in different instances of Excel.

On the other hand (to address David-W-Fenton's comment), Access does allow you to open multiple instances of the same database (not to mention different databases with the same name), as long as you don't open any instance in exclusive mode.

This is further evidence that the way Excel registers its documents in the ROT is very different from the way Access does so.

Body:
According to http://support.microsoft.com/kb/288902/en-us

You can attach to a specific instance
if you know the name of an open
document in that instance. For
example, if an instance of Excel is
running with an open workbook named
Book2, the following code attaches
successfully to that instance even if
it is not the earliest instance that
was launched:

Set xlApp = GetObject("Book2").Application

Th example works for Excel, mainly because the "Document Name" is nearly the same as the filename. I need to get this to work for Access.

I have users running multiple instances of different Access Applications (.ADP) and I need to get one with a specific name. I do NOT know the complete filepath, otherwise I could do a simple

Set app = GetObject("c:\my\app\myapp.adp", "Access.Application")

Currently, I go with calling

Set app = GetObject(, "Access.Application")

and check the returned Application.Name. If it's good, I use it to call some functions on it, if not it fails. I have heard about the Running Objects Table, but since I have to get the object inside a VBScript, it's a bit too much API-calls.

Bottom Line:
What is the correct "Document Name" of an Access ADP to use in the GetObject("Document Name") call and what type of object does it return?


问:
Applying the <!DOCTYPE html> in xquery file
I'm trying to add dateTimePicker of jquery to my UI through xquery code.
without  dateTimePicker functionality is not working correctly.

I'm using below method to apply !DOCTYPE, but browser is unable to render it as html, it is returning as text, please suggest.

```<code>let $document := <html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"></meta>
    <title>Demo - jquery-simple-datetimepicker</title>

    <!--Requirement jQuery-->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <!--Load Script and Stylesheet -->
    <script type="text/javascript" src="jquery.simple-dtpicker.js"></script>
    <script type="text/javascript" src="date.js"></script>
    <link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet" />
    <!---->

</head>
<body onload ="function()">

    <h3>Append to Input-field</h3>
    <input type="text" name="date" value=""></input>

</body>
</html>

return document {

      text{ '<!DOCTYPE html>' },
      xdmp:quote($document)

    }
</code>```

答:
Try adding xdmp:set-response-content-type("text/html").

```<code>xdmp:set-response-content-type("text/html"),
let $document := ...
return document { ... }
</code>```

That way, you can explicitly set the mime type of the response.

Body:
I'm trying to add dateTimePicker of jquery to my UI through xquery code.
without  dateTimePicker functionality is not working correctly.

I'm using below method to apply !DOCTYPE, but browser is unable to render it as html, it is returning as text, please suggest.

let $document :=

    <meta charset="UTF-8"></meta>
    <title>Demo - jquery-simple-datetimepicker</title>

    <link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet" />

Append to Input-field

    <input type="text" name="date" value=""></input>

return document {

      text{ '<!DOCTYPE html>' },
      xdmp:quote($document)

    }

Body:
Try adding xdmp:set-response-content-type("text/html").

xdmp:set-response-content-type("text/html"),
let $document := ...
return document { ... }

That way, you can explicitly set the mime type of the response.


问:
redirecting issue with .htaccess file in PHP
I have a site like https://yoursitename.com. I am using .htaccess file for redirection. The code in .htaccess file is as :

```<code>RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
</code>```

But redirection goes me to another page which has the following htaccess code :

```<code>RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1
</code>```

What I am doing wrong?

Content of .htaccess file

```<code>RewriteEngine on
RewriteBase    /

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]

RewriteRule ^domains/all /filter.php?module=2&filter=all [R=301,NC,P]
RewriteRule ^domains/auction /filter.php?module=2&filter=auction [R=301,NC,P]
RewriteRule ^domains/active /filter.php?module=2&filter=active [R=301,NC,P]
RewriteRule ^domains/ending /filter.php?module=2&filter=ending [R=301,NC,P]
RewriteRule ^domains/justsold /filter.php?module=2&filter=justsold [R=301,NC,P]
RewriteRule ^domains/appraisal /filter.php?module=2&filter=appraisal [R=301,NC,P]
RewriteRule ^domains/brokered /filter.php?module=2&filter=brokered [R=301,NC,P]

RewriteRule ^apps/all /filter.php?module=3&filter=all [R=301,NC,P]
RewriteRule ^apps/ios /filter.php?module=3&filter=ios [R=301,NC,P]
RewriteRule ^apps/android /filter.php?module=3&filter=android [R=301,NC,P]
RewriteRule ^apps/active /filter.php?module=3&filter=active [R=301,NC,P]
RewriteRule ^apps/ending /filter.php?module=3&filter=ending [R=301,NC,P]
RewriteRule ^apps/justsold /filter.php?module=3&filter=justsold [R=301,NC,P]

RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]

RewriteRule ^item/(.*)$ ./show-digital.php?url=$1

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

RewriteCond %{HTTP_HOST} ^hiwebby\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.hiwebby\.com$

RewriteRule ^blog\/index\.php$ "http\:\/\/hiwebby\.com\/blog\/index\.php\/Support\/" [R=301,L]
</code>```

答:
You have to add the [L] Flag (Last) - so no other rules are checked</p>

```<code>RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P,L]
</code>```

Body:
I have a site like https://yoursitename.com. I am using .htaccess file for redirection. The code in .htaccess file is as :

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]

But redirection goes me to another page which has the following htaccess code :

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

What I am doing wrong?

Content of .htaccess file

RewriteEngine on
RewriteBase    /

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P]
RewriteRule ^websites/established /filter.php?module=1&filter=established [R=301,NC,P]
RewriteRule ^websites/starter /filter.php?module=1&filter=starter [R=301,NC,P]
RewriteRule ^websites/active /filter.php?module=1&filter=active [R=301,NC,P]
RewriteRule ^websites/ending /filter.php?module=1&filter=ending [R=301,NC,P]
RewriteRule ^websites/justsold /filter.php?module=1&filter=justsold [R=301,NC,P]
RewriteRule ^websites/dealflow /filter.php?module=1&filter=dealflow [R=301,NC,P]

RewriteRule ^domains/all /filter.php?module=2&filter=all [R=301,NC,P]
RewriteRule ^domains/auction /filter.php?module=2&filter=auction [R=301,NC,P]
RewriteRule ^domains/active /filter.php?module=2&filter=active [R=301,NC,P]
RewriteRule ^domains/ending /filter.php?module=2&filter=ending [R=301,NC,P]
RewriteRule ^domains/justsold /filter.php?module=2&filter=justsold [R=301,NC,P]
RewriteRule ^domains/appraisal /filter.php?module=2&filter=appraisal [R=301,NC,P]
RewriteRule ^domains/brokered /filter.php?module=2&filter=brokered [R=301,NC,P]

RewriteRule ^apps/all /filter.php?module=3&filter=all [R=301,NC,P]
RewriteRule ^apps/ios /filter.php?module=3&filter=ios [R=301,NC,P]
RewriteRule ^apps/android /filter.php?module=3&filter=android [R=301,NC,P]
RewriteRule ^apps/active /filter.php?module=3&filter=active [R=301,NC,P]
RewriteRule ^apps/ending /filter.php?module=3&filter=ending [R=301,NC,P]
RewriteRule ^apps/justsold /filter.php?module=3&filter=justsold [R=301,NC,P]

RewriteRule ^(websites|domains|apps|digitalGoods|sell)($|/) - [L]

RewriteRule ^item/(.*)$ ./show-digital.php?url=$1

RewriteRule ^([a-zA-Z0-9_-]+)$ show-detail.php?c=$1

RewriteCond %{HTTP_HOST} ^hiwebby\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.hiwebby\.com$

RewriteRule ^blog\/index\.php$ "http\:\/\/hiwebby\.com\/blog\/index\.php\/Support\/" [R=301,L]

Body:
You have to add the [L] Flag (Last) - so no other rules are checked

RewriteRule ^websites/all /filter.php?module=1&filter=all [R=301,NC,P,L]


问:
How to use jQuery Plugin with Angular 4?
I want to use a range slider in an angular project and I tried using one available module for angular 4.

It works fine during compilation but when I try to build it for deployment, it throws the below error.

I checked for the option of using jQuery plugin directly in the angular project and I'm only getting options for doing it in Angular 2.

Is there any way we can use jQuery plugins in Angular 4?

Please let me know.

答:
You are not required to declare any jQuery variable as you installed @types/jquery.

```<code>declare var jquery:any;   // not required
declare var $ :any;   // not required
</code>```

You should have access to jQuery everywhere.

The following should work:

```<code>jQuery('.title').slideToggle();
</code>```

Body:
You are not required to declare any jQuery variable as you installed @types/jquery.

declare var jquery:any;   // not required
declare var $ :any;   // not required

You should have access to jQuery everywhere.

The following should work:

jQuery('.title').slideToggle();


问:
Python 2.7 GUI using Tkinter
I'm totally new to Python and GUI. I am trying to create a simple GUI using Tkinter which has two file browser options and a command button.

When I try to click on the first browse button and select the file, the file name is displayed in both text boxes. Similarly, when I click on the second button, the new file name is displayed in both text boxes. Please correct me where I'm going wrong. I tried much to fix but in vein. Also, Please pour in suggestions to improve my coding to reduce the LOC for such a simple GUI.

Issue Sceenshot

```<code>import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

file_path_1 = StringVar
file_path_2 = StringVar

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()
</code>```

答:
Since you are using Entry widget, you don't need textvariable at all. Just remove them and use widget's own methods.

```<code>def open_rules_file():
  filename1 = askopenfilename()
  print(filename1)
  entry1.delete(0, END)
  entry1.insert(0, filename1)

def open_src_file():
  filename2 = askopenfilename()
  print(filename2)
  entry2.delete(0, END)
  entry2.insert(0, filename2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()

f1 = Frame(mf, width=600, height=250)
f2 = Frame(mf, width=600, height=250)
f3 = Frame(mf, width=600, height=250)

f1.pack(fill=X)
f2.pack()
f3.pack()

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()
</code>```

But if you really insist on using it, you can change value of StringVar by using file_path_1.set("your value").

Your usage right now (file_path_1 = "value") changes file_path_1 to a plain string.

```<code>def open_rules_file():
  var.set(askopenfilename())

var = StringVar()
entry1 = Entry(f1, width=70, textvariable = var)
</code>```

Title: Python 2.7 GUI using Tkinter

Body:
I'm totally new to Python and GUI. I am trying to create a simple GUI using Tkinter which has two file browser options and a command button.

When I try to click on the first browse button and select the file, the file name is displayed in both text boxes. Similarly, when I click on the second button, the new file name is displayed in both text boxes. Please correct me where I'm going wrong. I tried much to fix but in vein. Also, Please pour in suggestions to improve my coding to reduce the LOC for such a simple GUI.

Issue Sceenshot

import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

file_path_1 = StringVar
file_path_2 = StringVar

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()

Body:
Since you are using Entry widget, you don't need textvariable at all. Just remove them and use widget's own methods.

def open_rules_file():
  filename1 = askopenfilename()
  print(filename1)
  entry1.delete(0, END)
  entry1.insert(0, filename1)

def open_src_file():
  filename2 = askopenfilename()
  print(filename2)
  entry2.delete(0, END)
  entry2.insert(0, filename2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()

f1 = Frame(mf, width=600, height=250)
f2 = Frame(mf, width=600, height=250)
f3 = Frame(mf, width=600, height=250)

f1.pack(fill=X)
f2.pack()
f3.pack()

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()

But if you really insist on using it, you can change value of StringVar by using file_path_1.set("your value").

Your usage right now (file_path_1 = "value") changes file_path_1 to a plain string.

def open_rules_file():
  var.set(askopenfilename())

var = StringVar()
entry1 = Entry(f1, width=70, textvariable = var)


问:
Select drop-down scroll style
Is there any css way to stylize the scroll of the default select drop-down?
Or it`s better just forgot this and use div, ul, li and some javascript ?

```<code><select id="selector">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  ...
</select>
</code>```

Here is a simple demo, of overflown select and div nearby, where only div has applyed scroll style, as expected

答: Scrollbar CSS styles are not part of the W3C standard for CSS and therefore most browsers just ignore them. Some browser have a way to style this, but the javascript solution is the best for cross-browser.</p>

Title: Select drop-down scroll style

Body:
Is there any css way to stylize the scroll of the default select drop-down?
Or it`s better just forgot this and use div, ul, li and some javascript ?

<select id="selector">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  ...
</select>

Here is a simple demo, of overflown select and div nearby, where only div has applyed scroll style, as expected


问:
DATENAME not working with Group By
I have a SQL query that returns data as expected:

```<code> SELECT intMonth as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear
</code>```

However, when I try to change the numerical Month to the Month Name like this:

```<code>SELECT DateName(month,intMonth) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear
</code>```

I get this:

Changing the "Group By" Clause to "Group By DateName(month,intMonth), intYear"

Produces this:

Can anyone tell me why I am not getting January, February, March, April May?

Any assistance is greatly appreciated!

答:
DATENAME only works with actual dates. You have to do something hacky to get this to work.

```<code>SELECT DATENAME(month, DATEADD(month, intMonth - 1, CAST('2017-01-01' AS DATETIME))) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear
</code>```

Edit: Sorry, to answer your question of why this is happening, try these queries:

```<code>SELECT CAST(1 AS DATETIME) -- 1900-01-02 00:00:00.000
SELECT CAST(42919 AS DATETIME) -- is today, the 42,919th day since January 1, 1900
</code>```

SQL Server actually stores dates as integers. When you put '1' as a date, it sees that as "1900-01-02 00:00:00.000". Therefore it says the month is January for all of your results because you're inputting the numbers 1-12. It thinks you're saying January 2-13, 1900. That's why it grabs January for each one.

Title: DATENAME not working with Group By

Body:
I have a SQL query that returns data as expected:

 SELECT intMonth as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

However, when I try to change the numerical Month to the Month Name like this:

SELECT DateName(month,intMonth) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

I get this:

Changing the "Group By" Clause to "Group By DateName(month,intMonth), intYear"

Produces this:

Can anyone tell me why I am not getting January, February, March, April May?

Any assistance is greatly appreciated!

Body:
DATENAME only works with actual dates. You have to do something hacky to get this to work.

SELECT DATENAME(month, DATEADD(month, intMonth - 1, CAST('2017-01-01' AS DATETIME))) as Month
, intYear AS Year,
Sum([intExposureHours]) as [Total Hours]
  FROM tblSSQReleaseToMajor RTM
  INNER JOIN tblCompany C On RTM.CompanyID = C.CompanyID
    AND C.bitActive = 1
  INNER JOIN [tblIncidentDetailByOperatorByMonth] BM ON RTM.MajorID = BM.OperatorID
    AND BM.ContractorID = RTM.CompanyID
        AND BM.OperatorID = 47792
    AND BM.intYear = 2017
        Group By intMonth, intYear

Edit: Sorry, to answer your question of why this is happening, try these queries:

SELECT CAST(1 AS DATETIME) -- 1900-01-02 00:00:00.000
SELECT CAST(42919 AS DATETIME) -- is today, the 42,919th day since January 1, 1900

SQL Server actually stores dates as integers. When you put '1' as a date, it sees that as "1900-01-02 00:00:00.000". Therefore it says the month is January for all of your results because you're inputting the numbers 1-12. It thinks you're saying January 2-13, 1900. That's why it grabs January for each one.


问:
How do forwarding types apply to IoC?
I'm still learning Castle Windsor and I see that it supports forwarded types - a term I was unfamiliar with.

Quick Google search and I found this article that explains it pretty throughly however I still don't understand how this applies to IoC or how I would use them from a container and for what reason.

Can anyone explain?

答: Type forwarding is a way to move type from one assembly to another without introducing breaking changes it has nothing to do with IoC. So you should not worry about this feature :) </p>

OwnerDisplayName: George Mauer

Title: How do forwarding types apply to IoC?

OwnerDisplayName: aku


问:
System.Net.Mail.SmtpException: Cannot get IIS pickup directory
Fellas,

Getting the "Cannot get IIS pickup directory" exception with my app. I have my directory created and specified in the config as follows:

```<code><system.net>
  <mailSettings>
    <smtp deliveryMethod="PickupDirectoryFromIis" from="donotreply@mysite.com">
      <specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\email\mysite"/>
    </smtp>
  </mailSettings>
</system.net>
</code>```

Trying to have the emails placed locally in a directory so I can see them.

Any ideas why it could be throwing that exception?

FWIW, this is IIS7 + Windows 7 and an MVC2 app (C#).

Also, went ahead and gave permissions to the IIS_IUSRS group to that directory.

答:
All,

Seems like I was using the wrong smtp deliveryMethod. I got the PickupDirectoryFromIis and SpecifiedPickup deliveryMethod's mixed up, and hence was using the wrong settings for it.

Body:
Fellas,

Getting the "Cannot get IIS pickup directory" exception with my app. I have my directory created and specified in the config as follows:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="PickupDirectoryFromIis" from="donotreply@mysite.com">
      <specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\email\mysite"/>
    </smtp>
  </mailSettings>
</system.net>

Trying to have the emails placed locally in a directory so I can see them.

Any ideas why it could be throwing that exception?

FWIW, this is IIS7 + Windows 7 and an MVC2 app (C#).

Also, went ahead and gave permissions to the IIS_IUSRS group to that directory.


问:
Scikit learn installation
I tried to install scikit learn on my Ubuntu device using the command :
pip install -U scikit-learn

I already have numpy, scipy and matpotlib installed.
I am getting the following error:
    from pip._vendor.pkg_resources import RequirementParseError
ImportError: cannot import name RequirementParseError

答:
Try this in the console:

```<code>sudo -i
</code>```

Type your password and then type:

```<code>pip install scikit-learn
</code>```

Hope this helps

Title: Scikit learn installation

Body:
Try this in the console:

sudo -i

Type your password and then type:

pip install scikit-learn

Hope this helps


Title: Split a list of timestamps by intervals of 2 seconds in python

Body:
I have a list of timestamps all converted to integers. How can I split them into separate lists of 2-second intervals?

d = [1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402, 1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405, 1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]

I would like to split them into intervals of 2 seconds so that I am able to print out the results of each interval.

Intended output:

[1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402]
[1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405]
[1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408]
[1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]

Thanks.

Body:
You could try this - determine the range of minimum and maximum values of d and then check if each element is within the interval if 2 seconds (x, x+1, x+2):

for x in range(min(d), max(d)+1, 3):
    print ([item for item in d if item in (x, x+1, x+2) ])

Returns:

[1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256400, 1499256401, 1499256401, 1499256401, 1499256401, 1499256402, 1499256402]
[1499256403, 1499256403, 1499256404, 1499256404, 1499256405, 1499256405, 1499256405, 1499256405]
[1499256406, 1499256406, 1499256407, 1499256407, 1499256408, 1499256408, 1499256408, 1499256408]
[1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409, 1499256409]


问:
Set custom steps in Jquery ui pips
I'm stuck with jQuery ui pips [http://simeydotme.github.io/jQuery-ui-Slider-Pips/].

There is default behavior that we can set steps by number.For example if I add 10 then it will execute it by "0,10,20...". But here I want custom steps like "0,499,199,499..". Please help me here.

答:
You can specify an array with the values you'd like to display as labels.

The trick here is to use an empty array and only fill in the indexes you want to show.

```<code>var labels = [];
    labels[0] = "zero";
    labels[99] = 99;
    labels[199] = 199;
    // ....
</code>```

Here is a JSFiddle demonstrating the code in practise; http://jsfiddle.net/d5boxc30/1/

Title: Set custom steps in Jquery ui pips

Body:
You can specify an array with the values you'd like to display as labels.

The trick here is to use an empty array and only fill in the indexes you want to show.

var labels = [];
    labels[0] = "zero";
    labels[99] = 99;
    labels[199] = 199;
    // ....

Here is a JSFiddle demonstrating the code in practise; http://jsfiddle.net/d5boxc30/1/


问:
Python Regex - How to Get Positions and Values of Matches
How can I get the start and end positions of all matches using the re module? For example given the pattern r'[a-z]' and the string 'a1b2c3d4' I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.

答:
For Python 3.x

```<code>from re import finditer
for match in finditer("pattern", "string"):
    print(match.span(), match.group())
</code>```

You shall get \n separated tuples (comprising first and last indices of the match, respectively) and the match itself, for each hit in the string.

OwnerDisplayName: Greg

Body:
For Python 3.x

from re import finditer
for match in finditer("pattern", "string"):
    print(match.span(), match.group())

You shall get \n separated tuples (comprising first and last indices of the match, respectively) and the match itself, for each hit in the string.