问:
How to disable access - request to standard MVC Controller with Bearer token
I have simple Cookie and Bearer Token authorization in my MVC project with WebApi. I want to disable access by Bearer on my standard MVC controllers.

This is my situation now:

Standard MVC controllers access: Bearer or Cookie

Web Api controllers access: only Bearer

I want to have:

Standard MVC controllers access: only Cookie

Web Api controllers access: only Bearer

WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter("Bearer"));
    }
}
</code>```

Startup.Auth.cs

```<code>public partial class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
}
</code>```

Is it possible to have custom authorization attribute? Like this: [Authorize("OnlyCookie"]

I saw similar solution, but it was for SinglePageAplication, and I dont know how to implement it in my .NET MVC 4 application - I saw it here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme

When I tried add 'AuthenticationScheme = "Cookie"', compilator gives me error: CookieAuthenticationOptions' does not contain a definition for 'AuthenticationScheme

答:
You don't that property because you're not using ASP.Net Core. The link you post on your question is ASP.Net Core not ASP.NEt MVC.

You can do the same by creating a custom authorization filter attribute. Let name it CustomAuthorizeAttribute and the implementation will be:

```<code>public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string AuthenticationType { get; private set; }

    public CustomAuthorize(string authenticationType)
    {
        if (string.IsNullOrWhiteSpace(authenticationType))
        {
            throw new ArgumentNullException(nameof(authenticationType));
        }

        this.AuthenticationType = authenticationType;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.AuthenticationType.Equals(this.AuthenticationType, StringComparison.InvariantCultureIgnoreCase))
        {
            return false;
        }

        return base.AuthorizeCore(httpContext);
    }
}
</code>```

So you can use it like this on your controller:

```<code>[CustomAuthorize(DefaultAuthenticationTypes.ApplicationCookie)]
</code>```

Body:
I have simple Cookie and Bearer Token authorization in my MVC project with WebApi. I want to disable access by Bearer on my standard MVC controllers.

This is my situation now:

Standard MVC controllers access: Bearer or Cookie

Web Api controllers access: only Bearer

I want to have:

Standard MVC controllers access: only Cookie

Web Api controllers access: only Bearer

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter("Bearer"));
    }
}

Startup.Auth.cs

public partial class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
}

Is it possible to have custom authorization attribute? Like this: [Authorize("OnlyCookie"]

I saw similar solution, but it was for SinglePageAplication, and I dont know how to implement it in my .NET MVC 4 application - I saw it here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme

When I tried add 'AuthenticationScheme = "Cookie"', compilator gives me error: CookieAuthenticationOptions' does not contain a definition for 'AuthenticationScheme

Body:
You don't that property because you're not using ASP.Net Core. The link you post on your question is ASP.Net Core not ASP.NEt MVC.

You can do the same by creating a custom authorization filter attribute. Let name it CustomAuthorizeAttribute and the implementation will be:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string AuthenticationType { get; private set; }

    public CustomAuthorize(string authenticationType)
    {
        if (string.IsNullOrWhiteSpace(authenticationType))
        {
            throw new ArgumentNullException(nameof(authenticationType));
        }

        this.AuthenticationType = authenticationType;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.AuthenticationType.Equals(this.AuthenticationType, StringComparison.InvariantCultureIgnoreCase))
        {
            return false;
        }

        return base.AuthorizeCore(httpContext);
    }
}

So you can use it like this on your controller:

[CustomAuthorize(DefaultAuthenticationTypes.ApplicationCookie)]


来源: stackexchange

问:
Live jQuery events not firing for dynamic element
Why are none of the live (or dead) events I bind to a dynamic element firing?

```<code>(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);
</code>```

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

```<code>var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});
</code>```

答:
.live() works off a selector (since it checks the target against the selector at the time the event happens), you can't attach it directly to an element...you should just use .click() in these cases:

```<code>(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").click(function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);
</code>```

You can try it out here, or a bit shorter with .insertBefore():

```<code>(function ($) {
  $.fn.myPlugin = function () {
    $("<input type='text'>").click(function () {
        alert("Clicked");
    }).insertBefore(this);
    return this;
  };
})(jQuery);
</code>```

You can test it here.

ContentLicense: CC BY-SA 2.5

Body:
Why are none of the live (or dead) events I bind to a dynamic element firing?

(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").live("click", function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);

I am calling myPlugin on several <select> elements. I thought it would work without the Live plugin if I bound it before adding the element to the DOM, but not even the live events are firing. Is it because my element has no ID?

Edit:
The following does not work either:

var $filterBox = $("<input type='text'>").bind("click", function () {
        alert("Clicked");
});

Body:
.live() works off a selector (since it checks the target against the selector at the time the event happens), you can't attach it directly to an element...you should just use .click() in these cases:

(function ($) {
    $.fn.myPlugin = function () {

    var $filterBox = $("<input type='text'>").click(function () {
        alert("Clicked");
    });
    this.before($filterBox); // insert into DOM before current element
    return this; // keep chain
    };
})(jQuery);

You can try it out here, or a bit shorter with .insertBefore():

(function ($) {
  $.fn.myPlugin = function () {
    $("<input type='text'>").click(function () {
        alert("Clicked");
    }).insertBefore(this);
    return this;
  };
})(jQuery);

You can test it here.


问:
Customizing VBA button in Excel ribbon
Let's say we have code that prints a variable's value.

```<code>Dim ii as String
ii = "This is a test"
MsgBox(ii)
</code>```

The code is run by pushing a button, in the Excel ribbon, linked to the VBA code.

Is there any way to set the value for the variable "ii" in the Excel ribbon, adding a bit of user friendly customization to the VBA code?

Preferably the user could right click the button to change the variable's value, and Excel would remember this change for all workbooks.

答:
You can use the following Microsoft tutorial to add a button to the ribbon and have it call a VBA macro.

Global variables must be stored in a standard module or in the document module. If it needs to be initialized when the workbook is opened, regardless of where it is stored, the value must be set either during WorkbookOpen event, or by a macro called by this event. Just in case, here is a link to the Chip Pearson event tutorial.

If the value of your variable needs to be preserved between sessions (uses), then it will have to be saved to a cell in a worksheet. Hidden or very hidden worksheets work well for this purpose. If the value is reset between sessions,  you can hardcode a default value in the module.

This should be all you need to get going. You will probably have to use a few macros to get the exact result you are looking for. Ultimately, this will depend on what you wish to accomplish.

ContentLicense: CC BY-SA 4.0

Title: Customizing VBA button in Excel ribbon

Body:
Let's say we have code that prints a variable's value.

Dim ii as String
ii = "This is a test"
MsgBox(ii)

The code is run by pushing a button, in the Excel ribbon, linked to the VBA code.

Is there any way to set the value for the variable "ii" in the Excel ribbon, adding a bit of user friendly customization to the VBA code?

Preferably the user could right click the button to change the variable's value, and Excel would remember this change for all workbooks.

ContentLicense: CC BY-SA 3.0


问:
Basic router template example - no url access
I am trying to set a basic example of react router where I have two simple routes, greetings and signup, under a template setup. Currently, I am not getting any errors on load, however, when trying to access the /signup route by typing it in to the address bar, I am getting the following error: Cannot GET /signup and I am having trouble understanding why.

Did anyone else run into this issue with react-router-dom v4? I appreciate any suggestions on how to resolve this issue and allow the successful navigation to different paths via URL.

Note, if I try to access these url paths using the built in react Link component and clicking on the link, its works as expected, but when refreshing the page at the url, I get the Cannot GET signup error again.

app.js

```<code>import React from "react";
import NavigationBar from '../components/navigation-bar';

export class App extends React.Component {
    render() {
        return (
            <div className="container">
                <NavigationBar />
                {this.props.children}
            </div>
        );
    }
}
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from "react-dom";
import {Provider} from "react-redux";
import {createStore} from "redux";
import allReducers from "./reducers";

import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import {App} from "./components/app";
import {Greetings} from "./components/greetings";
import {Signup} from "./components/signup";

const store = createStore(allReducers);

ReactDOM.render(
                <Provider store={store}>
                    <Router>
                        <App>
                            <Switch>
                                <Route exact path="/" component={Greetings} />
                                <Route path="/signup" component={Signup} />
                            </Switch>
                        </App>
                    </Router>

                </Provider>, window.document.getElementById("app"));
</code>```

greetings.js

```<code>import React from "react";

export class Greetings extends React.Component {
    render() {
        return (
            <h2>
                Greetings
            </h2>
        );
    }
}
</code>```

signup.js

```<code>import React from "react";

    export class Signup extends React.Component {
        render() {
            return (
                <h2>
                    SIGN UP
                </h2>
            );
        }
    }
</code>```

答:
Try using HashRouter over BrowserRouter because to use BrowserRouter web server must be ready to handle real URLs.

```<code>import {HashRouter as Router, Route, Switch} from "react-router-dom";
</code>```

Body:
I am trying to set a basic example of react router where I have two simple routes, greetings and signup, under a template setup. Currently, I am not getting any errors on load, however, when trying to access the /signup route by typing it in to the address bar, I am getting the following error: Cannot GET /signup and I am having trouble understanding why.

Did anyone else run into this issue with react-router-dom v4? I appreciate any suggestions on how to resolve this issue and allow the successful navigation to different paths via URL.

Note, if I try to access these url paths using the built in react Link component and clicking on the link, its works as expected, but when refreshing the page at the url, I get the Cannot GET signup error again.

app.js

import React from "react";
import NavigationBar from '../components/navigation-bar';

export class App extends React.Component {
    render() {
        return (

                <NavigationBar />
                {this.props.children}

        );
    }
}

index.js

import React from 'react';
import ReactDOM from "react-dom";
import {Provider} from "react-redux";
import {createStore} from "redux";
import allReducers from "./reducers";

import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import {App} from "./components/app";
import {Greetings} from "./components/greetings";
import {Signup} from "./components/signup";

const store = createStore(allReducers);

ReactDOM.render(
                <Provider store={store}>
                    <Router>
                        <App>
                            <Switch>
                                <Route exact path="/" component={Greetings} />
                                <Route path="/signup" component={Signup} />
                            </Switch>
                        </App>
                    </Router>

                </Provider>, window.document.getElementById("app"));

greetings.js

import React from "react";

export class Greetings extends React.Component {
    render() {
        return (

                Greetings

        );
    }
}

signup.js

import React from "react";

    export class Signup extends React.Component {
        render() {
            return (

                    SIGN UP

            );
        }
    }

Body:
Try using HashRouter over BrowserRouter because to use BrowserRouter web server must be ready to handle real URLs.

import {HashRouter as Router, Route, Switch} from "react-router-dom";


问:
Please explain the code snippet that tells whether the given word is unique?
Could someone please explain the working of this code snippet which tells if the given word is unique or not?

```<code>public static boolean isUniqueChars(String str) {
    if (str.length() > 128) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}
</code>```

I don't understand what is happening in the following two lines:

```<code>if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
</code>```

Thank you!

答:
To Understand how it is working in bit level put Integer.toBinaryString() and check. Basically whenever you use bit wise operator in any integral value actual operation happen on there respective binary values.

```<code>public static boolean isUniqueChars(String str) {
        if (str.length() > 128) {
            return false;
        }       int checker = 0;
        for (int i = 0; i < str.length(); i++) {
            int val = str.charAt(i) - 'a';
            System.out.println("Actual Value " + val); // ASCII substraction
            System.out.println("Actual Value in Binary " + Integer.toBinaryString(val));
            System.out.println("Left Shift Value in Binary " + Integer.toBinaryString(1<<val));
            System.out.println("Operator Value is" + Integer.toBinaryString(checker & (1 << val))));
            if ((checker & (1 << val)) > 0)
                return false;
            checker |= (1 << val); // checker = checker | (1<<val)
            System.out.println("Checker Value in Binary " + Integer.toBinaryString(checker));
        }
        return true;
    }
