问:
Highlight difference between two step data (derived from histogram) in R
:-)

I have two datasets where I derived histogram data from. These are both saved in two seperate arrays. The current sourcecode can be found below, along with the current plot.

```<code># DEMO file for the awesome stackoverflow community
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")
</code>```

The resulting plot is like this (and should be reproducable by you):
I cant link images yet, so here is the link

So, this is okay for now.

However, I want to highlight the difference in the histograms visually. Of course I can calculate the difference, which is good because I need  that too, but I also want to highlight the differences to show the the interesting areas. The final picture should look something like this Again the link

I would not necessarily need a color-discrimination between positive and negative difference, it would be nice though. I have no idea how to shade the areas in between the step data.

Can someone help me with this? One more thing, due to some restrictions, I am not allowed to use too many additional packages. I am using "R version 3.1.1 (2014-07-10) -- "Sock it to Me""

Thank you so much in advance!

答:
Not an elegant solution but nonetheless it does what you require.

```<code> #Get pairwise min
    y_low <-c(pmin(data_P_hist$counts, data_T_hist$counts),0)

    #Get pairwise max
    y_high <- c(pmax(data_P_hist$counts, data_T_hist$counts),0)

    for(i in 2:length(xtics)-1){
      rect(xtics[i], y_low[i], xtics[i+1],y_high[i], col="powderblue", border = NA)
    }
</code>```

This is the plot you get:

Hope it helps!

Body:
:-)

I have two datasets where I derived histogram data from. These are both saved in two seperate arrays. The current sourcecode can be found below, along with the current plot.

# DEMO file for the awesome stackoverflow community
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")

The resulting plot is like this (and should be reproducable by you):
I cant link images yet, so here is the link

So, this is okay for now.

However, I want to highlight the difference in the histograms visually. Of course I can calculate the difference, which is good because I need  that too, but I also want to highlight the differences to show the the interesting areas. The final picture should look something like this Again the link

I would not necessarily need a color-discrimination between positive and negative difference, it would be nice though. I have no idea how to shade the areas in between the step data.

Can someone help me with this? One more thing, due to some restrictions, I am not allowed to use too many additional packages. I am using "R version 3.1.1 (2014-07-10) -- "Sock it to Me""

Thank you so much in advance!

Body:
Not an elegant solution but nonetheless it does what you require.

 #Get pairwise min
    y_low <-c(pmin(data_P_hist$counts, data_T_hist$counts),0)

    #Get pairwise max
    y_high <- c(pmax(data_P_hist$counts, data_T_hist$counts),0)

    for(i in 2:length(xtics)-1){
      rect(xtics[i], y_low[i], xtics[i+1],y_high[i], col="powderblue", border = NA)
    }

This is the plot you get:

Hope it helps!


来源: stackexchange

问:
Can't download from AWS boto3 generated signed url

I'm trying to upload a file to an existing AWS s3 bucket, generate a public URL and use that URL (somewhere else) to download the file.
I'm closely following the example here:

```<code>import os
import boto3
import requests
import tempfile

s3 = boto3.client('s3')

with tempfile.NamedTemporaryFile(mode="w", delete=False) as outfile:
    outfile.write("dummycontent")
    file_name = outfile.name

with open(file_name, mode="r") as outfile:
    s3.upload_file(outfile.name, "twistimages", "filekey")

os.unlink(file_name)

url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': 'twistimages',
        'Key': 'filekey'
    }
)

response = requests.get(url)
print(response)
</code>```

I would expect to see a success return code (200) from the requests library.

Instead, stdout is: <Response [400]>

Also, if I navigate to the corresponding URL with a webbrowser, I get an XML file with an error code: InvalidRequest and an error message:

The authorization mechanism you have provided is not supported. Please
  use AWS4-HMAC-SHA256.

How can I use boto3 to generate a public URL, which can easily be downloaded by any user by just navigating to the corresponding URL, without generating complex headers?

Why does the example code from the official documentation not work in my case?

答:
I solved the issue. I'm using an S3 bucket in the eu-central-1 region and after specifying the region in the config file, everything worked as expected and the script stdout was <Response [200]>.

The configuration file (~/.aws/config) now looks like:

```<code>[default]
region=eu-central-1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to upload a file to an existing AWS s3 bucket, generate a public URL and use that URL (somewhere else) to download the file.
I'm closely following the example here:

import os
import boto3
import requests
import tempfile

s3 = boto3.client('s3')

with tempfile.NamedTemporaryFile(mode="w", delete=False) as outfile:
    outfile.write("dummycontent")
    file_name = outfile.name

with open(file_name, mode="r") as outfile:
    s3.upload_file(outfile.name, "twistimages", "filekey")

os.unlink(file_name)

url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': 'twistimages',
        'Key': 'filekey'
    }
)

response = requests.get(url)
print(response)

I would expect to see a success return code (200) from the requests library.

Instead, stdout is: <Response [400]>

Also, if I navigate to the corresponding URL with a webbrowser, I get an XML file with an error code: InvalidRequest and an error message:

The authorization mechanism you have provided is not supported. Please
  use AWS4-HMAC-SHA256.

How can I use boto3 to generate a public URL, which can easily be downloaded by any user by just navigating to the corresponding URL, without generating complex headers?

Why does the example code from the official documentation not work in my case?

Body:
I solved the issue. I'm using an S3 bucket in the eu-central-1 region and after specifying the region in the config file, everything worked as expected and the script stdout was <Response [200]>.

The configuration file (~/.aws/config) now looks like:

[default]
region=eu-central-1


问:
How to create dependency injection for ASP.NET MVC 5?
Creating Dependency Injection with ASP.NET Core is fairly easy. The documentation explains it very well here and this guy has a killer video to explain it.

However, I want to do the same thing with my ASP.NET MVC 5 project. How can handle dependency injection with ASP.MVC 5?

Also, is Dependency injection limited to controllers only or can it work with any class?

答:
In ASP.Net MVC you can use the .Net Core DI from NuGet rather than one of the third-party alternatives:-

```<code>using Microsoft.Extensions.DependencyInjection
</code>```

For the MVC Start/Configuration class:-

```<code>public void Configuration(IAppBuilder app)
{
    // We will use Dependency Injection for all controllers and other classes, so we'll need a service collection
    var services = new ServiceCollection();

    // configure all of the services required for DI
    ConfigureServices(services);

    // Configure authentication
    ConfigureAuth(app);

    // Create a new resolver from our own default implementation
    var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());

    // Set the application resolver to our default resolver. This comes from "System.Web.Mvc"
    //Other services may be added elsewhere through time
    DependencyResolver.SetResolver(resolver);
}
</code>```

My project uses Identity User and I've replaced the OWIN start-up configuration to follow a service-based approach instead. The default Identity User classes use static factory methods to create instances. I've moved that code into the constructors and relied on DI to provide the appropriate injection. It is still work in progress but here is where I am at:-

```<code>public void ConfigureServices(IServiceCollection services)
{
    //====================================================
    // Create the DB context for the IDENTITY database
    //====================================================
    // Add a database context - this can be instantiated with no parameters
    services.AddTransient(typeof(ApplicationDbContext));

    //====================================================
    // ApplicationUserManager
    //====================================================
    // instantiation requires the following instance of the Identity database
    services.AddTransient(typeof(IUserStore<ApplicationUser>), p => new UserStore<ApplicationUser>(new ApplicationDbContext()));

    // with the above defined, we can add the user manager class as a type
    services.AddTransient(typeof(ApplicationUserManager));

    //====================================================
    // ApplicationSignInManager
    //====================================================
    // instantiation requires two parameters, [ApplicationUserManager] (defined above) and [IAuthenticationManager]
    services.AddTransient(typeof(Microsoft.Owin.Security.IAuthenticationManager), p => new OwinContext().Authentication);
    services.AddTransient(typeof(ApplicationSignInManager));

    //====================================================
    // ApplicationRoleManager
    //====================================================
    // Maps the rolemanager of identity role to the concrete role manager type
    services.AddTransient<RoleManager<IdentityRole>, ApplicationRoleManager>();

    // Maps the role store role to the implemented type
    services.AddTransient<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>();
    services.AddTransient(typeof(ApplicationRoleManager));

    //====================================================
    // Add all controllers as services
    //====================================================
    services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
        .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
    .Where(t => typeof(IController).IsAssignableFrom(t)
    || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
}
</code>```

The Account Controller class has the single constructor:-

```<code>[Authorize]
public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private RoleManager<IdentityRole> _roleManager;

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, RoleManager<IdentityRole> roleManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }
}
</code>```

My Default Dependency Resolver:

```<code>/// <summary>
/// Provides the default dependency resolver for the application - based on IDependencyResolver, which hhas just two methods
/// </summary>
public class DefaultDependencyResolver : IDependencyResolver
{
    /// <summary>
    /// Provides the service that holds the services
    /// </summary>
    protected IServiceProvider serviceProvider;