</code>```

Run this and and check those print statement then you can identify how bit wise operator is working.

Logically:
1 is every time left shifted by ASCII substracted value and then BIT(or) is done with previous checker value. If current and checker value BIT(or) returns > 0 that means some bit position of both the value has 1. and thus its a repeating char. I know it sounds little complicate but take your time and debug it.

hope it helps you.

Body:
Could someone please explain the working of this code snippet which tells if the given word is unique or not?

public static boolean isUniqueChars(String str) {
    if (str.length() > 128) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}

I don't understand what is happening in the following two lines:

if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);

Thank you!

Body:
To Understand how it is working in bit level put Integer.toBinaryString() and check. Basically whenever you use bit wise operator in any integral value actual operation happen on there respective binary values.

public static boolean isUniqueChars(String str) {
        if (str.length() > 128) {
            return false;
        }       int checker = 0;
        for (int i = 0; i < str.length(); i++) {
            int val = str.charAt(i) - 'a';
            System.out.println("Actual Value " + val); // ASCII substraction
            System.out.println("Actual Value in Binary " + Integer.toBinaryString(val));
            System.out.println("Left Shift Value in Binary " + Integer.toBinaryString(1<<val));
            System.out.println("Operator Value is" + Integer.toBinaryString(checker & (1 << val))));
            if ((checker & (1 << val)) > 0)
                return false;
            checker |= (1 << val); // checker = checker | (1<<val)
            System.out.println("Checker Value in Binary " + Integer.toBinaryString(checker));
        }
        return true;
    }

Run this and and check those print statement then you can identify how bit wise operator is working.

Logically:
1 is every time left shifted by ASCII substracted value and then BIT(or) is done with previous checker value. If current and checker value BIT(or) returns > 0 that means some bit position of both the value has 1. and thus its a repeating char. I know it sounds little complicate but take your time and debug it.

hope it helps you.


问:
How to improve fetching speed from SQL?
I am not expert at MySQL indexes, but I saw a lot of tutorials, still my page takes 7 seconds to load, using PHP.

I have around 50k rows, and 30 columns in MySQL tables.

How can I improve MySQL Fetching data speed? Anything that I can improve in this below query?

```<code>SELECT tmdb_movies.movie_title,tmdb_movies.budget,tmdb_movies.original_language,tmdb_movies.original_title

,translations.translations_english_name

,videos.videos_name,videos.videos_key

FROM tmdb_movies

LEFT JOIN
(
  SELECT
    translations_tmdb_id
,GROUP_CONCAT(DISTINCT translations.translations_english_name SEPARATOR ', ') AS translations_english_name

  FROM translations
  GROUP BY translations_tmdb_id
) translations ON translations.translations_tmdb_id = tmdb_movies.tmdb_id

LEFT JOIN
(
  SELECT
    videos_tmdb_id
,GROUP_CONCAT(DISTINCT videos.videos_name) as videos_name
,GROUP_CONCAT(DISTINCT videos.videos_key) as videos_key
  FROM videos
  GROUP BY videos_tmdb_id
) videos ON videos.videos_tmdb_id = tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= '$tmdb_id'
</code>```

Here, I use tmdb_id to connect all tables. tmdb_id,translations_tmdb_idand videos_tmdb_id are indexed in MySQL.

Here is a sample of my MySQL table structure:

tmdb_movies table:

```<code>tmdb_id      movie_title
1            Logan
2            Iron Man
3            Superman
</code>```

translations table

```<code>translations_tmdb_id      translations_english_name
1                         English
1                         Hindi
1                         French
2                         English
2                         Spanish
2                         Hindi
</code>```

videos table

```<code>videos_tmdb_id          videos_name
1                       Official Trailer
1                       Trailer 2
2                       Trailer 1
2                       Trailer 2 HD
3                       Superman Trailer 1
3                       Superman Trailer 2
</code>```

答:
Your main SELECT statement is probably fine; you're filtering on the autoincrementing primary key.

It's the two subqueries where the opportunities may lie for improving performance.

The first one:

```<code>  SELECT
    translations_tmdb_id,
    GROUP_CONCAT( DISTINCT translations.translations_english_name
                  SEPARATOR ', ') AS translations_english_name
  FROM translations
  GROUP BY translations_tmdb_id
</code>```

A compound index (sometimes called a composite index or multi-column index) on translations_tmdb_id, translations_english_name has the potential to help this subquery a lot. Why? It can help with both the GROUP BY and the DISTINCT parts of the query.

The second one:

```<code>  SELECT
    videos_tmdb_id
,GROUP_CONCAT(DISTINCT videos.videos_name) as videos_name
,GROUP_CONCAT(DISTINCT videos.videos_key) as videos_key
  FROM videos
  GROUP BY videos_tmdb_id