    /// <summary>
    /// Create the service resolver using the service provided (Direct Injection pattern)
    /// </summary>
    /// <param name="serviceProvider"></param>
    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Get a service by type - assume you get the first one encountered
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    /// <summary>
    /// Get all services of a type
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}
</code>```

Body:
In ASP.Net MVC you can use the .Net Core DI from NuGet rather than one of the third-party alternatives:-

using Microsoft.Extensions.DependencyInjection

For the MVC Start/Configuration class:-

public void Configuration(IAppBuilder app)
{
    // We will use Dependency Injection for all controllers and other classes, so we'll need a service collection
    var services = new ServiceCollection();

    // configure all of the services required for DI
    ConfigureServices(services);

    // Configure authentication
    ConfigureAuth(app);

    // Create a new resolver from our own default implementation
    var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());

    // Set the application resolver to our default resolver. This comes from "System.Web.Mvc"
    //Other services may be added elsewhere through time
    DependencyResolver.SetResolver(resolver);
}

My project uses Identity User and I've replaced the OWIN start-up configuration to follow a service-based approach instead. The default Identity User classes use static factory methods to create instances. I've moved that code into the constructors and relied on DI to provide the appropriate injection. It is still work in progress but here is where I am at:-

public void ConfigureServices(IServiceCollection services)
{
    //====================================================
    // Create the DB context for the IDENTITY database
    //====================================================
    // Add a database context - this can be instantiated with no parameters
    services.AddTransient(typeof(ApplicationDbContext));

    //====================================================
    // ApplicationUserManager
    //====================================================
    // instantiation requires the following instance of the Identity database
    services.AddTransient(typeof(IUserStore<ApplicationUser>), p => new UserStore<ApplicationUser>(new ApplicationDbContext()));

    // with the above defined, we can add the user manager class as a type
    services.AddTransient(typeof(ApplicationUserManager));

    //====================================================
    // ApplicationSignInManager
    //====================================================
    // instantiation requires two parameters, [ApplicationUserManager] (defined above) and [IAuthenticationManager]
    services.AddTransient(typeof(Microsoft.Owin.Security.IAuthenticationManager), p => new OwinContext().Authentication);
    services.AddTransient(typeof(ApplicationSignInManager));

    //====================================================
    // ApplicationRoleManager
    //====================================================
    // Maps the rolemanager of identity role to the concrete role manager type
    services.AddTransient<RoleManager<IdentityRole>, ApplicationRoleManager>();

    // Maps the role store role to the implemented type
    services.AddTransient<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>();
    services.AddTransient(typeof(ApplicationRoleManager));

    //====================================================
    // Add all controllers as services
    //====================================================
    services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
        .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
    .Where(t => typeof(IController).IsAssignableFrom(t)
    || t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
}

The Account Controller class has the single constructor:-

[Authorize]
public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private RoleManager<IdentityRole> _roleManager;

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, RoleManager<IdentityRole> roleManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        RoleManager = roleManager;
    }
}

My Default Dependency Resolver:

/// <summary>
/// Provides the default dependency resolver for the application - based on IDependencyResolver, which hhas just two methods
/// </summary>
public class DefaultDependencyResolver : IDependencyResolver
{
    /// <summary>
    /// Provides the service that holds the services
    /// </summary>
    protected IServiceProvider serviceProvider;

    /// <summary>
    /// Create the service resolver using the service provided (Direct Injection pattern)
    /// </summary>
    /// <param name="serviceProvider"></param>
    public DefaultDependencyResolver(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Get a service by type - assume you get the first one encountered
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public object GetService(Type serviceType)
    {
        return this.serviceProvider.GetService(serviceType);
    }

    /// <summary>
    /// Get all services of a type
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return this.serviceProvider.GetServices(serviceType);
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to connect external database to AppEngine?
Are there any ways (better than using UrlFetch) to connect to any external database from AppEngine?

I already know about hosted SQL databases in App Engine for Business, but they are not free and will be avialable in Q2 2011, so it's not an option right now.

I like datastore very much, but customers don't like vendor lock or have other reasons.

答:
The only way to connect external databases to AppEngine is by exposing them via a web API.

Basically you need to create a webservices layer upon your Database, allowing your GAE Application to interact with the remote db through UrlFetch Http calls.

ContentLicense: CC BY-SA 2.5


问:
Indexing aggregate function in SQL
I have the following SQL query which I want to optimize using indexing. </p>

```<code>select    ean,   count(nif)
from    produto   P,   fornece_sec   F where    P.ean   =   F.ean
group   by    P.ean
having    count(nif)   >   1
</code>```

<p>Makes sense to use an index for nif? </p>

答:
First, learn how to write queries correctly using explicit join syntax:

```<code>select P.ean, count(nif)
from produto P join
     fornece_sec F
     on P.ean = F.ean