</code>```

The same priniciple applies, but the two distinct DISTINCT clauses will slow things down a little. Try a compound index on videos_tmdb_id, videos_name, videos_key. It should help.

Title: How to improve fetching speed from SQL?

Body:
I am not expert at MySQL indexes, but I saw a lot of tutorials, still my page takes 7 seconds to load, using PHP.

I have around 50k rows, and 30 columns in MySQL tables.

How can I improve MySQL Fetching data speed? Anything that I can improve in this below query?

SELECT tmdb_movies.movie_title,tmdb_movies.budget,tmdb_movies.original_language,tmdb_movies.original_title

,translations.translations_english_name

,videos.videos_name,videos.videos_key

FROM tmdb_movies

LEFT JOIN
(
  SELECT
    translations_tmdb_id
,GROUP_CONCAT(DISTINCT translations.translations_english_name SEPARATOR ', ') AS translations_english_name

  FROM translations
  GROUP BY translations_tmdb_id
) translations ON translations.translations_tmdb_id = tmdb_movies.tmdb_id

LEFT JOIN
(
  SELECT
    videos_tmdb_id
,GROUP_CONCAT(DISTINCT videos.videos_name) as videos_name
,GROUP_CONCAT(DISTINCT videos.videos_key) as videos_key
  FROM videos
  GROUP BY videos_tmdb_id
) videos ON videos.videos_tmdb_id = tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= '$tmdb_id'

Here, I use tmdb_id to connect all tables. tmdb_id,translations_tmdb_idand videos_tmdb_id are indexed in MySQL.

Here is a sample of my MySQL table structure:

tmdb_movies table:

tmdb_id      movie_title
1            Logan
2            Iron Man
3            Superman

translations table

translations_tmdb_id      translations_english_name
1                         English
1                         Hindi
1                         French
2                         English
2                         Spanish
2                         Hindi

videos table

videos_tmdb_id          videos_name
1                       Official Trailer
1                       Trailer 2
2                       Trailer 1
2                       Trailer 2 HD
3                       Superman Trailer 1
3                       Superman Trailer 2

Body:
Your main SELECT statement is probably fine; you're filtering on the autoincrementing primary key.

It's the two subqueries where the opportunities may lie for improving performance.

The first one:

  SELECT
    translations_tmdb_id,
    GROUP_CONCAT( DISTINCT translations.translations_english_name
                  SEPARATOR ', ') AS translations_english_name
  FROM translations
  GROUP BY translations_tmdb_id

A compound index (sometimes called a composite index or multi-column index) on translations_tmdb_id, translations_english_name has the potential to help this subquery a lot. Why? It can help with both the GROUP BY and the DISTINCT parts of the query.

The second one:

  SELECT
    videos_tmdb_id
,GROUP_CONCAT(DISTINCT videos.videos_name) as videos_name
,GROUP_CONCAT(DISTINCT videos.videos_key) as videos_key
  FROM videos
  GROUP BY videos_tmdb_id

The same priniciple applies, but the two distinct DISTINCT clauses will slow things down a little. Try a compound index on videos_tmdb_id, videos_name, videos_key. It should help.


问:
Android multiple databases open
I am making a IM client for android and I am working with databases for storing the contacts and other info's... In my app I have an activity and one service. I need to open three databases in the same time both on the service and on the activity.

I use three database because I want the databases to be managed more easily without having problems with the synchronization of writing in them. (as far as I know I need to write in the database synchronously because it may crush).

To manage the databases from the service and from the activity in the same time, I thought that a singleton or a static class of DatabaseHelper could help me...

So I have started to make a test by making two databasehelper global objects in the activity, each one opens a diferent database, after running the project i've noticed that the last opened database remains opened in both objects :((, why is this happening?

Can somebody sugest me how can i make this work?
Thank you!

L.E.: after more tests, I made a Static object of databasehelper, open a service from which I take the database object from activity and in the same time i made two for statements, one in activity and one in service that run from 0 to 3000 and adds some values into the same database and then it reads the database.

After this run i noticed that the database is still in feet and running without errors. The strange thing is that the service for is running only after the activity for finishes the job. Why is that?
Thank you!

答:
I have a DatabaseAdapter class which contains two databases which are opened together.

```<code>public class DatabaseAdapter {
    /** Identifier for the internal database */
    public static final int             INTERNAL            = 0;
    /** Identifier for the external database */
    public static final int             EXTERNAL                = 1;

    private final SQLiteOpenHelper[]    mDatabaseManager    = new SQLiteOpenHelper[2];
    private final SQLiteDatabase[]      mDatabases          = new SQLiteDatabase[2];

    /**
     * Constructs the database and open it.
     */
    public DatabaseAdapter() {
        // Open the internal_db
        mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance());
        mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase();
    }

    /**
     * Checks the database state and throws an {@link IllegalStateException} if database isn't open.
     * Should always be used before starting to access the database.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void checkDbState(int type) {
        if (mDatabases[type] == null || !mDatabases[type].isOpen()) {
            throw new IllegalStateException("The database has not been opened");
        }
    }

    /**
     * Closes the database of the given type.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void close(int type) {
        if (mDatabases[type].isOpen()) {
            mDatabases[type].close();
            mDatabases[type] = null;
            if (mDatabaseManager[type] != null) {
                mDatabaseManager[type].close();
                mDatabaseManager[type] = null;
            }
        }
    }

    /**
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     * @return true if the database is open, false otherwise.
     */
    public boolean isOpen(int type) {
        return mDatabases[type] != null && mDatabases[type].isOpen();
    }

    /**
     * Opens the default database.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void open(int type) {
        switch (type) {
            case INTERNAL:
                mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance());
                if (!isOpen(INTERNAL)) {
                    mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase();
                }
            break;
            case EXTERNAL:
                mDatabaseManager[EXTERNAL] = new ExternalDatabaseManager(MyApplication.getInstance(), Constants.EXTERNAL_DB_PATH, 1);
                if (!isOpen(EXTERNAL)) {
                    mDatabases[EXTERNAL] = mDatabaseManager[EXTERNAL].getWritableDatabase();
                }
            break;
        }
    }
}
</code>```

to add a third one should be easy :)

Title: Android multiple databases open

Body:
I have a DatabaseAdapter class which contains two databases which are opened together.

public class DatabaseAdapter {
    /** Identifier for the internal database */
    public static final int             INTERNAL            = 0;
    /** Identifier for the external database */
    public static final int             EXTERNAL                = 1;

    private final SQLiteOpenHelper[]    mDatabaseManager    = new SQLiteOpenHelper[2];
    private final SQLiteDatabase[]      mDatabases          = new SQLiteDatabase[2];

    /**
     * Constructs the database and open it.
     */
    public DatabaseAdapter() {
        // Open the internal_db
        mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance());
        mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase();
    }

    /**
     * Checks the database state and throws an {@link IllegalStateException} if database isn't open.
     * Should always be used before starting to access the database.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void checkDbState(int type) {
        if (mDatabases[type] == null || !mDatabases[type].isOpen()) {
            throw new IllegalStateException("The database has not been opened");
        }
    }

    /**
     * Closes the database of the given type.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void close(int type) {
        if (mDatabases[type].isOpen()) {
            mDatabases[type].close();
            mDatabases[type] = null;
            if (mDatabaseManager[type] != null) {
                mDatabaseManager[type].close();
                mDatabaseManager[type] = null;
            }
        }
    }

    /**
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     * @return true if the database is open, false otherwise.
     */
    public boolean isOpen(int type) {
        return mDatabases[type] != null && mDatabases[type].isOpen();
    }

    /**
     * Opens the default database.
     *
     * @param type Type of the database. Can be INTERNAL or EXTERNAL.
     */
    public void open(int type) {
        switch (type) {
            case INTERNAL:
                mDatabaseManager[INTERNAL] = new InternalDatabaseManager(MyApplication.getInstance());
                if (!isOpen(INTERNAL)) {
                    mDatabases[INTERNAL] = mDatabaseManager[INTERNAL].getWritableDatabase();
                }
            break;
            case EXTERNAL:
                mDatabaseManager[EXTERNAL] = new ExternalDatabaseManager(MyApplication.getInstance(), Constants.EXTERNAL_DB_PATH, 1);
                if (!isOpen(EXTERNAL)) {
                    mDatabases[EXTERNAL] = mDatabaseManager[EXTERNAL].getWritableDatabase();
                }
            break;
        }
    }
}

to add a third one should be easy :)


问:
Concatenate CSV files with pandas
l have csv files to concatenate. l have three files l want to concatenate. The number of columns is the same so the desired output will have also the same columns

file1.csv

```<code>id                                       ocr    raw_value   manual_raw_value
2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0
</code>```

File2

```<code>id                                        ocr   raw_value   manual_raw_value
bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
</code>```

File3

```<code>id                                        ocr   raw_value   manual_raw_value
4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
 Renseignements
507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59
</code>```

Desired output

```<code>         id                                      ocr    raw_value   manual_raw_value

        2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
        0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
        12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
        2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
        f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
        2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
        2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

        bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
        213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
        1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
        35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
        009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
        35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
        218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
        4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
        8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
        52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
         Renseignements
        507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
        52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
        c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
        4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
        4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
        4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
        829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59
</code>```

Here is my code

```<code>import os
import glob
import pandas

def concatenate(indir,outputfile):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    colnames=["id","ocr","raw_value","manual_raw_value"]
    for filename in fileList:
        print(filename)
        df=pandas.read_csv(input,header=None)
        dfList.append(df)
    concatenateDF=pandas.concat(dfList,axis=0)
    concatenateDF.columns=colnames
    concatenateDF.to_save(outputfile,index=None)

if __name__ == "__main__":
    input="/files"
    output="files/concatenated.csv"
    concatenate(input,output)
</code>```

l get the following error :

```<code>Traceback (most recent call last):
  File "/home/ahmed/crnn/concatenate_files.py", line 21, in <module>
    concatenate(input,output)
  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
    df=pandas.read_csv(input,header=None)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 1390, in __init__
words2.csv
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 538, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6171)
pandas.io.common.EmptyDataError: No columns to parse from file
</code>```

What's wrong with my code ?

How can l solve that?

Thank you

答:
Your error is not due to concatenation as mentioned here:

```<code>  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
df=pandas.read_csv(input,header=None)
</code>```

You have unequally spaced columns in your file, the separation between the columns have to be consistent. This question is irrelevant to the error you are getting. I guess, you must have copied the print out of a dataframe from some text.

For example, in file1.csv the number of space between the raw_value and manual_value columns

line#1 is 9

```<code>2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
</code>```

in line#2 is 12

```<code>0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
</code>```

Title: Concatenate CSV files with pandas

Body:
l have csv files to concatenate. l have three files l want to concatenate. The number of columns is the same so the desired output will have also the same columns

file1.csv

id                                       ocr    raw_value   manual_raw_value
2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

File2

id                                        ocr   raw_value   manual_raw_value
bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT

File3

id                                        ocr   raw_value   manual_raw_value
4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
 Renseignements
507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59