group by P.ean
having count(nif) > 1;
</code>```

Then -- assuming that all eans in fornece_sec are also in produto -- you don't need the join, because you are aggregating by the join key.  So, you can simplify this to:

```<code>select F.ean, count(F.nif)
from fornece_sec F
group by F.ean
having count(F.nif) > 1;
</code>```

For this version of the query, you can use a covering index:  fornece_sec(ean, nif).

Title: Indexing aggregate function in SQL

Body:
I have the following SQL query which I want to optimize using indexing.

select    ean,   count(nif)
from    produto   P,   fornece_sec   F where    P.ean   =   F.ean
group   by    P.ean
having    count(nif)   >   1

Makes sense to use an index for nif?

Body:
First, learn how to write queries correctly using explicit join syntax:

select P.ean, count(nif)
from produto P join
     fornece_sec F
     on P.ean = F.ean
group by P.ean
having count(nif) > 1;

Then -- assuming that all eans in fornece_sec are also in produto -- you don't need the join, because you are aggregating by the join key.  So, you can simplify this to:

select F.ean, count(F.nif)
from fornece_sec F
group by F.ean
having count(F.nif) > 1;

For this version of the query, you can use a covering index:  fornece_sec(ean, nif).


问:
How to check if .xls and .csv files are empty
Question 1: How can I check if an entire .xls or .csv file is empty.This is the code I am using:

```<code>try:
    if os.stat(fullpath).st_size > 0:
       readfile(fullpath)
    else:
       print "empty file"
except OSError:
    print "No file"
</code>```

An empty .xls file has size greater than 5.6kb so it is not obvious whether it has any contents. How can I check if an xls or csv file is empty?

Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?

```<code>import xlrd
def readfile(fullpath)
    xls=xlrd.open_workbook(fullpath)
    for sheet in xls.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols
        sheetname = sheet.name
        header = sheet.row_values(0) #Then if it contains only headers, treat it as empty.
</code>```

This is my attempt. How do I continue with this code?

Please provide a solution for both questions. Thanks in advance.

答:
For your question:

Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?

You can just check the line in files.

with open('empty_csv_with_header.csv') as f:
    f.readline()  # skip header
    line = f.readline()
    if line == b'':
        print('Empty csv')
```

Body:
Question 1: How can I check if an entire .xls or .csv file is empty.This is the code I am using:

try:
    if os.stat(fullpath).st_size > 0:
       readfile(fullpath)
    else:
       print "empty file"
except OSError:
    print "No file"

An empty .xls file has size greater than 5.6kb so it is not obvious whether it has any contents. How can I check if an xls or csv file is empty?

Question 2: I need to check the header of the file. How can I tell python that files which are just a single row of headers are empty?

import xlrd
def readfile(fullpath)
    xls=xlrd.open_workbook(fullpath)
    for sheet in xls.sheets():
        number_of_rows = sheet.nrows
        number_of_columns = sheet.ncols
        sheetname = sheet.name
        header = sheet.row_values(0) #Then if it contains only headers, treat it as empty.

This is my attempt. How do I continue with this code?

Please provide a solution for both questions. Thanks in advance.


问:
Cannot resolve Symbol otl_connect (otl_connect class not including)
I have been trying to connect to mysql using OTL_ODBC. I have included the OTL header file (otlv4.h) in my Visual Studio 2010 Project but when I try to use otl_connect, it displays the error "Cannot Resolve Symbol otl_connect", and the otl_connect class appears red in colour:

May I know where I'm doing it wrong?

```<code>#define OTL_ODBC
#include "otlv4.h"
int main(int argc, char* argv[])
{
  otl_connect db;
}
</code>```

答: otl_connect is inside namespace odbc. Try odbc::otl_connect.

Body:
I have been trying to connect to mysql using OTL_ODBC. I have included the OTL header file (otlv4.h) in my Visual Studio 2010 Project but when I try to use otl_connect, it displays the error "Cannot Resolve Symbol otl_connect", and the otl_connect class appears red in colour:

May I know where I'm doing it wrong?

#define OTL_ODBC
#include "otlv4.h"
int main(int argc, char* argv[])
{
  otl_connect db;
}


问:
Command line argument not working when passing to a function while using getopts
I've been trying to get some practice in with bash shell scripting but I've been having trouble using the $1 variable to reference the first argument for my script. It's a simple script that takes a file as an argument and prints the name of the file. Here's my script:

```<code>#!/bin/bash

function practice() {
  echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
  h) practice
     ;;
  esac
done

exit 0
</code>```

I tried the following command:

```<code>./practice.sh -h somefile.txt
</code>```

For some reason it returns an empty line. Any thoughts?

答:
$1 in functions refers to first positional parameter passed to that function, not passed to your script.

Therefore, you have to pass the arguments you want to the function again. You also tell getopts you want to process -h but then you are checking for -a in your case instead:

```<code>#!/bin/bash

practice() {
   echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
     h) practice "${OPTARG}"
        ;;
  esac
done
</code>```

Body:
I've been trying to get some practice in with bash shell scripting but I've been having trouble using the $1 variable to reference the first argument for my script. It's a simple script that takes a file as an argument and prints the name of the file. Here's my script:

#!/bin/bash

function practice() {
  echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
  h) practice
     ;;
  esac
done

exit 0

I tried the following command:

./practice.sh -h somefile.txt

For some reason it returns an empty line. Any thoughts?

Body:
$1 in functions refers to first positional parameter passed to that function, not passed to your script.

Therefore, you have to pass the arguments you want to the function again. You also tell getopts you want to process -h but then you are checking for -a in your case instead:

#!/bin/bash

practice() {
   echo "${1}"
}

while getopts "h:" opt; do
  case "$opt" in
     h) practice "${OPTARG}"
        ;;
  esac
done


问:
How to make string as an Array Object in JQuery
I have got below string values in a variable.

```<code>var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'
</code>```

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

```<code>$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});
</code>```

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

```<code>             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);
</code>```

the above code is giving below error

```<code>Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'
</code>```

答:
You need to use a javascript var (I think):

```<code>gImgs = [
    {"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}
];
</code>```

then

```<code>$('.slideshow').liveBanner(gImgs, {"autostart":false,
  "pause_time":5500, "random":false});
</code>```

So on each page you will have a different gImgs. Note that if you include a script for the liveBanner creation, you will have to define gImgs before the , like:

```<code><html>
    <head>
        <!-- ... -->
        <script type="application/x-javascript">
        <!--
            var gImgs = [ /* ... */ ];
        -->
        </script>
        <script type="application/x-javascript" src="yourscript.js"></script>
    </head>
    <body>
    <!-- ... -->
    </body>
</html>
</code>```

Body:
I have got below string values in a variable.

var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);

the above code is giving below error

Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'

Body:
You need to use a javascript var (I think):