Desired output

         id                                      ocr    raw_value   manual_raw_value

        2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20
        0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44
        12973bd0-72c7-4333-ac8d-ab0f18e33cb0    OMNIPAGE    4578     4578
        2ccbeb11-ed0d-49a3-a321-a1c583764e3d    ABBYY        1             1
        f78636d7-c22f-4a85-bb34-fd8757352ec5    ABBYY   8040.56     8040.56
        2d1c5869-1f87-4b47-bbf4-c2f31b122c0b    OMNIPAGE    6        6
        2d914f73-39d9-4108-8467-4d7a28933aa6    OMNIPAGE    0         0

        bfa6c9f1-89c0-486b-a85c-a97a370a92c4    OMNIPAGE    35470       35470
        213e1e1e-29df-44c2-acee-79f7fefa7ba9    OMNIPAGE    Echeance    Ech√©ance
        1ebecadc-056b-41c8-8426-446fff6bad71    OMNIPAGE    Etoblissemenls  Etablissements
        35c1b736-f504-487d-a531-3b133045139e    OMNIPAGE    :               :
        009ee382-c1f2-4194-92e1-9b9fffd387d2    OMNIPAGE    1087         1087
        35dd36a6-7c9c-4f81-b3f7-db6533bd159f    OMNIPAGE    1              1
        218f6860-b6aa-4bba-b64a-c2cc0b40812b    OMNIPAGE    HT               HT
        4a82a357-99e7-49e6-85b6-b2f6a27b8d5f    OMNIPAGE    Terms   Terms
        8b549fef-0cda-4af5-8239-35153c33ffbc    OMNIPAGE    price   price
        52ffe66a-b1ab-4b22-9b26-c298d53c951c    OMNIPAGE    Renseignements
         Renseignements
        507a0d96-9481-4b3f-8c35-f16588bedc0b    OMNIPAGE    pour    pour
        52e171dc-8d22-4162-b748-692b2fc11659    OMNIPAGE    Client  Client
        c40a7e9f-1ec4-4cac-87e8-02ed0f335fe9    OMNIPAGE    5   5
        4a936ed7-c082-4f46-9fa1-761a1525e2df    OMNIPAGE    SAS SAS
        4b78130e-b099-400c-b7bf-6470e0519783    OMNIPAGE    des des
        4d5c6297-1c79-42f9-b4ea-929a9abfb3f7    OMNIPAGE    431 431
        829d8bf5-b251-4bb1-82d8-0e912ab64e8e    OMNIPAGE    59  59

Here is my code

import os
import glob
import pandas

def concatenate(indir,outputfile):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    colnames=["id","ocr","raw_value","manual_raw_value"]
    for filename in fileList:
        print(filename)
        df=pandas.read_csv(input,header=None)
        dfList.append(df)
    concatenateDF=pandas.concat(dfList,axis=0)
    concatenateDF.columns=colnames
    concatenateDF.to_save(outputfile,index=None)

if __name__ == "__main__":
    input="/files"
    output="files/concatenated.csv"
    concatenate(input,output)

l get the following error :

Traceback (most recent call last):
  File "/home/ahmed/crnn/concatenate_files.py", line 21, in <module>
    concatenate(input,output)
  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
    df=pandas.read_csv(input,header=None)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 646, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 389, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 730, in __init__
    self._make_engine(self.engine)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 923, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/pandas/io/parsers.py", line 1390, in __init__
words2.csv
    self._reader = _parser.TextReader(src, **kwds)
  File "pandas/parser.pyx", line 538, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:6171)
pandas.io.common.EmptyDataError: No columns to parse from file

What's wrong with my code ?

How can l solve that?

Thank you

Body:
Your error is not due to concatenation as mentioned here:

  File "/home/ahmed/crnn/concatenate_files.py", line 12, in concatenate
df=pandas.read_csv(input,header=None)

You have unequally spaced columns in your file, the separation between the columns have to be consistent. This question is irrelevant to the error you are getting. I guess, you must have copied the print out of a dataframe from some text.

For example, in file1.csv the number of space between the raw_value and manual_value columns

line#1 is 9

2a909d6e-5eb2-49a1-b6e8-171bf01dafdc    ABBYY   7,20         7,20

in line#2 is 12

0c93bc55-2c42-4afb-8428-c12736b0a86e    ABBYY   44            44


问:
google app engine launcher won't deploy application: says application does not exist
I can deploy from the command line using this command:

```<code>appcfg.py --no_cookies --oauth2 --email=myemail --noauth_local_webserver  update .
</code>```

noauth_local_webserver is what is letting me deploy because it gives me an access token at a location I can access

If I deploy from google app engine launcher, it takes me to a sign in page, I accept, and it returns the token to localhost:8080, and my app isn't running off that port. So the response is "no data received" in a webpage located at localhost:8080

I tried fixing the port by using:

dev_appserver.py --port=11080 .

but that just runs the server from that port, and doesn't solve the launcher problem-- the problem that I can't deploy from the launcher.

More history:

I believe I'm running into this problem because I deployed another app engine project from the launcher under a different email

Now, I'm trying to deploy a different app under a different email from the launcher.

How can I fix the deployment issue from launcher?

答:
Just faced the same issue and this post was very useful - thank-you.

Flow to fix for me was:

1) Delete Google App Engine Launcher config and close Google App Engine Launcher

2) Close browser

3) Open Google App Engine Launcher

4) Re-add config

5) Click Deploy

6) Authenticate on the browser (gets stuck in a loop of "authentication flow succeeded)

7) Hit Run in Google App Engine Launcher

It then deployed and deploys again fine now. Had tried a few other variants but the above cleared the blockage.

Body:
I can deploy from the command line using this command:

appcfg.py --no_cookies --oauth2 --email=myemail --noauth_local_webserver  update .

noauth_local_webserver is what is letting me deploy because it gives me an access token at a location I can access

If I deploy from google app engine launcher, it takes me to a sign in page, I accept, and it returns the token to localhost:8080, and my app isn't running off that port. So the response is "no data received" in a webpage located at localhost:8080

I tried fixing the port by using:

dev_appserver.py --port=11080 .

but that just runs the server from that port, and doesn't solve the launcher problem-- the problem that I can't deploy from the launcher.

More history:

I believe I'm running into this problem because I deployed another app engine project from the launcher under a different email

Now, I'm trying to deploy a different app under a different email from the launcher.

How can I fix the deployment issue from launcher?


问:
Using node to query another node in firebase
I came across this problem, and can't figure it out. I have a node of users where I store all users

```<code>{
  users: {
    uid: {
      displayName: "stringOfSomeKind"
    }
    uid2: {
      displayName: "moreStrings"
    }
    uid3: {
      displayName: "evenMoreStrings"
    }
    ...
  }
}
</code>```

And then I have a node of events, and inside of the events node I have all users assigned to that event

```<code>{
  event_name: {
    asigned_users:"uid","uid2"
  }
}
</code>```

So the problem comes when the event admin wants to assign new users (from the users node) to the event, and I want to get only the users that are not already in the event (uid3 in this case). How can I do that? there is some sort of query I can run? I'm kinda new to no-relational databases so any advise would help

答:
This asigned_users:"uid","uid2" is not valid JSON. And unfortunately the answer depends on what JSON you actually use there.

Most likely you're using an array, which is the wrong structure for this type of data. To model a set in Firebase, you'd do: asigned_users: { uid1: true, uid2: true }.

Also see my more elaborated answer from yesterday and this older, somewhat related answer here.

Body:
I came across this problem, and can't figure it out. I have a node of users where I store all users

{
  users: {
    uid: {
      displayName: "stringOfSomeKind"
    }
    uid2: {
      displayName: "moreStrings"
    }
    uid3: {
      displayName: "evenMoreStrings"
    }
    ...
  }
}

And then I have a node of events, and inside of the events node I have all users assigned to that event

{
  event_name: {
    asigned_users:"uid","uid2"
  }
}

So the problem comes when the event admin wants to assign new users (from the users node) to the event, and I want to get only the users that are not already in the event (uid3 in this case). How can I do that? there is some sort of query I can run? I'm kinda new to no-relational databases so any advise would help


问:
Get uri parameter with javascript than return it to new url?
im not that familir with javascript but i need some help . Basically i have this scenario : i want to get a parameter from url , lets say http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER here also i have a javascript code which redirects to a second site , lets say mysite2.com/path1 , so what i need is when mysite1 redirects to mysite2 i want it also to return http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER , where #me parameter value is the same.</p>

答:
If you wish to reuse the complete "hash" part of the Location (the part after and including #...), you can say:

```<code>window.location = "http://mysite2.com/path1/" + window.location.hash;
</code>```

This will also redirect you to http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER, if executed from http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER.

Body:
If you wish to reuse the complete "hash" part of the Location (the part after and including #...), you can say:

window.location = "http://mysite2.com/path1/" + window.location.hash;

This will also redirect you to http://mysite2.com/path1/#me=VALUE_OF_ME_PARAMETER, if executed from http://mysite1.com/path/#me=VALUE_OF_ME_PARAMETER.


问:
Embed an ES6 Arrow Function in JSON Object
Is it possible to embed an ES6 Arrow Function within a JSON object?

Example, would the following data format be considered "valid"?

```<code>{
     function:{() => {console.log("executed")}}
}
</code>```

答:
First off, there is no such thing as a JSON object.  JSON is a text format, not an object format.  There is JSON text and Javascript objects.  The two are completely different things.

Per the JSON specification, the JSON text format does not accept functions.  Values in a JSON formatted string are described in this spec in shorthand like this:

```<code>value = false / null / true / object / array / number / string
</code>```

Those are the types that are allowed in JSON.

On the other hand, a Javascript object can indeed have a property that is a function. Since people regularly mix up those two separate things, I'm not sure what you meant, though you refer to JSON which is a text format and does not accept functions.

A Javascript object could have a function like this:

```<code>let obj = {
    somePropertyName: function() { console.log("hi")}
};
</code>```

that could then be called as:

```<code> obj.somePropertyName();
</code>```

ES6 syntax also allows a few other ways to declare the function, but the idea is the same.  You end up with a named property on the object that points to a function.  Using an arrow function with ES6 syntax:

```<code>let obj = {
    somePropertyName: () => { console.log("hi")}
};
</code>```

It is important to realize that when using an arrow function, the value of this when that function is called will NOT be set to the object itself since by definition, an arrow function uses the lexical form of this, and this is not set by how the method is called as it is with a normal function definition.

Body:
Is it possible to embed an ES6 Arrow Function within a JSON object?

Example, would the following data format be considered "valid"?

{
     function:{() => {console.log("executed")}}
}

Body:
First off, there is no such thing as a JSON object.  JSON is a text format, not an object format.  There is JSON text and Javascript objects.  The two are completely different things.

Per the JSON specification, the JSON text format does not accept functions.  Values in a JSON formatted string are described in this spec in shorthand like this:

value = false / null / true / object / array / number / string

Those are the types that are allowed in JSON.

On the other hand, a Javascript object can indeed have a property that is a function. Since people regularly mix up those two separate things, I'm not sure what you meant, though you refer to JSON which is a text format and does not accept functions.

A Javascript object could have a function like this:

let obj = {
    somePropertyName: function() { console.log("hi")}
};

that could then be called as:

 obj.somePropertyName();

ES6 syntax also allows a few other ways to declare the function, but the idea is the same.  You end up with a named property on the object that points to a function.  Using an arrow function with ES6 syntax:

let obj = {
    somePropertyName: () => { console.log("hi")}
};

It is important to realize that when using an arrow function, the value of this when that function is called will NOT be set to the object itself since by definition, an arrow function uses the lexical form of this, and this is not set by how the method is called as it is with a normal function definition.


问:
PHP cURL, memory leak when using CURLOPT_RETURNTRANSFER
The following code is in a loop. Each loop changes $URI to a new address.
My problem is that each pass takes up more and more memory.

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$res = curl_exec($ch);
curl_close($ch);
</code>```

I finally worked out that if I comment out the CURLOPT_RETURNTRANSFER line the leak stops.

I use "CURLOPT_RETURNTRANSFER, true" so I can get the result of the cURL operation as a string to parse. But, it would appear that the memory used to store this string is not parsed with each pass.
Can anyone suggest a way to clear this buffer and recover the used memory? Is there a destructor I could use, I've tried __destruct() but can't seem to get the syntax right.

Thanks
C

答:
Version 5.1.6 of PHP seems to have an issue with memory leaking when using "CURLOPT_RETURNTRANSFER, true" to store the results of the cURL as a string.
Upgrading to 5.3 sorted the leak out for me.

Thanks

Body:
The following code is in a loop. Each loop changes $URI to a new address.
My problem is that each pass takes up more and more memory.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$res = curl_exec($ch);
curl_close($ch);

I finally worked out that if I comment out the CURLOPT_RETURNTRANSFER line the leak stops.

I use "CURLOPT_RETURNTRANSFER, true" so I can get the result of the cURL operation as a string to parse. But, it would appear that the memory used to store this string is not parsed with each pass.
Can anyone suggest a way to clear this buffer and recover the used memory? Is there a destructor I could use, I've tried __destruct() but can't seem to get the syntax right.

Thanks
C


问:
Implementing a function similar to EXCEL Lookup in VB.net
I have a lot of code that requires random numbers to be generated and then options selected based on percentage.  I have it working without issue by simply using an implementation of the Mersenne Twister and generating a double between 0 and 100, then assigning results by percentage with select case.  It works fine, but it's very cumbersome and truth be told, I'm tired of continuously writing this out everytime.

I'd much prefer something similar to EXCEL's Lookup Function where you give two arrays such as LOOKUP(5, {1,10,20,30,40}, {"1-10", "11-20", "21-30","31-40"})

Which in this case would return: "1-10" since 5 is between 1-10.

Is there an easy way to implement a C#/VB.Net version of this using LINQ?  I'm sure there must be but I'm at a loss for how to implement something like this.  It would be far easier to write this one line of code than long select case statements.

If there is a better way than implementing an equivalent of an EXCEL lookup function, I'd love to know that as well...

答:
I actually came up with something similar to @Alexander Higgins answer on my own after I sat there and thought about it for a few minutes.  I call it like so:

```<code>CaseLookup({41, 59, 80, 101}, {"Balanced", "PowerBack", "Receiving", "OneCut"}, 0, 100)
</code>```

Basically I set the boundary for the next item and loop to find the first index it is less than, which means it would fall within that range. I then simply take the same index from the lookup array as the value.

```<code>Public Shared Function CaseLookup(numArray As Array, lookupArray As Array, minVal As Double, maxval As Double) As String
        Dim result As String = ""
        Dim GetNum As Double = MT.GenerateDouble(minVal, maxval)

        If numArray.Length <> lookupArray.Length Then 'Checks to make sure the arrays are the same length
           Throw New Exception("numArray and lookupArray MUST be the same length!")
           Exit Function
        End If

        For i = 0 To numArray.Length - 1
            If GetNum < numArray(i) Then result = lookupArray(i).ToString()
        Next i
        Return result
    End Function
</code>```

Body:
I actually came up with something similar to @Alexander Higgins answer on my own after I sat there and thought about it for a few minutes.  I call it like so:

CaseLookup({41, 59, 80, 101}, {"Balanced", "PowerBack", "Receiving", "OneCut"}, 0, 100)

Basically I set the boundary for the next item and loop to find the first index it is less than, which means it would fall within that range. I then simply take the same index from the lookup array as the value.

Public Shared Function CaseLookup(numArray As Array, lookupArray As Array, minVal As Double, maxval As Double) As String
        Dim result As String = ""
        Dim GetNum As Double = MT.GenerateDouble(minVal, maxval)

        If numArray.Length <> lookupArray.Length Then 'Checks to make sure the arrays are the same length
           Throw New Exception("numArray and lookupArray MUST be the same length!")
           Exit Function
        End If

        For i = 0 To numArray.Length - 1
            If GetNum < numArray(i) Then result = lookupArray(i).ToString()
        Next i
        Return result
    End Function


问:
No restricted globals
I am using React and Redux to develop a webapp and when I started up my project I got this:

```<code>Line 13:  Unexpected use of 'location'  no-restricted-globals

Search for the keywords to learn more about each error.
</code>```

I search a lot about how to resolve it, but none of the answers I found helped me, so I turned to Stack overflow.

Does anyone know how to fix this error? I appreciate all the help I can get.

答: Try adding window before location (i.e. window.location).

Title: No restricted globals

Body:
I am using React and Redux to develop a webapp and when I started up my project I got this:

Line 13:  Unexpected use of 'location'  no-restricted-globals

Search for the keywords to learn more about each error.

I search a lot about how to resolve it, but none of the answers I found helped me, so I turned to Stack overflow.

Does anyone know how to fix this error? I appreciate all the help I can get.


问:
Python: How to multply a dictionary of lists for a dictionary of float numbers?
I was wondering if it is possible to to multply a dictionary of lists of integers for a dictionary of float numbers. Both dictionary have the same keys.

I have a dictionary

```<code>q = dict(((i, f), somefloatnumber) for i in I for f in F)
p = dict(((i, f), somelistofinteger) for i in I for f in F)
</code>```

For instance, if I have:

```<code>dict1={(0, 0):[1, 0, 1], (0, 1):[1, 0, 0], (0, 2):[0, 0, 1]}

dict2={(0, 0): 10.54, (0, 1): 47.32, (0, 2): 33.1}
</code>```

The output would be:

```<code>dict3={(0, 0):[10.54, 0, 10.54], (0, 1):[47.32, 0, 0], (0, 2):[0, 0, 33.1]}
</code>```

Is there a way to multiply the dictionary q and p?
Thanks in advance

答:
Edit: I guess, you mean lists in dict 2. Please wrap them with [ and ]

Edit 2: You edited your question after my answer. For everyone who is looking for a solution where dict2 does not contain floats but lists of integers ( [10,54] instead of 10.54 ) here is my solution. Otherwise please read the accepted answer.

Of course there is a way to do that. You could simply cycle through each of the keys:

```<code>resultDict = {}  # = dict3
for key in dict1:
    multiplierList = dict2[key]
    sourceList = dict1[key]
    resultDict[key] = []
    for sourceElement in sourceList:
        if sourceElement == 0:        #in your question you described that in dict3 you would only have one 0 element.
            resultDict[key].append(0) #without these two lines you would have as many 0's as there are multipliers (in the example there would be two 0's)
        for multiplier in multiplierList:
            resultDict[key].append(sourceElement * multiplier)
</code>```

This code iterates over each of the list elements in dict1 and multiplies it with each of the elements in dict2 and appends them to the resultDict.

Body:
I was wondering if it is possible to to multply a dictionary of lists of integers for a dictionary of float numbers. Both dictionary have the same keys.

I have a dictionary

q = dict(((i, f), somefloatnumber) for i in I for f in F)
p = dict(((i, f), somelistofinteger) for i in I for f in F)

For instance, if I have:

dict1={(0, 0):[1, 0, 1], (0, 1):[1, 0, 0], (0, 2):[0, 0, 1]}

dict2={(0, 0): 10.54, (0, 1): 47.32, (0, 2): 33.1}

The output would be:

dict3={(0, 0):[10.54, 0, 10.54], (0, 1):[47.32, 0, 0], (0, 2):[0, 0, 33.1]}

Is there a way to multiply the dictionary q and p?
Thanks in advance

Body:
Edit: I guess, you mean lists in dict 2. Please wrap them with [ and ]

Edit 2: You edited your question after my answer. For everyone who is looking for a solution where dict2 does not contain floats but lists of integers ( [10,54] instead of 10.54 ) here is my solution. Otherwise please read the accepted answer.

Of course there is a way to do that. You could simply cycle through each of the keys:

resultDict = {}  # = dict3
for key in dict1:
    multiplierList = dict2[key]
    sourceList = dict1[key]
    resultDict[key] = []
    for sourceElement in sourceList:
        if sourceElement == 0:        #in your question you described that in dict3 you would only have one 0 element.
            resultDict[key].append(0) #without these two lines you would have as many 0's as there are multipliers (in the example there would be two 0's)
        for multiplier in multiplierList:
            resultDict[key].append(sourceElement * multiplier)

This code iterates over each of the list elements in dict1 and multiplies it with each of the elements in dict2 and appends them to the resultDict.


问:
How to get subclasses attributes using SingleTableInheritance with SpringMVC
i am working on a web application using Spring, Hibernate and SpringMVC,
i am facing a problem with retreiving values from a subclass table using SingleTable inheritance strategy, here are my entities

Client.java (Super class)

```<code>    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "typeClient", discriminatorType = DiscriminatorType.STRING)
    public class Client implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int idClient;

        private String matricule;
        private String statut;

        private String secteurDactivite;
        private String nomClient;

        private String emailClient;

        private String numTelephone;

        private String adresse;
//constructor
//getter & setters
     }