gImgs = [
    {"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}
];

then

$('.slideshow').liveBanner(gImgs, {"autostart":false,
  "pause_time":5500, "random":false});

So on each page you will have a different gImgs. Note that if you include a script for the liveBanner creation, you will have to define gImgs before the <script src="..."></script>, like:

<html>
    <head>
        <!-- ... -->
        <script type="application/x-javascript">
        <!--
            var gImgs = [ /* ... */ ];
        -->
        </script>
        <script type="application/x-javascript" src="yourscript.js"></script>
    </head>
    <body>
    <!-- ... -->
    </body>
</html>


问:
Formal Languages : Grammar, construct a grammar which produces a particular pattern
I have to construction an L(G) which creates the following pattern:

"The word starts always with a 'b', if an a is in the word, that is immediately followed by 'b'"

So we cannot have two 'a' consequently

```<code>For ex the pattern can be:  'b', 'bb', 'bab', 'bbbbbbab', 'bababab'
</code>```

I construct the Finite State Machine, but I am not able to find a general L(G) which produces this kind of grammar, this is what I got so far:

```<code>L(G) = { b^n  a^m b^k | n>1, a => 0, b > 1 }
</code>```

Does anybody has an idea how to proceed with this problem, if yes please tell me what can I do?

答:
I think you can write the definition like this:

L = {bn(axby)m | n>0, m>=0, x in {0,1}, y>=x}

Body:
I have to construction an L(G) which creates the following pattern:

"The word starts always with a 'b', if an a is in the word, that is immediately followed by 'b'"

So we cannot have two 'a' consequently

For ex the pattern can be:  'b', 'bb', 'bab', 'bbbbbbab', 'bababab'

I construct the Finite State Machine, but I am not able to find a general L(G) which produces this kind of grammar, this is what I got so far:

L(G) = { b^n  a^m b^k | n>1, a => 0, b > 1 }

Does anybody has an idea how to proceed with this problem, if yes please tell me what can I do?


问:
how to set 2 pictures side by side?
i'm trying to put 2 pictures side by side. i thought i can do that by using bootstrap grid but it doesn't work for me. my code

```<code><div class="row">
  <div class="col-xs-6">
    <img src="https://lh3.googleusercontent.com/aHxLM6563JbtHMwdbWTAEzIbILKwxsuM-s6SIGR2zki8h5wmSf-Semz8xhNIbwbHGwAW3CE3j-g=w640-h400-e365" alt="google">
 <div class="col-xs-6">
    <img src="http://www.hisocial.com/eng/wp-content/uploads/2013/08/fb_login_1.png" alt="facebook">
</code>```

I want the portfolio pictures to be like this:

his code

答:
First, you need to make your that you've included the bootstrap framework before using classes such as "row" and "col-xs-6". Include this line of code in the  if you haven't -

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

Use col-md-* for desktops & laptops instead of xs. XS is for small devices. Try this code:

```<code><div class="row">
<div class="col-md-6">
    <img src="https://lh3.googleusercontent.com/aHxLM6563JbtHMwdbWTAEzIbILKwxsuM-s6SIGR2zki8h5wmSf-Semz8xhNIbwbHGwAW3CE3j-g=w640-h400-e365" alt="google">
</div>
<div class="col-md-6">
    <img src="http://www.hisocial.com/eng/wp-content/uploads/2013/08/fb_login_1.png" alt="facebook">
</div>
</code>```

Title: how to set 2 pictures side by side?

Body:
i'm trying to put 2 pictures side by side. i thought i can do that by using bootstrap grid but it doesn't work for me. my code

I want the portfolio pictures to be like this:

his code

Body:
First, you need to make your that you've included the bootstrap framework before using classes such as "row" and "col-xs-6". Include this line of code in the  if you haven't -

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

Use col-md-* for desktops & laptops instead of xs. XS is for small devices. Try this code:

<div class="row">
<div class="col-md-6">
    <img src="https://lh3.googleusercontent.com/aHxLM6563JbtHMwdbWTAEzIbILKwxsuM-s6SIGR2zki8h5wmSf-Semz8xhNIbwbHGwAW3CE3j-g=w640-h400-e365" alt="google">
</div>
<div class="col-md-6">
    <img src="http://www.hisocial.com/eng/wp-content/uploads/2013/08/fb_login_1.png" alt="facebook">
</div>


问:
Entity Framework - "An error occurred while updating the entries. See the inner exception for details"
I have problem, I have just started learning EF Model First and Im staying in one point for some time. I got such error :

"An error occurred while updating the entries. See the inner exception for details"

I have created an easy model on diagram, generated the database and wrote easy code in C# to add just one row in the table but the error is showing up all the time.

I post screenshot with Diagram/Generated DLL/Simple Main/And error throwing

Link for bigger size : http://i.imgur.com/bKGc4wv.png

答:
I had this problem recently.
This was happen, because the permissions of user database.
check permissions of user database, maybe the user do not have permission to write on db. </p>


问:
S3 Bucket Lambda Event: Unable to validate the following destination configurations
I'm trying to create an S3 bucket and immediately assign a lambda notification event to it.

Here's the node test script I wrote:

```<code>const aws = require('aws-sdk');
const uuidv4 = require('uuid/v4');

aws.config.update({
  accessKeyId: 'key',
  secretAccessKey:'secret',
  region: 'us-west-1'
});

const s3 = new aws.S3();

const params = {
  Bucket: `bucket-${uuidv4()}`,
  ACL: "private",
  CreateBucketConfiguration: {
    LocationConstraint: 'us-west-1'
  }
};

s3.createBucket(params, function (err, data) {
  if (err) {
    throw err;
  } else {
    const bucketUrl = data.Location;

    const bucketNameRegex = /bucket-[a-z0-9\-]+/;
    const bucketName = bucketNameRegex.exec(bucketUrl)[0];

    const params = {
      Bucket: bucketName,
      NotificationConfiguration: {
        LambdaFunctionConfigurations: [
          {
            Id: `lambda-upload-notification-${bucketName}`,
            LambdaFunctionArn: 'arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload',
            Events: ['s3:ObjectCreated:CompleteMultipartUpload']
          },
        ]
      }
    };

    // Throws "Unable to validate the following destination configurations" until an event is manually added and deleted from the bucket in the AWS UI Console
    s3.putBucketNotificationConfiguration(params, function(err, data) {
      if (err) {
        console.error(err);
        console.error(this.httpResponse.body.toString());
      } else {
        console.log(data);
      }
    });
  }
});
</code>```

The creation works fine but calling s3.putBucketNotificationConfiguration from the aws-sdk throws:

```<code>{ InvalidArgument: Unable to validate the following destination configurations
    at Request.extractError ([...]/node_modules/aws-sdk/lib/services/s3.js:577:35)
    at Request.callListeners ([...]/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
    at Request.emit ([...]/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
    at Request.emit ([...]/node_modules/aws-sdk/lib/request.js:683:14)
    at Request.transition ([...]/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo ([...]/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at [...]/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> ([...]/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> ([...]/node_modules/aws-sdk/lib/request.js:685:12)
    at Request.callListeners ([...]/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
  message: 'Unable to validate the following destination configurations',
  code: 'InvalidArgument',
  region: null,
  time: 2017-11-10T02:55:43.004Z,
  requestId: '9E1CB35811ED5828',
  extendedRequestId: 'tWcmPfrAu3As74M/0sJL5uv+pLmaD4oBJXwjzlcoOBsTBh99iRAtzAloSY/LzinSQYmj46cwyfQ=',
  cfId: undefined,
  statusCode: 400,
  retryable: false,
  retryDelay: 4.3270874729153475 }

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>InvalidArgument</Code>
    <Message>Unable to validate the following destination configurations</Message>
    <ArgumentName1>arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload, null</ArgumentName1>
    <ArgumentValue1>Not authorized to invoke function [arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload]</ArgumentValue1>
    <RequestId>9E1CB35811ED5828</RequestId>
    <HostId>tWcmPfrAu3As74M/0sJL5uv+pLmaD4oBJXwjzlcoOBsTBh99iRAtzAloSY/LzinSQYmj46cwyfQ=</HostId>
</Error>
</code>```

I've run it with a role assigned to lambda with what I think are all the policies it needs. I could be missing something. I'm using my root access keys to run this script.

I've thought it might be a timing error where S3 needs time to create the bucket before adding the event, but I've waited a while, hardcoded the bucket name, and run my script again which throws the same error.

The weird thing is that if I create the event hook in the S3 UI and immediately delete it, my script works if I hardcode that bucket name into it. It seems like creating the event in the UI adds some needed permissions but I'm not sure what that would be in the SDK or in the console UI.

Any thoughts or things to try? Thanks for your help

答:
You are getting this message because your s3 bucket is missing permissions for invoking your lambda function.

According to AWS documentation! there are two types of permissions required:

Permissions for your Lambda function to invoke services

Permissions for Amazon S3 to invoke your Lambda function

You should create an object of type 'AWS::Lambda::Permission' and it should look similar to this:

```<code>{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement": [
    {
      "Sid": "<optional>",
      "Effect": "Allow",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "<ArnToYourFunction>",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "<YourAccountId>"
        },
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:s3:::<YourBucketName>"
        }
      }
    }
  ]
}
</code>```

Body:
I'm trying to create an S3 bucket and immediately assign a lambda notification event to it.

Here's the node test script I wrote:

const aws = require('aws-sdk');
const uuidv4 = require('uuid/v4');

aws.config.update({
  accessKeyId: 'key',
  secretAccessKey:'secret',
  region: 'us-west-1'
});

const s3 = new aws.S3();

const params = {
  Bucket: `bucket-${uuidv4()}`,
  ACL: "private",
  CreateBucketConfiguration: {
    LocationConstraint: 'us-west-1'
  }
};

s3.createBucket(params, function (err, data) {
  if (err) {
    throw err;
  } else {
    const bucketUrl = data.Location;

    const bucketNameRegex = /bucket-[a-z0-9\-]+/;
    const bucketName = bucketNameRegex.exec(bucketUrl)[0];

    const params = {
      Bucket: bucketName,
      NotificationConfiguration: {
        LambdaFunctionConfigurations: [
          {
            Id: `lambda-upload-notification-${bucketName}`,
            LambdaFunctionArn: 'arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload',
            Events: ['s3:ObjectCreated:CompleteMultipartUpload']
          },
        ]
      }
    };

    // Throws "Unable to validate the following destination configurations" until an event is manually added and deleted from the bucket in the AWS UI Console
    s3.putBucketNotificationConfiguration(params, function(err, data) {
      if (err) {
        console.error(err);
        console.error(this.httpResponse.body.toString());
      } else {
        console.log(data);
      }
    });
  }
});

The creation works fine but calling s3.putBucketNotificationConfiguration from the aws-sdk throws:

{ InvalidArgument: Unable to validate the following destination configurations
    at Request.extractError ([...]/node_modules/aws-sdk/lib/services/s3.js:577:35)
    at Request.callListeners ([...]/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
    at Request.emit ([...]/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
    at Request.emit ([...]/node_modules/aws-sdk/lib/request.js:683:14)
    at Request.transition ([...]/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo ([...]/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at [...]/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> ([...]/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> ([...]/node_modules/aws-sdk/lib/request.js:685:12)
    at Request.callListeners ([...]/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
  message: 'Unable to validate the following destination configurations',
  code: 'InvalidArgument',
  region: null,
  time: 2017-11-10T02:55:43.004Z,
  requestId: '9E1CB35811ED5828',
  extendedRequestId: 'tWcmPfrAu3As74M/0sJL5uv+pLmaD4oBJXwjzlcoOBsTBh99iRAtzAloSY/LzinSQYmj46cwyfQ=',
  cfId: undefined,
  statusCode: 400,
  retryable: false,
  retryDelay: 4.3270874729153475 }

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    InvalidArgument
    <Message>Unable to validate the following destination configurations</Message>
    <ArgumentName1>arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload, null</ArgumentName1>
    <ArgumentValue1>Not authorized to invoke function [arn:aws:lambda:us-west-1:xxxxxxxxxx:function:respondS3Upload]</ArgumentValue1>
    <RequestId>9E1CB35811ED5828</RequestId>
    <HostId>tWcmPfrAu3As74M/0sJL5uv+pLmaD4oBJXwjzlcoOBsTBh99iRAtzAloSY/LzinSQYmj46cwyfQ=</HostId>
</Error>

I've run it with a role assigned to lambda with what I think are all the policies it needs. I could be missing something. I'm using my root access keys to run this script.

I've thought it might be a timing error where S3 needs time to create the bucket before adding the event, but I've waited a while, hardcoded the bucket name, and run my script again which throws the same error.

The weird thing is that if I create the event hook in the S3 UI and immediately delete it, my script works if I hardcode that bucket name into it. It seems like creating the event in the UI adds some needed permissions but I'm not sure what that would be in the SDK or in the console UI.

Any thoughts or things to try? Thanks for your help

Body:
You are getting this message because your s3 bucket is missing permissions for invoking your lambda function.

According to AWS documentation! there are two types of permissions required:

Permissions for your Lambda function to invoke services

Permissions for Amazon S3 to invoke your Lambda function

You should create an object of type 'AWS::Lambda::Permission' and it should look similar to this:

{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement": [
    {
      "Sid": "<optional>",
      "Effect": "Allow",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "<ArnToYourFunction>",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "<YourAccountId>"
        },
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:s3:::<YourBucketName>"
        }
      }
    }
  ]
}


问:
How to pass input json along with S3 event trigger in AWS lambda
I want to pass some input json along with S3 event trigger data to AWS lambda function.

So  i would like to configure AWS lambda with S3 file put Event and add input target as Constant ie {"job_name":"job1"} ?Is this even possible as far as i know im able to do this using Cloudwatch Event by passing input constant Json but it replaces the actual Cloudwatch event data

Would like to know how can i pass input json along with S3 event trigger data to AWS lambda function

答:
This is not currently possible. When the S3 event is triggered it will replace the event object with the one sent from S3.

As an alternative approach, you can store some details with object metadata in s3 and access from Lambda.


问:
implementing operator * in C++
```<code>class Rational {

 const Rational operator*(const Rational& rhs) const

  ...
};

 Rational oneHalf(1,2);

 Rational result = oneHalf * 2;   // fine (with non-explicit ctor)
 result          = 2 * oneHalf;  // error! (even with non-explicit ctor)
</code>```

It was mentioned by scott meyers in Effective C++ book as below

Even when Rationl's constructor is not explicit, one compiles and one doesnot. Reason is given as below:

It turns out that parameters are eligible for implicit conversion "only if they are listed in the parameter list".

The implicit parameter corresponding to object on which member function is invoked -- the one  "this" points to -- is
 never eligible  for implicit conversions.  That's way first call compiles and the second one doesnot.

My question is what does author mean in above statment "only if they are listed in the parameter list" ? What is parameter list?

答: He means that function arguments may be implicitly converted, but something that would form *this for the function will never be implicitly converted.

Title: implementing operator * in C++

Body:
class Rational {

 const Rational operator*(const Rational& rhs) const

  ...
};

 Rational oneHalf(1,2);

 Rational result = oneHalf * 2;   // fine (with non-explicit ctor)
 result          = 2 * oneHalf;  // error! (even with non-explicit ctor)

It was mentioned by scott meyers in Effective C++ book as below

Even when Rationl's constructor is not explicit, one compiles and one doesnot. Reason is given as below:

It turns out that parameters are eligible for implicit conversion "only if they are listed in the parameter list".

The implicit parameter corresponding to object on which member function is invoked -- the one  "this" points to -- is
 never eligible  for implicit conversions.  That's way first call compiles and the second one doesnot.

My question is what does author mean in above statment "only if they are listed in the parameter list" ? What is parameter list?


问:
Display selected checkbox in Textarea
Users want to select maximum 5 checkboxes and the values should display in the textarea. Validation is working fine and the values are coming to textarea. But when I click more than 5 checkboxes, sixth value is coming to textarea. Please check the below code and help me to fix.

If I select four or five checkboxes those values should be displayed in the textarea. Currently it display more than selected.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea></code>```

答:
Counting starts from 0 in programming so you need to use < 5.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length < 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea></code>```

Title: Display selected checkbox in Textarea

Body:
Users want to select maximum 5 checkboxes and the values should display in the textarea. Validation is working fine and the values are coming to textarea. But when I click more than 5 checkboxes, sixth value is coming to textarea. Please check the below code and help me to fix.

If I select four or five checkboxes those values should be displayed in the textarea. Currently it display more than selected.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})

    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect

    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer

    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman

    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer

    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer

    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer

    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect

    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor

    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer

    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea>

Body:
Counting starts from 0 in programming so you need to use < 5.

$(document).ready(function() {
    $('label.chkskillsedit>input[type=checkbox].hid').on('change', function(evt) {
        if ($('label.chkskillsedit>input[type=checkbox]:checked').length < 5) {
            $(this).parent('label').toggleClass('highlightcheckboxedit', this.checked);

            function fullskilledit() {
                var allValsedit = [];
                $('label.chkskillsedit :checked').each(function() {
                    allValsedit.push($(this).val());
                });
                $('.txtValueshwskilledit').val(allValsedit);
            };
            $(function() {
                $('.chkskillsedit>input.hid').click(fullskilledit);
                fullskilledit();
            });
        } else {
            $(this).prop('checked', false);
            $(this).parent('label').removeClass('highlightcheckboxedit');
        }
    })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="51" checked>Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="52">Building Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="53">Draftsman</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="54" checked>Interior Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="55">Landscape Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="56">MEP Designer</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color highlightcheckboxedit">
    <input class="hid" name="fr_skills" type="checkbox" value="57" checked>Restoration Architect</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="58">Surveyor</label><br>
<label class="chkskillsedit cursor1 backgroundcolor2-color ">
    <input class="hid" name="fr_skills" type="checkbox" value="59">Sustainable Designer</label><br>
    <br>
    <textarea cols="50" class="txtValueshwskilledit" name="skills" value="">51,54,57</textarea>


问:
Can I pass DATEADD straight into a variable?
In one of the tSQLt tests I am writing I call a method with parameters to fill the expected table like so:

```<code>EXEC Test.Insert_Expected
    @CommencementDt = DATEADD(MONTH, 1, GETDATE)
</code>```

However I am getting an error over the MONTH part of the second line reading:

'Incorrect syntax near MONTH, expecting ( or SELECT'

I'm new to using parameterised methods and was wandering why this wasn't working, and how I might solve it? Thanks

答:
try this instead

```<code>DECLARE @CommencementDt datetime = DATEADD(MONTH, 1, GETDATE())
EXEC Test.Insert_Expected @CommencementDt
</code>```

because you can't directly pass the result of a function into the input of a stored procedure. instead, you have to assign the result of the function to a variable and pass that variable to the sp

Body:
In one of the tSQLt tests I am writing I call a method with parameters to fill the expected table like so:

EXEC Test.Insert_Expected
    @CommencementDt = DATEADD(MONTH, 1, GETDATE)

However I am getting an error over the MONTH part of the second line reading:

'Incorrect syntax near MONTH, expecting ( or SELECT'

I'm new to using parameterised methods and was wandering why this wasn't working, and how I might solve it? Thanks

Body:
try this instead

DECLARE @CommencementDt datetime = DATEADD(MONTH, 1, GETDATE())
EXEC Test.Insert_Expected @CommencementDt

because you can't directly pass the result of a function into the input of a stored procedure. instead, you have to assign the result of the function to a variable and pass that variable to the sp


问:
Tizen SDK .NET TV Visual Studio LLDB
I'm currently trying the new Samsung Tizen .NET TV Framework for Visual Studio.
I've followed the instructions to install it and created a basic application to test it.

But when I try to launch the app on the emulator (or on real TV), I've got the following error:

Unable to start debugging. Unable to establish a connection to LLDB. The following message was written to stderr: closed. See Output Window for details.

In the Output Window I've got the following message for the emulator:

```<code>Starting: "C:\tizen-studio\tools\sdb.exe"  -s emulator-26101 shell sh -c 'launch_app org.tizen.example.TizenVisualTest.Tizen.TV   __AUL_SDK__ LLDB-SERVER __DLP_DEBUG_ARG__ g,--platform=host,*:1234,-- CORECLR_GDBJIT TizenVisualTest.dll,TizenVisualTest.Tizen.TV.dll;/home/owner/share/tmp/sdk_tools/lldb/bin/lldb-mi'
closed
"C:\tizen-studio\tools\sdb.exe" exited with code 1 (0x1).
</code>```

And for TV:

```<code>Starting: "C:\tizen-studio\tools\sdb.exe"  -s 10.20.1.79:26101 shell sh -c 'launch_app org.tizen.example.TizenVisualTest.Tizen.TV   __AUL_SDK__ LLDB-SERVER __DLP_DEBUG_ARG__ g,--platform=host,*:1234,-- CORECLR_GDBJIT TizenVisualTest.dll,TizenVisualTest.Tizen.TV.dll;/lldb/bin/lldb-mi'
... launch failed
sh: /lldb/bin/lldb-mi: No such file or directory
"C:\tizen-studio\tools\sdb.exe" exited with code 0 (0x0).
</code>```

答:
Alright, after more investigations and tests with SDB command, I've found out that there's here two different problems:

For the emulator: the platform wasn't correctly configured in emulator manager - it was set to tv-samsung-4.0 instead of tv-4.0 wich seemed to cause the error

For the TV: the Tizen SDK version of my device is 2.4 or the .NET SDK is for 4.0 or more

Title: Tizen SDK .NET TV Visual Studio LLDB

Body:
I'm currently trying the new Samsung Tizen .NET TV Framework for Visual Studio.
I've followed the instructions to install it and created a basic application to test it.

But when I try to launch the app on the emulator (or on real TV), I've got the following error:

Unable to start debugging. Unable to establish a connection to LLDB. The following message was written to stderr: closed. See Output Window for details.

In the Output Window I've got the following message for the emulator:

Starting: "C:\tizen-studio\tools\sdb.exe"  -s emulator-26101 shell sh -c 'launch_app org.tizen.example.TizenVisualTest.Tizen.TV   __AUL_SDK__ LLDB-SERVER __DLP_DEBUG_ARG__ g,--platform=host,*:1234,-- CORECLR_GDBJIT TizenVisualTest.dll,TizenVisualTest.Tizen.TV.dll;/home/owner/share/tmp/sdk_tools/lldb/bin/lldb-mi'
closed
"C:\tizen-studio\tools\sdb.exe" exited with code 1 (0x1).

And for TV:

Starting: "C:\tizen-studio\tools\sdb.exe"  -s 10.20.1.79:26101 shell sh -c 'launch_app org.tizen.example.TizenVisualTest.Tizen.TV   __AUL_SDK__ LLDB-SERVER __DLP_DEBUG_ARG__ g,--platform=host,*:1234,-- CORECLR_GDBJIT TizenVisualTest.dll,TizenVisualTest.Tizen.TV.dll;/lldb/bin/lldb-mi'
... launch failed
sh: /lldb/bin/lldb-mi: No such file or directory
"C:\tizen-studio\tools\sdb.exe" exited with code 0 (0x0).


答:
```<code>#!/bin/bash

function practice() {
    echo "${1}"
}

 while getopts "h:" opt; do
  case "$opt" in
  a) practice $*
    ;;
  esac
 done

exit 0
</code>```

pass the command line arguments to the function as above.

Title: Command line argument not working when passing to a function while using getopts

Body:
#!/bin/bash

function practice() {
    echo "${1}"
}

 while getopts "h:" opt; do
  case "$opt" in
  a) practice $*
    ;;
  esac
 done

exit 0

pass the command line arguments to the function as above.


问:
Piwik tracking code
I am adding piwik script into my website. And I have added the trackingcode js file ie

```<code>if(domains && tracker_url && site_id ) {
var _paq = _paq || [];
_paq.push(["setDomains", [domains]]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
(function() {
    var u= tracker_url;
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', site_id]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();

}
</code>```

My question is do we need to include any piwik files other than this? ie whether we need to include the piwik.js file and all? Is there any package that is to be included into web root?

答:
No, there is nothing else that needs to be included.

The tracking code loads the piwik.js (asynchronously) which then includes everything needed for the tracking.

Title: Piwik tracking code

Body:
I am adding piwik script into my website. And I have added the trackingcode js file ie

if(domains && tracker_url && site_id ) {
var _paq = _paq || [];
_paq.push(["setDomains", [domains]]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
(function() {
    var u= tracker_url;
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', site_id]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();

}

My question is do we need to include any piwik files other than this? ie whether we need to include the piwik.js file and all? Is there any package that is to be included into web root?


问:
I need to want how to Post/Upload a recorded or selected video to server using binary formate and mp4 type in objective c
Hi I just used image picker view to record a video and convert the video formate mov to mp4 and change NSData for posting. But it is not working I get 415 error some times 500 errors. Please check below code for how I implemented. Anybody can guid or help me for this issue.

if I need to check my server side team , they test with postman it is working well when I am implement of below code it is not working if may did any mistakes please guid me thank you

```<code>-(void)camerabuttonHandlerqas{

UIAlertController * picker = [UIAlertController alertControllerWithTitle:@"Pick an image using" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;

UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { }];

UIAlertAction* takeVideo = [UIAlertAction actionWithTitle:@"TakeVideo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

imagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];

imagePicker.view.tag = 100;

[self presentViewController:imagePicker animated:YES completion:nil]; }];
[picker addAction:picture];

[picker addAction:cancel];

picker.view.tintColor = [UIColor grayColor];
[self presentViewController:picker animated:YES completion:nil];

}

#pragma mark - <UIImagePickerControllerDelegate>

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

videoURL = info[UIImagePickerControllerMediaURL];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString* videoPath = [NSString stringWithFormat:@"%@/test_%d.mp4", [paths objectAtIndex:0],arc4random_uniform(1000)];

NSURL *outputURL = [NSURL fileURLWithPath:videoPath];

[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)

{

switch (exportSession.status) {
     case AVAssetExportSessionStatusFailed:
         NSLog(@"status failed");
         break;
     case AVAssetExportSessionStatusCompleted:{
         NSLog(@"status success %@ ",videoPath);
         NSMutableDictionary *data = [NSMutableDictionary new];

         videoURL = info[UIImagePickerControllerMediaURL];

         [data setObject:[self generatePostDataForData:[NSData dataWithContentsOfFile:videoPath]] forKey:@"SelectedvideoURL"];
         imagePickerIsSelected = YES;
         [self postData:data];
         break;

     }

}];

[picker dismissViewControllerAnimated:YES completion:nil]; }
- (NSData *)generatePostDataForData:(NSData *)uploadData

{    // Generate the post header:

NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\";

filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];

    // Get the post header int ASCII format:

NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Generate the mutable data variable:

NSMutableData *postData = [[NSMutableData alloc] initWithLength: [postHeaderData length] ];
[postData setData:postHeaderData];

// Add the image:
// Add the closing boundry:

[postData appendData: [@"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];

// Return the post data:

return postData;
}

-(void) postData:(NSData *)data

{

service = [NSString stringWithFormat:@"http://1.1.1.1:8080/testing/postapi/photoUpload/uploadVideo?videoName=video_%d&type=mp4",arc4random_uniform(1000)]

delegate = delegateInstance;
service = [service stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLFragmentAllowedCharacterSet]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:service]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

[request setHTTPShouldHandleCookies:NO];

[request setTimeoutInterval:60];

[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header

[request setValue:@"mp4/MOV" forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];

// add image data

if (videoData) {
    [body appendData:videoData];
}

// setting the body of the post to the reqeust

[request setHTTPBody:videoData];

// set URL

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                            if (error) {
                                                NSLog(@"%@", error);
                                            } else {
                                                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                NSLog(@"%@", httpResponse);

} }]; [dataTask resume]; }
</code>```

答:
I got solution that code is absolutely right and no need to change media type to mp4 if server side accept .mov type and please discuss with server side then have to change content type, and take file like as a one data then its working for me

Thank you.

Body:
Hi I just used image picker view to record a video and convert the video formate mov to mp4 and change NSData for posting. But it is not working I get 415 error some times 500 errors. Please check below code for how I implemented. Anybody can guid or help me for this issue.

if I need to check my server side team , they test with postman it is working well when I am implement of below code it is not working if may did any mistakes please guid me thank you

-(void)camerabuttonHandlerqas{

UIAlertController * picker = [UIAlertController alertControllerWithTitle:@"Pick an image using" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;

UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { }];

UIAlertAction* takeVideo = [UIAlertAction actionWithTitle:@"TakeVideo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

imagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];

imagePicker.view.tag = 100;

[self presentViewController:imagePicker animated:YES completion:nil]; }];
[picker addAction:picture];

[picker addAction:cancel];

picker.view.tintColor = [UIColor grayColor];
[self presentViewController:picker animated:YES completion:nil];

}

#pragma mark - <UIImagePickerControllerDelegate>

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

videoURL = info[UIImagePickerControllerMediaURL];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString* videoPath = [NSString stringWithFormat:@"%@/test_%d.mp4", [paths objectAtIndex:0],arc4random_uniform(1000)];

NSURL *outputURL = [NSURL fileURLWithPath:videoPath];

[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)

{

switch (exportSession.status) {
     case AVAssetExportSessionStatusFailed:
         NSLog(@"status failed");
         break;
     case AVAssetExportSessionStatusCompleted:{
         NSLog(@"status success %@ ",videoPath);
         NSMutableDictionary *data = [NSMutableDictionary new];

         videoURL = info[UIImagePickerControllerMediaURL];

         [data setObject:[self generatePostDataForData:[NSData dataWithContentsOfFile:videoPath]] forKey:@"SelectedvideoURL"];
         imagePickerIsSelected = YES;
         [self postData:data];
         break;

     }

}];

[picker dismissViewControllerAnimated:YES completion:nil]; }
- (NSData *)generatePostDataForData:(NSData *)uploadData

{    // Generate the post header:

NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\";

filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];

    // Get the post header int ASCII format:

NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

// Generate the mutable data variable:

NSMutableData *postData = [[NSMutableData alloc] initWithLength: [postHeaderData length] ];
[postData setData:postHeaderData];

// Add the image:
// Add the closing boundry:

[postData appendData: [@"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];

// Return the post data:

return postData;
}

-(void) postData:(NSData *)data

{

service = [NSString stringWithFormat:@"http://1.1.1.1:8080/testing/postapi/photoUpload/uploadVideo?videoName=video_%d&type=mp4",arc4random_uniform(1000)]

delegate = delegateInstance;
service = [service stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLFragmentAllowedCharacterSet]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString:service]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

[request setHTTPShouldHandleCookies:NO];

[request setTimeoutInterval:60];

[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header

[request setValue:@"mp4/MOV" forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];

// add image data

if (videoData) {
    [body appendData:videoData];
}

// setting the body of the post to the reqeust

[request setHTTPBody:videoData];

// set URL

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                                            if (error) {
                                                NSLog(@"%@", error);
                                            } else {
                                                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                NSLog(@"%@", httpResponse);

} }]; [dataTask resume]; }


答:
Change your if condition like this

```<code>if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 4) {
</code>```

because when you click on it, it gets checked and then it checkes the if condition. So before the 6th one gets checked and added to textarea, we need to stop that.

Title: Display selected checkbox in Textarea

Body:
Change your if condition like this

if ($('label.chkskillsedit>input[type=checkbox]:checked').length <= 4) {

because when you click on it, it gets checked and then it checkes the if condition. So before the 6th one gets checked and added to textarea, we need to stop that.


问:
A unique key to use in query operations for the view
I have this view table in sql server and I want to make it a unique key for each record in a separate column.

how I can make it a unique key for each record in a separate column? like index for example

This is the code created the view

```<code>SELECT     'order' AS type, id AS id, id_customer, amount AS debit, 0 AS credit, order_date AS date, '....' AS description
FROM         dbo.Orders
UNION ALL
SELECT     'receipt' AS type, id AS id, id_customer, 0 AS debit, amount AS credit, receipt_date AS date, 'cash' AS description
FROM         dbo.receipts
</code>```

I am asking this presentation using this code
But I have a problem when there is an invoice and receipt similar id number is repeated each one of them twice so I want a unique key to do the comparison in the following code

```<code>declare @id_customer int
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]
</code>```

答:
If you want to distinguish your records with a new unique key (as I understand) then you shall use the NEWID for your selection in order to have a unique key for the UnionAll query:</p>

```<code>declare @id_customer int
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select NEWID(), -- this is a new generated unique key
        [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]
</code>```

Body:
I have this view table in sql server and I want to make it a unique key for each record in a separate column.

how I can make it a unique key for each record in a separate column? like index for example

This is the code created the view

SELECT     'order' AS type, id AS id, id_customer, amount AS debit, 0 AS credit, order_date AS date, '....' AS description
FROM         dbo.Orders
UNION ALL
SELECT     'receipt' AS type, id AS id, id_customer, 0 AS debit, amount AS credit, receipt_date AS date, 'cash' AS description
FROM         dbo.receipts

I am asking this presentation using this code
But I have a problem when there is an invoice and receipt similar id number is repeated each one of them twice so I want a unique key to do the comparison in the following code

declare @id_customer int
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]

Body:
If you want to distinguish your records with a new unique key (as I understand) then you shall use the NEWID for your selection in order to have a unique key for the UnionAll query:

declare @id_customer int
;with initial as(
  select *
  from result
  where id_customer= @id_customer
),report as(
  select r.id,[balance]=isnull((select sum(b.debit-b.credit)
               from initial b
               where b.[date]<r.[date]) + r.debit - r.credit ,r.debit-r.credit)
  from initial r
)

 select NEWID(), -- this is a new generated unique key
        [Operation type] = type,
        reference_no = r.id,
        [description],
        [Debit] = debit,
        [Credit] = credit,
        [Balance] = b.balance
 from result r
 inner join report b on b.id = r.id
 where r.id_customer = @id_customer
 order by r.[date]


问:
Mongodb Sorting returns null instead of data
My Mongodb dataset is like this

```<code>{
    "_id" : ObjectId("5a27cc4783800a0b284c7f62"),
    "action" : "1",
    "silent" : "0",
    "createdate" : ISODate("2017-12-06T10:53:59.664Z"),
    "__v" : 0
}
</code>```

Now I have to find the data whose Action value is 1 and silent value is 0. one more thing is that all the data returns is descending Order.
My Mongodb Query is

```<code>db.collection.find({'action': 1, 'silent': 0}).sort({createdate: -1}).exec(function(err, post) {
            console.log(post.length);
});
</code>```

Earlier It works Fine for me But Now I have 121000 entry on this Collection. Now it returns null.

```<code>I know there is some confusion on .sort()
</code>```

If i remove the sort Query then everything is fine. Example

```<code>db.collection.find({'action': 1, 'silent': 0}).exec(function(err, post) {
            console.log(post.length);// Now it returns data but not on Descending order
});
</code>```

答:
MongoDB limits the amount of data it will attempt to sort without an index .
This is because Mongo has to sort the data in memory or on disk, both of which can be expensive operations, particularly for queries run frequently.

In most cases, this can be alleviated by creating indexes on the fields you sort on.

you can create index with :-

```<code>db.myColl.createIndex( { createdate: 1 })
</code>```

thanks !

Body:
My Mongodb dataset is like this

{
    "_id" : ObjectId("5a27cc4783800a0b284c7f62"),
    "action" : "1",
    "silent" : "0",
    "createdate" : ISODate("2017-12-06T10:53:59.664Z"),
    "__v" : 0
}

Now I have to find the data whose Action value is 1 and silent value is 0. one more thing is that all the data returns is descending Order.
My Mongodb Query is

db.collection.find({'action': 1, 'silent': 0}).sort({createdate: -1}).exec(function(err, post) {
            console.log(post.length);
});

Earlier It works Fine for me But Now I have 121000 entry on this Collection. Now it returns null.

I know there is some confusion on .sort()

If i remove the sort Query then everything is fine. Example

db.collection.find({'action': 1, 'silent': 0}).exec(function(err, post) {
            console.log(post.length);// Now it returns data but not on Descending order
});

Body:
MongoDB limits the amount of data it will attempt to sort without an index .
This is because Mongo has to sort the data in memory or on disk, both of which can be expensive operations, particularly for queries run frequently.

In most cases, this can be alleviated by creating indexes on the fields you sort on.

you can create index with :-

db.myColl.createIndex( { createdate: 1 })

thanks !