</code>```

Societe.java  (subClass1)

```<code>@Entity
@DiscriminatorValue("Societe")
public class Societe extends Client implements Serializable{

    private String nomResponsable;

    private String emailResponsable;

    private String telResponsable;

    private String nomSuperieur;

    private String emailSuperieur;

    private String telSuperieur;

    private String commentaire;

    //constructeur sans parametre
    public Societe() {
        }
    }
</code>```

Particulier.java (subclass2)

```<code>@Entity
@DiscriminatorValue("Particulier")
public class Particulier extends Client implements Serializable {

    private String cin;

    //constructeur sans parametres
    public Particulier() {

    }
    }
</code>```

in my implementation i am using this methode to get a particular client with his ID

ClientDaoImpl.java

```<code>public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    @Override
    public Client getClientByID(int id_client) {
        return em.find(Client.class, id_client);
    }
</code>```

When i ran this code i only selected the attributes of the superClass Client.

what i am trying to do is to get a client with its subclass whether it's a Societe or Particulier based on its type or clientID.

Please Help

答:
You can modify your getClientByID method to accept an additional argument which will say what type of entity your want to retrieve and get back:

```<code>public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    public <T extends Client> T getByID(int id_client, Class<T> klass) {
        return em.find(klass, id_client);
    }
}
</code>```

And you can use this dao in the following manner:

```<code>Societe societe = clientDao.getByID(42, Societe.class);
Particulier particulier = clientDao.getByID(43, Particulier.class);
</code>```

Body:
i am working on a web application using Spring, Hibernate and SpringMVC,
i am facing a problem with retreiving values from a subclass table using SingleTable inheritance strategy, here are my entities

Client.java (Super class)

    @Entity
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name = "typeClient", discriminatorType = DiscriminatorType.STRING)
    public class Client implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int idClient;

        private String matricule;
        private String statut;

        private String secteurDactivite;
        private String nomClient;

        private String emailClient;

        private String numTelephone;

        private String adresse;
//constructor
//getter & setters
     }

Societe.java  (subClass1)

@Entity
@DiscriminatorValue("Societe")
public class Societe extends Client implements Serializable{

    private String nomResponsable;

    private String emailResponsable;

    private String telResponsable;

    private String nomSuperieur;

    private String emailSuperieur;

    private String telSuperieur;

    private String commentaire;

    //constructeur sans parametre
    public Societe() {
        }
    }

Particulier.java (subclass2)

@Entity
@DiscriminatorValue("Particulier")
public class Particulier extends Client implements Serializable {

    private String cin;

    //constructeur sans parametres
    public Particulier() {

    }
    }

in my implementation i am using this methode to get a particular client with his ID

ClientDaoImpl.java

public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    @Override
    public Client getClientByID(int id_client) {
        return em.find(Client.class, id_client);
    }

When i ran this code i only selected the attributes of the superClass Client.

what i am trying to do is to get a client with its subclass whether it's a Societe or Particulier based on its type or clientID.

Please Help

Body:
You can modify your getClientByID method to accept an additional argument which will say what type of entity your want to retrieve and get back:

public class ClientDaoImpl implements ClientDao {
    @PersistenceContext
    private EntityManager em;

    public <T extends Client> T getByID(int id_client, Class<T> klass) {
        return em.find(klass, id_client);
    }
}

And you can use this dao in the following manner:

Societe societe = clientDao.getByID(42, Societe.class);
Particulier particulier = clientDao.getByID(43, Particulier.class);


问:
how to change browser history in java script
I'm creating a small web application and I'm loading my pages using ajax in div.

Whenever user click on link, ajax request page and then update my div and url..
after ajax request when i try to refresh my pages,

It's working fine and show me current page but when i click on back button it's change top url but not the page and it's content
here is my code

```<code>$.ajax({
url: link,
type:'POST',
data : name,
success: function(data) {
$("#main").html(data);
  history.pushState({foo:'bar'}, title, link);
  }
 }
});
</code>```

答:
As @Slaks says in the comments, you need to handle the window.onpopstate.

Documentation:

going back doesn't change the document's contents from what they were
  in the previous step, although the document might update its contents
  manually upon receiving the popstate event.

To do this you need a State object, which you pass as a parameter in your pushState call. A state Object is a javascript object that is associated with the new history entry. The popstate event is fired only when the active history entry changes and it will have a copy of the State object as a parameter.
As docs says, history.pushState() (and history.replaceState()) methods only add (and modify) history entries, for this reason:

calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document.

Body:
I'm creating a small web application and I'm loading my pages using ajax in div.

Whenever user click on link, ajax request page and then update my div and url..
after ajax request when i try to refresh my pages,

It's working fine and show me current page but when i click on back button it's change top url but not the page and it's content
here is my code

$.ajax({
url: link,
type:'POST',
data : name,
success: function(data) {
$("#main").html(data);
  history.pushState({foo:'bar'}, title, link);
  }
 }
});


问:
I got Malformed config.xml when trying to compile with PhoneGap Build
I have search, but I didn't know what was wrong with my config.xml here is the code

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

<!-- config.xml reference: https://build.phonegap.com/docs/config-xml -->
<widget xmlns     = "http://www.w3.org/ns/widgets"
        xmlns:gap = "http://phonegap.com/ns/1.0"
        id        = "com.techware.callMyCab"
        version   = "1.0.0">

    <name>TaxiRide/name>

    <description>
       TaxiRide is your one stop cab ride
    </description>

    <author href="http://taxiride.com/" email="info@taxiride.com">
        Taxi Ride
    </author>

    <!--
        If you do not want any permissions to be added to your app, add the
        following tag to your config.xml; you will still have the INTERNET
        permission on your app, which PhoneGap requires.
    -->
        <!-- <preference name="phonegap-version" value="cli-5.2.0" /> -->
        <!-- <preference name="phonegap-version"       value="3.5.0" /> -->
    <preference name="permissions"                value="none"/>

    <!-- Customize your app and platform with the preference element. -->
    <preference name="orientation"                value="portrait" />        <!-- all: default means both landscape and portrait are enabled -->
    <preference name="target-device"              value="universal" />      <!-- all: possible values handset, tablet, or universal -->
    <preference name="fullscreen"                 value="false" />           <!-- all: hides the status bar at the top of the screen -->
    <preference name="webviewbounce"              value="true" />           <!-- ios: control whether the screen 'bounces' when scrolled beyond the top -->
    <preference name="prerendered-icon"           value="true" />           <!-- ios: if icon is prerendered, iOS will not apply it's gloss to the app's icon on the user's home screen -->
    <preference name="stay-in-webview"            value="false" />          <!-- ios: external links should open in the default browser, 'true' would use the webview the app lives in -->
    <preference name="ios-statusbarstyle"         value="black-opaque" />   <!-- ios: black-translucent will appear black because the PhoneGap webview doesn't go beneath the status bar -->
    <preference name="detect-data-types"          value="true" />           <!-- ios: controls whether data types (such as phone no. and dates) are automatically turned into links by the system -->
    <preference name="exit-on-suspend"            value="false" />          <!-- ios: if set to true, app will terminate when home button is pressed -->

        <preference name="show-splash-screen-spinner" value="true" />           <!-- ios: if set to false, the spinner won't appear on the splash screen during app loading -->
    <preference name="auto-hide-splash-screen"    value="false" />           <!-- ios: if set to false, the splash screen must be hidden using a JavaScript API -->
    <preference name="disable-cursor"             value="false" />          <!-- blackberry: prevents a mouse-icon/cursor from being displayed on the app -->
    <preference name="android-installLocation"    value="auto" />           <!-- android: app install location. 'auto' will choose. 'internalOnly' is device memory. 'preferExternal' is SDCard. -->
    <preference name="splashScreenDelay"        value="70000" />
        <!--
        Define a specific version of PhoneGap to build into your app.
        <preference name="phonegap-version"       value="3.5.0" />
    -->

    <!-- Plugins -->

    <!-- Core plugins -->

        <!-- <gap:plugin name="org.apache.cordova.geolocation"  source="pgb" version="0.3.7" />
        <gap:plugin name="com.ionic.keyboard" source="pgb" version="1.0.3" />
        <gap:plugin name="org.apache.cordova.device" source="pgb" version="0.2.12" />
        <gap:plugin name="org.apache.cordova.device-orientation" source="pgb" version="0.3.9" />
        <gap:plugin name="org.apache.cordova.dialogs" source="pgb" version="0.2.10" />
        <gap:plugin name="org.apache.cordova.file-transfer" source="pgb" version="0.4.6" />
        <gap:plugin name="org.apache.cordova.inappbrowser" source="pgb" version="0.5.2" />
        <gap:plugin name="org.apache.cordova.network-information" source="pgb" version="0.2.12" />
        <gap:plugin name="org.apache.cordova.splashscreen" source="pgb" version="0.3.4" /> -->

        <gap:plugin name="cordova-plugin-geolocation"  source="npm" spec="~2.4.0"/>
        <gap:plugin name="cordova-plugin-ionic-keyboard" source="npm"  />
        <gap:plugin name="cordova-plugin-device" source="npm" spec="~1.1.3" />
        <gap:plugin name="cordova-plugin-device-orientation" source="npm" spec="~1.0.4" />
        <gap:plugin name="cordova-plugin-dialogs" source="npm"  spec="~1.3.0" />
        <gap:plugin name="cordova-plugin-file-transfer" source="npm"  spec="~1.6.0" />
        <gap:plugin name="cordova-plugin-inappbrowser" source="npm" spec="~1.5.0" />
        <gap:plugin name="cordova-plugin-network-information" source="npm"  spec="~1.3.0" />
        <gap:plugin name="cordova-plugin-splashscreen" source="npm" spec="~4.0.0" />

        <!-- <gap:plugin name="cordova-plugin-whitelist" version="1.0.0"  /> -->
    <!-- Third party plugins -->
    <!-- A list of available plugins are available at https://build.phonegap.com/plugins -->
    <!--
        <gap:plugin name="com.phonegap.plugins.barcodescanner" />
    -->

    <!-- Define app icon for each platform. -->
    <icon src="icon.png" />
    <icon src="res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:qualifier="ldpi" />
    <icon src="res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:qualifier="mdpi" />
    <icon src="res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:qualifier="hdpi" />
    <icon src="res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:qualifier="xhdpi" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" gap:state="hover"/>
    <icon src="res/icon/ios/icon-57.png"            gap:platform="ios"        width="57" height="57" />
    <icon src="res/icon/ios/icon-72.png"            gap:platform="ios"        width="72" height="72" />
    <icon src="res/icon/ios/icon-57-2x.png"         gap:platform="ios"        width="114" height="114" />
    <icon src="res/icon/ios/icon-72-2x.png"         gap:platform="ios"        width="144" height="144" />
    <icon src="res/icon/webos/icon-64.png"          gap:platform="webos" />
    <icon src="res/icon/windows-phone/icon-48.png"  gap:platform="winphone" />
    <icon src="res/icon/windows-phone/icon-173.png" gap:platform="winphone"   gap:role="background" />

    <!-- Define app splash screen for each platform. -->
        <gap:splash src="res/screen/android/screen-ldpi-portrait.png" />
        <gap:splash src="res/screen/android/screen-ldpi-portrait.png"       gap:platform="android" gap:qualifier="port-ldpi" />
    <gap:splash src="res/screen/android/screen-mdpi-portrait.png"       gap:platform="android" gap:qualifier="port-mdpi" />
    <gap:splash src="res/screen/android/screen-hdpi-portrait.png"       gap:platform="android" gap:qualifier="port-hdpi" />
    <gap:splash src="res/screen/android/screen-xhdpi-portrait.png"      gap:platform="android" gap:qualifier="port-xhdpi" />
    <gap:splash src="res/screen/blackberry/screen-225.png"              gap:platform="blackberry" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait.png"         gap:platform="ios"     width="320" height="480" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-2x.png"      gap:platform="ios"     width="640" height="960" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-568h-2x.png" gap:platform="ios"     width="640" height="1136" />
    <gap:splash src="res/screen/ios/screen-ipad-portrait.png"           gap:platform="ios"     width="768" height="1024" />
    <gap:splash src="res/screen/ios/screen-ipad-landscape.png"          gap:platform="ios"     width="1024" height="768" />
    <gap:splash src="res/screen/windows-phone/screen-portrait.jpg"      gap:platform="winphone" />

    <gap:config-file platform="ios" parent="CFBundleShortVersionString">
    <string>100</string>
    </gap:config-file>

    <!--
        Define access to external domains.
        <access />            - a blank access tag denies access to all external resources.
        <access origin="*" /> - a wildcard access tag allows access to all external resource.
        Otherwise, you can specify specific domains:
        <access origin="http://phonegap.com" />                    - allow any secure requests to http://phonegap.com/
        <access origin="http://phonegap.com" subdomains="true" />  - same as above, but including subdomains, such as http://build.phonegap.com/
        <access origin="http://phonegap.com" browserOnly="true" /> - only allows http://phonegap.com to be opened by the child browser.
    -->

    <access origin="*"/>
    <!-- Added the following intents to support the removal of whitelist code from base cordova to a plugin -->
    <!-- Whitelist configuration. Refer to https://cordova.apache.org/docs/en/edge/guide_appdev_whitelist_index.md.html -->
    <plugin name="cordova-plugin-whitelist" version="1" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>

</widget>
</code>```

If I try to compile it using PhoneGap Build I get a malformed config.xml error. I got the code from documents so I'm really not sure what the problem can be.

答:
This line

```<code><name>TaxiRide/name>
</code>```

should be

```<code><name>TaxiRide</name>
              ^
</code>```

Body:
I have search, but I didn't know what was wrong with my config.xml here is the code

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

<widget xmlns     = "http://www.w3.org/ns/widgets"
        xmlns:gap = "http://phonegap.com/ns/1.0"
        id        = "com.techware.callMyCab"
        version   = "1.0.0">

    <name>TaxiRide/name>

    <description>
       TaxiRide is your one stop cab ride
    </description>

    <author href="http://taxiride.com/" email="info@taxiride.com">
        Taxi Ride
    </author>

    <preference name="permissions"                value="none"/>

    <preference name="orientation"                value="portrait" />
    <preference name="target-device"              value="universal" />
    <preference name="fullscreen"                 value="false" />
    <preference name="webviewbounce"              value="true" />
    <preference name="prerendered-icon"           value="true" />
    <preference name="stay-in-webview"            value="false" />
    <preference name="ios-statusbarstyle"         value="black-opaque" />
    <preference name="detect-data-types"          value="true" />
    <preference name="exit-on-suspend"            value="false" />

        <preference name="show-splash-screen-spinner" value="true" />
    <preference name="auto-hide-splash-screen"    value="false" />
    <preference name="disable-cursor"             value="false" />
    <preference name="android-installLocation"    value="auto" />
    <preference name="splashScreenDelay"        value="70000" />

        <gap:plugin name="cordova-plugin-geolocation"  source="npm" spec="~2.4.0"/>
        <gap:plugin name="cordova-plugin-ionic-keyboard" source="npm"  />
        <gap:plugin name="cordova-plugin-device" source="npm" spec="~1.1.3" />
        <gap:plugin name="cordova-plugin-device-orientation" source="npm" spec="~1.0.4" />
        <gap:plugin name="cordova-plugin-dialogs" source="npm"  spec="~1.3.0" />
        <gap:plugin name="cordova-plugin-file-transfer" source="npm"  spec="~1.6.0" />
        <gap:plugin name="cordova-plugin-inappbrowser" source="npm" spec="~1.5.0" />
        <gap:plugin name="cordova-plugin-network-information" source="npm"  spec="~1.3.0" />
        <gap:plugin name="cordova-plugin-splashscreen" source="npm" spec="~4.0.0" />

    <icon src="icon.png" />
    <icon src="res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:qualifier="ldpi" />
    <icon src="res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:qualifier="mdpi" />
    <icon src="res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:qualifier="hdpi" />
    <icon src="res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:qualifier="xhdpi" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" />
    <icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" gap:state="hover"/>
    <icon src="res/icon/ios/icon-57.png"            gap:platform="ios"        width="57" height="57" />
    <icon src="res/icon/ios/icon-72.png"            gap:platform="ios"        width="72" height="72" />
    <icon src="res/icon/ios/icon-57-2x.png"         gap:platform="ios"        width="114" height="114" />
    <icon src="res/icon/ios/icon-72-2x.png"         gap:platform="ios"        width="144" height="144" />
    <icon src="res/icon/webos/icon-64.png"          gap:platform="webos" />
    <icon src="res/icon/windows-phone/icon-48.png"  gap:platform="winphone" />
    <icon src="res/icon/windows-phone/icon-173.png" gap:platform="winphone"   gap:role="background" />

        <gap:splash src="res/screen/android/screen-ldpi-portrait.png" />
        <gap:splash src="res/screen/android/screen-ldpi-portrait.png"       gap:platform="android" gap:qualifier="port-ldpi" />
    <gap:splash src="res/screen/android/screen-mdpi-portrait.png"       gap:platform="android" gap:qualifier="port-mdpi" />
    <gap:splash src="res/screen/android/screen-hdpi-portrait.png"       gap:platform="android" gap:qualifier="port-hdpi" />
    <gap:splash src="res/screen/android/screen-xhdpi-portrait.png"      gap:platform="android" gap:qualifier="port-xhdpi" />
    <gap:splash src="res/screen/blackberry/screen-225.png"              gap:platform="blackberry" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait.png"         gap:platform="ios"     width="320" height="480" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-2x.png"      gap:platform="ios"     width="640" height="960" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-568h-2x.png" gap:platform="ios"     width="640" height="1136" />
    <gap:splash src="res/screen/ios/screen-ipad-portrait.png"           gap:platform="ios"     width="768" height="1024" />
    <gap:splash src="res/screen/ios/screen-ipad-landscape.png"          gap:platform="ios"     width="1024" height="768" />
    <gap:splash src="res/screen/windows-phone/screen-portrait.jpg"      gap:platform="winphone" />

    <gap:config-file platform="ios" parent="CFBundleShortVersionString">
    <string>100</string>
    </gap:config-file>

    <access origin="*"/>

    <plugin name="cordova-plugin-whitelist" version="1" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>

</widget>

If I try to compile it using PhoneGap Build I get a malformed config.xml error. I got the code from documents so I'm really not sure what the problem can be.

Body:
This line

<name>TaxiRide/name>

should be

<name>TaxiRide</name>
              ^


问:
SimpleJdbcCall: get result of Microsoft/Sybase stored procedure call
I've a Microsoft and Sybase stored procedures that return result as "return @value". I need to read the value from Java via SimpleJdbcCall.

Is it possible?

答:
Spring has supported stored procedures nicely since 2.x:

http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html

These should be able to sort you out.


问:
How to get start day timestamp and end day timestamp from value
For example I have one column TIMESTAMP WITH TIME ZONE with value '2017-07-09 19:43:54.418544'
How to get from this value something like this :

```<code>2017-07-09 00:00:00 as start_day,
2017-07-09 23:59:59 as end_day
</code>```

答:
That format is not a timestamp with timezone.  It doesn't have the timezone part.  But with or without, you can use date_trunc():

```<code>select date_trunc('day', val) as start_day,
       (date_trunc('day', val) + interval '1 day' - interval '1 second') as end_day
</code>```

I am not a fan of inclusive end-day bounds.  I would recommend just saying "< the start of the next day".

Body:
For example I have one column TIMESTAMP WITH TIME ZONE with value '2017-07-09 19:43:54.418544'
How to get from this value something like this :

2017-07-09 00:00:00 as start_day,
2017-07-09 23:59:59 as end_day

Body:
That format is not a timestamp with timezone.  It doesn't have the timezone part.  But with or without, you can use date_trunc():

select date_trunc('day', val) as start_day,
       (date_trunc('day', val) + interval '1 day' - interval '1 second') as end_day

I am not a fan of inclusive end-day bounds.  I would recommend just saying "< the start of the next day".


Title: Python: How to multply a dictionary of lists for a dictionary of float numbers?

Body:
Try this

dict1 = {(0, 0):[1, 0, 1], (0, 1):[1, 0, 0], (0, 2):[0, 0, 1]}
dict2 = {(0, 0): 10.54, (0, 1): 47.32, (0, 2): 33.1}
dict3 = {}

for key, elems in dict1.items():
    multiplier = dict2[key]
    dict3[key] = [multiplier*elem for elem in elems]

# dict3 =
# {(0, 0): [10.54, 0.0, 10.54],
#  (0, 1): [47.32, 0.0, 0.0],
#  (0, 2): [0.0, 0.0, 33.1]}

I'm assuming by 10,54 you actually mean 10.54. In programming you have to represent decimals as a .


问:
Javascript how to filter an array using forEach() inside filter()
I have an array of objects and I'd like to filter it based on the objects property values. I'd like to filter it by different properties, so it needed to be dynamic. For this I have an input field where I type and then filter the array. So, let's say I have these 2 different arrays:

```<code>const array_one = [
  {id: 1, code: 'ABC123', name: 'John'},
  {id: 2, code: 'DEF456', name: 'Stew'},
    // ...
];

const array_two = [
  {id: 1, value: '012345', company: 'Company 01' },
  {id: 2, value: '678910', company: 'Company 02' },
    // ...
];
</code>```

I want a function where I can filter the first array based on the name, also If I want to filter the second array, I want to filter it by the value.

For this, I built this function:

```<code>filterArray(array: Array<any>, fields: Array<any>, value: string) {
    value = this.convertString(value);

    array = array.filter((item) => {
        fields.forEach(obj => {
            if ( item[obj] ) {
                const _newObj = this.convertString(item[obj]);
                if ( _newObj.indexOf(value) !== -1 ) {
                    console.log(item);
                    return item;
                }
            }
        });
    });

    return array;
}
// convertString() is just another function to replace accents, spaces, etc...
</code>```

Then I call it like this:

```<code>filterArray(originalArray, ['name'], valueFromInput);

// or...
filterArray(originalArray, ['value'], valueFromInput);

// or even...
filterArray(originalArray, ['value', 'company'], valueFromInput);
</code>```

But the array filtered is always returnin empty, even if the console inside the indexOf verification prints the correct object on the console.

What am I doing wrong here? Because it's filtering properly, I have manually checked it, but it doesn't add to the new filtered array.

答:
If you want to make the filter about more than one filed then the value that you send it to the function, should be also array.
In my code below I assume that you want to return the object that Achieves all conditions (contains all properties that you send to the function with the same value)

```<code> const array_one = [
      {id: 1, code: 'ABC123', name: 'John'},
      {id: 2, code: 'DEF456', name: 'Stew'},
   ];

   const array_two = [
      {id: 1, value: '012345', company: 'Company 01' },
      {id: 2, value: '678910', company: 'Company 02' },
   ];

   function filterArray(array, fields, value) {
       array = array.filter((item) => {
           const found = fields.every((field, index) => {
               return item[field] && item[field] === value[index]
           })
           return found
       });
       return array;
   }

   console.log(filterArray(array_one, ['name'], ['Stew']));

   console.log(filterArray(array_two, ['id', 'company'], [1,'Company 01']));
</code>```

Body:
I have an array of objects and I'd like to filter it based on the objects property values. I'd like to filter it by different properties, so it needed to be dynamic. For this I have an input field where I type and then filter the array. So, let's say I have these 2 different arrays:

const array_one = [
  {id: 1, code: 'ABC123', name: 'John'},
  {id: 2, code: 'DEF456', name: 'Stew'},
    // ...
];

const array_two = [
  {id: 1, value: '012345', company: 'Company 01' },
  {id: 2, value: '678910', company: 'Company 02' },
    // ...
];

I want a function where I can filter the first array based on the name, also If I want to filter the second array, I want to filter it by the value.

For this, I built this function:

filterArray(array: Array<any>, fields: Array<any>, value: string) {
    value = this.convertString(value);

    array = array.filter((item) => {
        fields.forEach(obj => {
            if ( item[obj] ) {
                const _newObj = this.convertString(item[obj]);
                if ( _newObj.indexOf(value) !== -1 ) {
                    console.log(item);
                    return item;
                }
            }
        });
    });

    return array;
}
// convertString() is just another function to replace accents, spaces, etc...

Then I call it like this:

filterArray(originalArray, ['name'], valueFromInput);

// or...
filterArray(originalArray, ['value'], valueFromInput);

// or even...
filterArray(originalArray, ['value', 'company'], valueFromInput);

But the array filtered is always returnin empty, even if the console inside the indexOf verification prints the correct object on the console.

What am I doing wrong here? Because it's filtering properly, I have manually checked it, but it doesn't add to the new filtered array.

Body:
If you want to make the filter about more than one filed then the value that you send it to the function, should be also array.
In my code below I assume that you want to return the object that Achieves all conditions (contains all properties that you send to the function with the same value)

 const array_one = [
      {id: 1, code: 'ABC123', name: 'John'},
      {id: 2, code: 'DEF456', name: 'Stew'},
   ];

   const array_two = [
      {id: 1, value: '012345', company: 'Company 01' },
      {id: 2, value: '678910', company: 'Company 02' },
   ];

   function filterArray(array, fields, value) {
       array = array.filter((item) => {
           const found = fields.every((field, index) => {
               return item[field] && item[field] === value[index]
           })
           return found
       });
       return array;
   }

   console.log(filterArray(array_one, ['name'], ['Stew']));

   console.log(filterArray(array_two, ['id', 'company'], [1,'Company 01']));