答:
You need a bit of boilerplate to get the right tuple specialization out of a typelist, for you can't simply store the parameter pack as it is.

As an example, you could do that by using properly a function declaration and an using declaration:

```<code>#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {};

template<typename... T>
std::tuple<T...> foo(typelist<T...>);

template<typename L>
using tupleFromTypelist = decltype(foo(std::declval<L>()));

int main() {
    using tl = typelist<int, int>;
    tupleFromTypelist<tl> tp{0,1};
    static_assert(std::is_same<tupleFromTypelist<tl>, std::tuple<int, int>>::value, "!");
}
</code>```

Or an helper class like the one in the following example:

```<code>#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {};

template<typename>
struct helper;

template<typename... T>
struct helper<typelist<T...>> {
    using type = std::tuple<T...>;
};

int main() {
    using tl = typelist<int, int>;
    helper<tl>::type tp{0,1};
    static_assert(std::is_same<helper<tl>::type, std::tuple<int, int>>::value, "!");
}
</code>```

Otherwise, let typelist expose the tuple specialization and get it directly from it:

```<code>#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {
    using tuple = std::tuple<T...>;
};

int main() {
    using tl = typelist<int, int>;
    tl::tuple tp{0,1};
    static_assert(std::is_same<tl::tuple, std::tuple<int, int>>::value, "!");
}
</code>```

If it's the only type for which you want to use the parameter pack, this is the easiest approach.

Title: How do I rebuild parameter pack from TypeList

Body:
You need a bit of boilerplate to get the right tuple specialization out of a typelist, for you can't simply store the parameter pack as it is.

As an example, you could do that by using properly a function declaration and an using declaration:

#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {};

template<typename... T>
std::tuple<T...> foo(typelist<T...>);

template<typename L>
using tupleFromTypelist = decltype(foo(std::declval<L>()));

int main() {
    using tl = typelist<int, int>;
    tupleFromTypelist<tl> tp{0,1};
    static_assert(std::is_same<tupleFromTypelist<tl>, std::tuple<int, int>>::value, "!");
}

Or an helper class like the one in the following example:

#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {};

template<typename>
struct helper;

template<typename... T>
struct helper<typelist<T...>> {
    using type = std::tuple<T...>;
};

int main() {
    using tl = typelist<int, int>;
    helper<tl>::type tp{0,1};
    static_assert(std::is_same<helper<tl>::type, std::tuple<int, int>>::value, "!");
}

Otherwise, let typelist expose the tuple specialization and get it directly from it:

#include<tuple>
#include<utility>
#include<type_traits>

template <class... T>
struct typelist {
    using tuple = std::tuple<T...>;
};

int main() {
    using tl = typelist<int, int>;
    tl::tuple tp{0,1};
    static_assert(std::is_same<tl::tuple, std::tuple<int, int>>::value, "!");
}

If it's the only type for which you want to use the parameter pack, this is the easiest approach.


来源: stackexchange

问:
How do I pass variable value of one activity to baseactivity in android
I have BaseActivity and LoginActivity in my application where access token is being fetched from web service. I do not want to save access token in static or shared preference so I want to make it available accessToken to BaseActivity from LoginActivity so it can be access across the application which extends BaseActivity using simple method.

BaseActivity.java

```<code>@Override
public String getAccessToken() {
    return accessToken;
}
</code>```

Any idea how I can do this

答: put bundle in one activity and s and another activity get bundle </p>

ContentLicense: CC BY-SA 3.0

Body:
I have BaseActivity and LoginActivity in my application where access token is being fetched from web service. I do not want to save access token in static or shared preference so I want to make it available accessToken to BaseActivity from LoginActivity so it can be access across the application which extends BaseActivity using simple method.

BaseActivity.java

@Override
public String getAccessToken() {
    return accessToken;
}

Any idea how I can do this


问:
Python SQL, how to keep program going after entering an invalid input
Ok, so I have some code when creating a database.

Here's the code:

So basically, the PhoneNumber is set to unique. If I enter a phone number that has already been entered the program stops and gives an error message (Because it is unique).

How do I get it to keep running or display a message saying "Phone number already taken please input another on" instead of ending

Thanks

答: You can use try catch statement to do exception handle.


问:
Return identity of last inserted row from stored procedure
I am trying to return identity of last inserted row from a stored procedure.

A simplified version of my code looks like this:

```<code>CREATE PROCEDURE [sp_name]
    @AuthorisationCode uniqueidentifier
AS
    INSERT INTO [tablename]
           ([AuthorisationCode]
           )
     VALUES
           (@AuthorisationCode
           )

 RETURN @@IDENTITY

GO
</code>```

I am calling this stored procedure via Execute Scalar in Enterprise library 4.1.

It returns null. Anybody see what I am doing wrong.

答: you should use select @@identity

ContentLicense: CC BY-SA 2.5

Body:
I am trying to return identity of last inserted row from a stored procedure.

A simplified version of my code looks like this:

CREATE PROCEDURE [sp_name]
    @AuthorisationCode uniqueidentifier
AS
    INSERT INTO [tablename]
           ([AuthorisationCode]
           )
     VALUES
           (@AuthorisationCode
           )

 RETURN @@IDENTITY

GO

I am calling this stored procedure via Execute Scalar in Enterprise library 4.1.

It returns null. Anybody see what I am doing wrong.

Body: you should use select @@identity


问:
Promise error The message port closed before a reponse was received
I've just started to get this error:

Uncaught (in promise) Objectmessage: "The message port closed before a reponse was received."

at chrome-extension://gppongmhjkpfnbhagpmjfkannfbllamg/js/browser-polyfill.js at this line:

```<code>const makeCallback = promise => {
  return (...callbackArgs) => {
    if (chrome.runtime.lastError) {
      promise.reject(chrome.runtime.lastError); // uncaught in promise
    } else if (callbackArgs.length === 1) {
      promise.resolve(callbackArgs[0]);
    } else {
      promise.resolve(callbackArgs);
    }
  };
};
</code>```

Do you know what can cause it?

Thanks

答:
Update:

As of the comment by morficus, the problem has been fixed in the version: 4.0.1

The plugin will auto-update or you could reinstall from here:

https://chrome.google.com/webstore/detail/wappalyzer/gppongmhjkpfnbhagpmjfkannfbllamg

If anyone is interested in the issue the pull request is here:

https://github.com/AliasIO/Wappalyzer/pull/1491

2019 Edit:

If that is not solving your issue. You could try disabling all the chrome extensions and check if that solve your issue.

To disable you could type the below code in chrome url:

chrome://extensions/

or could go on

Settings > Extensions

After that you could enable each extensions and check the culprit.

Older issue:

It is not the chrome's bug but the bug with the wappalyzer extension.

I am not sure you are using it but i have used it and was just updated and got the same issue.

Here is the proof of the issue:

https://github.com/AliasIO/Wappalyzer/issues/1487

We need to wait until there is any solution for the extension or use the older version of the extension until it gets resolved.

Body:
I've just started to get this error:

Uncaught (in promise) Objectmessage: "The message port closed before a reponse was received."

at chrome-extension://gppongmhjkpfnbhagpmjfkannfbllamg/js/browser-polyfill.js at this line:

const makeCallback = promise => {
  return (...callbackArgs) => {
    if (chrome.runtime.lastError) {
      promise.reject(chrome.runtime.lastError); // uncaught in promise
    } else if (callbackArgs.length === 1) {
      promise.resolve(callbackArgs[0]);
    } else {
      promise.resolve(callbackArgs);
    }
  };
};

Do you know what can cause it?

Thanks

ContentLicense: CC BY-SA 4.0


问:
how to store session data into custom storage in bot builder
I am using node js to build chat bot.

I'm currently storing session data into Microsoft default storage, which have a limit of 64K per user session. I want to use my own storage to store session data. Here is what I got help from Microsoft developer.

I am able to store in document DB and Azure table.

Still, I am confused. How we will implement the IStorageClient interface to store in own DB?

Whenever I set session.UserData.name="" it should store in own DB.

答:
I'm not sure if I got the issue; I understand what you are trying to do and it seems you have all the pieces in place.

First, you have to implement the IStorageClient interface. In your implementation, you write the logic to store things in your DB.

You can review the DocumentDB and Azure Tables implementations to get an idea of how that can be implemented.

Now, the question is.. if your custom storage is in Azure..., then you might be able to use the AzureBotStorage with your custom storage client. You instantiate your custom storage client, pass a reference to the AzureBotStorage and set that as the storage in the bot

```<code>// Azure DocumentDb State Store
var docDbClient = new azure.DocumentDbClient({
    host: process.env.DOCUMENT_DB_HOST,
    masterKey: process.env.DOCUMENT_DB_MASTER_KEY,
    database: process.env.DOCUMENT_DB_DATABASE,
    collection: process.env.DOCUMENT_DB_COLLECTION
});
var botStorage = new azure.AzureBotStorage({ gzipData: false }, docDbClient);

// Set Custom Store
bot.set('storage', botStorage);
</code>```

If your custom storage is in any other place than Azure, then AzureBotStorage might not work for you. Please note that I'm not sure of this, you will have to check the code to confirm. From what I saw, it seems pretty generic, and so you might be able to reuse it and just implement IStorageClient. If that's not the case, you will have to also implement the IBotStorage interface.

At the end, AzureBotStorage is doing that. It implements IBotStorage and uses an IStorageClient to interact with the actual provider.

Body:
I'm not sure if I got the issue; I understand what you are trying to do and it seems you have all the pieces in place.

First, you have to implement the IStorageClient interface. In your implementation, you write the logic to store things in your DB.

You can review the DocumentDB and Azure Tables implementations to get an idea of how that can be implemented.

Now, the question is.. if your custom storage is in Azure..., then you might be able to use the AzureBotStorage with your custom storage client. You instantiate your custom storage client, pass a reference to the AzureBotStorage and set that as the storage in the bot

// Azure DocumentDb State Store
var docDbClient = new azure.DocumentDbClient({
    host: process.env.DOCUMENT_DB_HOST,
    masterKey: process.env.DOCUMENT_DB_MASTER_KEY,
    database: process.env.DOCUMENT_DB_DATABASE,
    collection: process.env.DOCUMENT_DB_COLLECTION
});
var botStorage = new azure.AzureBotStorage({ gzipData: false }, docDbClient);

// Set Custom Store
bot.set('storage', botStorage);

If your custom storage is in any other place than Azure, then AzureBotStorage might not work for you. Please note that I'm not sure of this, you will have to check the code to confirm. From what I saw, it seems pretty generic, and so you might be able to reuse it and just implement IStorageClient. If that's not the case, you will have to also implement the IBotStorage interface.

At the end, AzureBotStorage is doing that. It implements IBotStorage and uses an IStorageClient to interact with the actual provider.


问:
Java lesson: public void displayMessage() Doesn't working
I have a Java book and im trying to learn obviously Java Programming.

I have a lesson that tells me simply to put this Code on Eclipse.

I copied from the Book and i put it on Eclipse program that i test and learn there. When i run it, it doesn't says any error. But at the moment that i run it, it shows me this error:

Code on Eclipse

Code on the Book

Does anyone knows what happens here? Is the book wrong or what?

Thanks.

答:
You have a public class GradeBook and you have not defined the main[String args[]] method inside it. (Remember JVM expects main method inside the public class, if JVM not found the main method then it complains for that.)

if you just want to compile your code successfully without run time target simply remove the public before class.

Or

Define the main method inside your public class GradeBook

```<code>public static void main(String args[])
{
...
}
</code>```

Body:
You have a public class GradeBook and you have not defined the main[String args[]] method inside it. (Remember JVM expects main method inside the public class, if JVM not found the main method then it complains for that.)

if you just want to compile your code successfully without run time target simply remove the public before class.

Or

Define the main method inside your public class GradeBook

public static void main(String args[])
{
...
}


问:
Layout access without create a new class in android studio
I'm a novice programmer and I'm working on one of the my first projects on Android Studio.
Is it possible to access a .xml file without create a new java class? If I have two or more layouts, in which way can I switch between them with only the main class?</p>

答:
Question is not clear.
setContentView(R.layout.your_layout); sets the activity with .XML file. So adding the buttons to your layouts you can play with that


问:
Finding parents by their children's properties
I have a database containing information about members of a choir (which is divided into sections) and their parents. I need to build an e-mail list containing all children in a specific section of the choir as well as their parents.

There is a large table COMPersonen which contains all the personal information I need (especially their ID number Nummer and primary e-mail address Serienbrief E-Mail Adresse).

Another table COMPBereiche contains all the details about which section(s) (Bereich (Nr)) of the choir a certain person belonged to at a certain time. It is linked to the primary table via Nummer/Person (Nr). The [Bis] (= "until") field can be used to determine whether a person is currently a section member by checking if that field is either empty or set to a future date.

Lastly (at least for this purpose) there is a table COMElternKind that contains the ID number of all the parents (Elternteil (Nr)) and the ID numbers of their children (Kind (Nr)). Of course, each parent can have more than one child and vice versa.

So far, this is pretty straightforward. In Access, the relations look like this:

The easy part was building a query that returns all the addresses for the children in a specific section of the choir (for example the section with the ID Bereich (Nr) = 4):

```<code>SELECT COMPersonen.Nummer, COMPersonen.[Serienbrief E-Mail Adresse],
       COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
FROM COMPersonen
INNER JOIN COMPBereiche ON COMPersonen.[Nummer] = COMPBereiche.[Person (Nr)]
WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
AND ((COMPBereiche.[Bereich (Nr)])=4)
AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()));
</code>```

But now I also need the addresses of the parents whose children are in section 4 of the choir at the moment. How would I go about that? Finally, the two SELECT statements would need to be combined, but my guess is that that's a simple UNION, right?

答:
every parent+children whose have children in your logic, rowcount will be equal children count

```<code>select prnt.[Nummer] as parentnum, prnt.[Serienbrief E-Mail Adresse] as parentemail,
           prnt.[Bereich (Nr)] parentBereinch, prnt.[Bis] parentBis, chld.*
           from COMPersonen prnt
  INNER JOIN COMelternKind cmk, ON prnt.[Person (Nr)] = cmk.[Elternteil (Nr)]
  INNER JOIN
    (SELECT COMPersonen.Nummer as chldnum, COMPersonen.[Serienbrief E-Mail Adresse],
           COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
    FROM COMPersonen
    INNER JOIN (COMPersonenRel1
        INNER JOIN COMPBereiche
        ON COMPersonenRel1.[Person (Nr)] = COMPBereiche.[Person (Nr)])
    ON COMPersonen.[Nummer] = COMPersonenRel1.[Person (Nr)]
    WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
    AND ((COMPBereiche.[Bereich (Nr)])=4)
    AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()))) chld
ON cmk.[Kind (Nr)]) = chld.[chldnum]
</code>```

every parent whose have children in your logic, rowcount will be only parents count

```<code>select * from COMPersonen prnt
  INNER JOIN COMelternKind cmk, ON prnt.[Person (Nr)] = cmk.[Elternteil (Nr)]

  where exists (SELECT COMPersonen.Nummer as chldnum, COMPersonen.[Serienbrief E-Mail Adresse],
           COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
    FROM COMPersonen
    INNER JOIN (COMPersonenRel1
        INNER JOIN COMPBereiche
        ON COMPersonenRel1.[Person (Nr)] = COMPBereiche.[Person (Nr)])
    ON COMPersonen.[Nummer] = COMPersonenRel1.[Person (Nr)]
    WHERE ((COMPersonen.Nummer = cmk.[Kind (Nr)])
    AND ((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
    AND ((COMPBereiche.[Bereich (Nr)])=4)
    AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date())))
</code>```

Body:
I have a database containing information about members of a choir (which is divided into sections) and their parents. I need to build an e-mail list containing all children in a specific section of the choir as well as their parents.

There is a large table COMPersonen which contains all the personal information I need (especially their ID number Nummer and primary e-mail address Serienbrief E-Mail Adresse).

Another table COMPBereiche contains all the details about which section(s) (Bereich (Nr)) of the choir a certain person belonged to at a certain time. It is linked to the primary table via Nummer/Person (Nr). The [Bis] (= "until") field can be used to determine whether a person is currently a section member by checking if that field is either empty or set to a future date.

Lastly (at least for this purpose) there is a table COMElternKind that contains the ID number of all the parents (Elternteil (Nr)) and the ID numbers of their children (Kind (Nr)). Of course, each parent can have more than one child and vice versa.

So far, this is pretty straightforward. In Access, the relations look like this:

The easy part was building a query that returns all the addresses for the children in a specific section of the choir (for example the section with the ID Bereich (Nr) = 4):

SELECT COMPersonen.Nummer, COMPersonen.[Serienbrief E-Mail Adresse],
       COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
FROM COMPersonen
INNER JOIN COMPBereiche ON COMPersonen.[Nummer] = COMPBereiche.[Person (Nr)]
WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
AND ((COMPBereiche.[Bereich (Nr)])=4)
AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()));

But now I also need the addresses of the parents whose children are in section 4 of the choir at the moment. How would I go about that? Finally, the two SELECT statements would need to be combined, but my guess is that that's a simple UNION, right?

Body:
every parent+children whose have children in your logic, rowcount will be equal children count

select prnt.[Nummer] as parentnum, prnt.[Serienbrief E-Mail Adresse] as parentemail,
           prnt.[Bereich (Nr)] parentBereinch, prnt.[Bis] parentBis, chld.*
           from COMPersonen prnt
  INNER JOIN COMelternKind cmk, ON prnt.[Person (Nr)] = cmk.[Elternteil (Nr)]
  INNER JOIN
    (SELECT COMPersonen.Nummer as chldnum, COMPersonen.[Serienbrief E-Mail Adresse],
           COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
    FROM COMPersonen
    INNER JOIN (COMPersonenRel1
        INNER JOIN COMPBereiche
        ON COMPersonenRel1.[Person (Nr)] = COMPBereiche.[Person (Nr)])
    ON COMPersonen.[Nummer] = COMPersonenRel1.[Person (Nr)]
    WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
    AND ((COMPBereiche.[Bereich (Nr)])=4)
    AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()))) chld
ON cmk.[Kind (Nr)]) = chld.[chldnum]

every parent whose have children in your logic, rowcount will be only parents count

select * from COMPersonen prnt
  INNER JOIN COMelternKind cmk, ON prnt.[Person (Nr)] = cmk.[Elternteil (Nr)]

  where exists (SELECT COMPersonen.Nummer as chldnum, COMPersonen.[Serienbrief E-Mail Adresse],
           COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
    FROM COMPersonen
    INNER JOIN (COMPersonenRel1
        INNER JOIN COMPBereiche
        ON COMPersonenRel1.[Person (Nr)] = COMPBereiche.[Person (Nr)])
    ON COMPersonen.[Nummer] = COMPersonenRel1.[Person (Nr)]
    WHERE ((COMPersonen.Nummer = cmk.[Kind (Nr)])
    AND ((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
    AND ((COMPBereiche.[Bereich (Nr)])=4)
    AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date())))


问:
Multiple selectors: identify the triggering one?
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});
</code>```

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

答:
I would agree with Patrick and Dexter about separating these elements if they have different functionality. But if you are going to use this method, try using some of the built in javascript methods. I don't know what the HTML markup looks like, but assuming this markup, you can try the script below:</p>

```<code><a class="button" href="http://somesite.com">Some Site</a>
<span class="xyz">span</span>
<a class="another" href="/topics/topic2.html">Topic 2</a>

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked = 'a.another';
   if (this.tagName == "SPAN") { clicked = 'span.xyz'; }
   if (this.href.match('somesite')) { clicked = 'a.button'; }
   // Do something
});
</code>```

Body:
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

Body:
I would agree with Patrick and Dexter about separating these elements if they have different functionality. But if you are going to use this method, try using some of the built in javascript methods. I don't know what the HTML markup looks like, but assuming this markup, you can try the script below:

<a class="button" href="http://somesite.com">Some Site</a>
<span class="xyz">span</span>
<a class="another" href="/topics/topic2.html">Topic 2</a>

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked = 'a.another';
   if (this.tagName == "SPAN") { clicked = 'span.xyz'; }
   if (this.href.match('somesite')) { clicked = 'a.button'; }
   // Do something
});


问:
Resize UILabel & UIView automatically on UIViewController in a Playground
I have a UIViewController in my Playground Book on which I want to position a UILabel & UIView.

In the Playground Book the user is able to resize the UIViewController by Gestures but the content (the UILabel & UIView) does not resize. That means that the UILabel & UIView are bigger than the actual UIViewController sometimes. Also the UILabel & UIView need to be dismissible at some times.

I created my UIViewController like this

```<code>let window1 = WMWindow(frame: CGRectMake(150,150,400,300))
window1.title = "View 2"

let vc1 = UIViewController()
vc1.title = "View 2"
vc1.view = UIView()
vc1.view.backgroundColor = UIColor.white
let nc1 = UINavigationController(rootViewController: vc1)

window1.rootViewController = nc1
window1.makeKeyAndVisible()

window.addSubview(window1)
</code>```

and my UILabel & UIView like this

```<code>let textLabel = UILabel(frame: CGRect(x: 30, y: window1.bounds.height-50, width: window1.bounds.width, height: window1.bounds.height))
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 5
textLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

let backgroundView = UIView(frame: CGRect(x: 0, y: window1.bounds.height, width: window1.bounds.width, height: 200))
backgroundView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
backgroundView.alpha = 0.7
</code>```

and of course I added them as subviews to the UIViewController.

Now how can I change the UILabel and UIView to automatically resize depending on the size of the UIViewController?

I found out that I can instead of window1.addSubview(...) use vc1.view.addSubview(...). This line enables the user to resize the view and the subviews properly but unfortunately after a few seconds the subviews will be in the same position as the beginning.

答:
You need to add constraints to your views, for this to happen automatically.

For example this :

```<code>backgroundView.leadingAnchor.constraint(equalTo: vc1.view.leadingAnchor).isActive = true;
backgroundView.topAnchor.constraint(equalTo: vc1.view.topAnchor).isActive = true;
backgroundView.trailingAnchor.constraint(equalTo: vc1.view.trailingAnchor).isActive = true;
backgroundView.bottomAnchor.constraint(equalTo: vc1.view.bottomAnchor).isActive = true;
</code>```

will pin your backgroundView to match the exact size of the view controller.

As always, there is more in the docs :

Understanding AutoLayout

Programatically creating constraints

NSLayoutAnchor reference

--

Update :

I took a more careful look at your code, and with your comment it seems that you added your views as subviews of a window. You generally shouldn't do that. You should rather do it like this : vc1.view.addSubview(...). Also this vc1.view = UIView() is not needed, unless you wanted to provide a custom UIView subclass there.

Body:
I have a UIViewController in my Playground Book on which I want to position a UILabel & UIView.

In the Playground Book the user is able to resize the UIViewController by Gestures but the content (the UILabel & UIView) does not resize. That means that the UILabel & UIView are bigger than the actual UIViewController sometimes. Also the UILabel & UIView need to be dismissible at some times.

I created my UIViewController like this

let window1 = WMWindow(frame: CGRectMake(150,150,400,300))
window1.title = "View 2"

let vc1 = UIViewController()
vc1.title = "View 2"
vc1.view = UIView()
vc1.view.backgroundColor = UIColor.white
let nc1 = UINavigationController(rootViewController: vc1)

window1.rootViewController = nc1
window1.makeKeyAndVisible()

window.addSubview(window1)

and my UILabel & UIView like this

let textLabel = UILabel(frame: CGRect(x: 30, y: window1.bounds.height-50, width: window1.bounds.width, height: window1.bounds.height))
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 5
textLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

let backgroundView = UIView(frame: CGRect(x: 0, y: window1.bounds.height, width: window1.bounds.width, height: 200))
backgroundView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
backgroundView.alpha = 0.7

and of course I added them as subviews to the UIViewController.

Now how can I change the UILabel and UIView to automatically resize depending on the size of the UIViewController?

I found out that I can instead of window1.addSubview(...) use vc1.view.addSubview(...). This line enables the user to resize the view and the subviews properly but unfortunately after a few seconds the subviews will be in the same position as the beginning.

Body:
You need to add constraints to your views, for this to happen automatically.

For example this :

backgroundView.leadingAnchor.constraint(equalTo: vc1.view.leadingAnchor).isActive = true;
backgroundView.topAnchor.constraint(equalTo: vc1.view.topAnchor).isActive = true;
backgroundView.trailingAnchor.constraint(equalTo: vc1.view.trailingAnchor).isActive = true;
backgroundView.bottomAnchor.constraint(equalTo: vc1.view.bottomAnchor).isActive = true;

will pin your backgroundView to match the exact size of the view controller.

As always, there is more in the docs :

Understanding AutoLayout

Programatically creating constraints

NSLayoutAnchor reference

--

Update :

I took a more careful look at your code, and with your comment it seems that you added your views as subviews of a window. You generally shouldn't do that. You should rather do it like this : vc1.view.addSubview(...). Also this vc1.view = UIView() is not needed, unless you wanted to provide a custom UIView subclass there.


问:
How to get unique values in an array
How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?

I am going to be using JavaScript and jQuery only. No additional libraries can be used.

答:
I have tried this problem in pure JS.
I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value

```<code>// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];

//sort the given array
inpArr.sort(function(a, b){
    return a-b;
});

var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
    //check previous and next value
  if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
        finalArr.push(inpArr[i]);
  }
}
console.log(finalArr);
</code>```

Demo

Title: How to get unique values in an array

Body:
I have tried this problem in pure JS.
I have followed following steps 1. Sort the given array, 2. loop through the sorted array, 3. Verify previous value and next value with current value

// JS
var inpArr = [1, 5, 5, 4, 3, 3, 2, 2, 2,2, 100, 100, -1];

//sort the given array
inpArr.sort(function(a, b){
    return a-b;
});

var finalArr = [];
//loop through the inpArr
for(var i=0; i<inpArr.length; i++){
    //check previous and next value
  if(inpArr[i-1]!=inpArr[i] && inpArr[i] != inpArr[i+1]){
        finalArr.push(inpArr[i]);
  }
}
console.log(finalArr);

Demo


问:
why does binary search while loop condition ( l+1 != u)?
```<code>a = (1..10).to_a
def search(x, t)
  l = -1
  u = x.length

  while l+1 != u
    m = (l + u) / 2.round
    if x[m] < t
      l = m
    else
      u = m
    end
    puts "l:\t#{l} u:\t #{u} m:\t#{m}"
  end

  p = u
  puts "p: #{p} -> #{x[p]}"
  if p >= x.length || x[p] != t
    p = -1
  end
end

search(a, 5)
</code>```

i was research long times , but can't found the why,

l = -1

why initial assign the l to -1

while loop condition why is l+1 != u than l < u

i'm trying to understand that method ,finally can't eat it

can does help me ?

答:
l and u are lower and upper of your binary search.

Here you are assigning l to -1 and u to x.length. You can easily change the assignment of l from -1 to 0, and change the condition l+1 != u to l < u.

Body:
a = (1..10).to_a
def search(x, t)
  l = -1
  u = x.length

  while l+1 != u
    m = (l + u) / 2.round
    if x[m] < t
      l = m
    else
      u = m
    end
    puts "l:\t#{l} u:\t #{u} m:\t#{m}"
  end

  p = u
  puts "p: #{p} -> #{x[p]}"
  if p >= x.length || x[p] != t
    p = -1
  end
end

search(a, 5)

i was research long times , but can't found the why,

l = -1

why initial assign the l to -1

while loop condition why is l+1 != u than l < u

i'm trying to understand that method ,finally can't eat it

can does help me ?


问:
How do I use if isType() for each object on a canvas with fabric js?
I am trying to show certain attributes for each object on a canvas, but I am having a difficult time writing the code to do so. E.G. I want the code below to identify the difference between a shape, text, and image objects and show attributes based off the type.

Attributes to console.log:

for each object on canavas check to see if -

Image then URL (source) and scale <= I am having a difficult time
showing the source and name of the image.

Text then font family, font size, color, scale

Shape then scale and color

What do I need to add/remove/change to make it work?

Here is a JS fiddle example:
https://jsbin.com/vevihikefo/1/edit?html,js,console,output

```<code>canvas.getObjects().forEach(object=>{
    if(object.isType('xyz')) { // object is a shape
      console.log(object.scaleX, object.fill);
    } else if(object.isType('text')) { // object is a text
      console.log(object.text, object.fontFamily, object.fontSize*3, object.scaleX, object.fill);
    } else { // object is an image
      console.log(object.name, object.scaleX, object.fill);
    }
})
</code>```

答:
There are two things that need to be added / changed, to make it work ...

change object.isType('xyz') to !object.isType('text') && !object.isType('image')      ( as there isn't any type called 'xyz' )

wrap the entire code for getting the objects attributes in a function and call that function on image load, to get the image object attributes properly.

fabric.Object.prototype.objectCaching = false;
var canvas = new fabric.Canvas('canvas');
canvas.add(new fabric.Text('foo', {
    fontFamily: 'Roboto',
    left: 100,
    top: 100,
    fontSize: 25
}));
canvas.add(new fabric.Text('help', {
    fontFamily: 'Roboto',
    left: 100,
    top: 200,
    fontSize: 25
}));
canvas.add(new fabric.Triangle({
    fill: 'green',
    left: 200,
    top: 200
}));
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
    //i create an extra var for to change some image properties
    var img1 = myImg.set({
        left: 200,
        top: 0,
        width: 150,
        height: 150
    });
    canvas.add(img1);
    getAttributes();
});
canvas.renderAll();

function getAttributes() {
    canvas.getObjects().forEach(object => {
        if (!object.isType('text') && !object.isType('image')) { // object is a shape
            console.log(object.scaleX, object.fill);
        } else if (object.isType('text')) { // object is a text
            console.log(object.text, object.fontFamily, object.fontSize * 3, object.scaleX, object.fill);
        } else if (object.isType('image')) { // object is an image
            console.log(object.name, object.scaleX, object.fill);
        }
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="canvas" width="800" height="600" style="border: 1px solid #d3d3d3; position: absolute;">
Your browser does not support the canvas element.
</canvas></code>```

Body:
I am trying to show certain attributes for each object on a canvas, but I am having a difficult time writing the code to do so. E.G. I want the code below to identify the difference between a shape, text, and image objects and show attributes based off the type.

Attributes to console.log:

for each object on canavas check to see if -

Image then URL (source) and scale <= I am having a difficult time
showing the source and name of the image.

Text then font family, font size, color, scale

Shape then scale and color

What do I need to add/remove/change to make it work?

Here is a JS fiddle example:
https://jsbin.com/vevihikefo/1/edit?html,js,console,output

canvas.getObjects().forEach(object=>{
    if(object.isType('xyz')) { // object is a shape
      console.log(object.scaleX, object.fill);
    } else if(object.isType('text')) { // object is a text
      console.log(object.text, object.fontFamily, object.fontSize*3, object.scaleX, object.fill);
    } else { // object is an image
      console.log(object.name, object.scaleX, object.fill);
    }
})

Body:
There are two things that need to be added / changed, to make it work ...

change object.isType('xyz') to !object.isType('text') && !object.isType('image')      ( as there isn't any type called 'xyz' )

wrap the entire code for getting the objects attributes in a function and call that function on image load, to get the image object attributes properly.

fabric.Object.prototype.objectCaching = false;
var canvas = new fabric.Canvas('canvas');
canvas.add(new fabric.Text('foo', {
    fontFamily: 'Roboto',
    left: 100,
    top: 100,
    fontSize: 25
}));
canvas.add(new fabric.Text('help', {
    fontFamily: 'Roboto',
    left: 100,
    top: 200,
    fontSize: 25
}));
canvas.add(new fabric.Triangle({
    fill: 'green',
    left: 200,
    top: 200
}));
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
    //i create an extra var for to change some image properties
    var img1 = myImg.set({
        left: 200,
        top: 0,
        width: 150,
        height: 150
    });
    canvas.add(img1);
    getAttributes();
});
canvas.renderAll();

function getAttributes() {
    canvas.getObjects().forEach(object => {
        if (!object.isType('text') && !object.isType('image')) { // object is a shape
            console.log(object.scaleX, object.fill);
        } else if (object.isType('text')) { // object is a text
            console.log(object.text, object.fontFamily, object.fontSize * 3, object.scaleX, object.fill);
        } else if (object.isType('image')) { // object is an image
            console.log(object.name, object.scaleX, object.fill);
        }
    });
}

<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="canvas" width="800" height="600" style="border: 1px solid #d3d3d3; position: absolute;">
Your browser does not support the canvas element.
</canvas>


问:
How is the binary data of each character in a unicode string separated from the binary data of the next character?
in JavaScript I can get the Unicode from a single character using the charCodeAt-method.

When I use this to convert a string to the unicode number I will get following results:

"A".charCodeAt(0) === 65

"४".charCodeAt(0) === 2410

Converting these decimal numbers to binary numbers would be following:

"A".charCodeAt(0).toString(2) === "1000001" // 1 byte, with padleft: "01000001"

"४".charCodeAt(0).toString(2) === "100101101010" // 2 bytes, with padleft: "0000100101101010"

This means, that the ४-symbol uses 2 bytes to get represented. But how does the reading process know that?

It could be also two different characters " " and "j":

String.fromCharCode(parseInt("00001001", 2)) === " " // horizontal tabulator

String.fromCharCode(parseInt("01101010", 2)) === "j".

So how does the binary reading process know how many bytes are used for one single character? Is there something like a separator?

答:
Internally, JS uses UTF-16, that is, every code point from the plane 0 takes one 16-bit unit, and higher plane characters are represented as surrogate pairs and use two units.

Source encoding is UTF-8, that is, a character takes 1 to 4 bytes, depending on the leading bits of the first byte.


问:
Laravel 5.4 TokenMismatchException in VerifyCsrfToken.php line 68 on some device
I know it's one of the most asked question around here, but I really read everything on the first 10 pages results on google and nothing solved my problem.

On a fresh installation of laravel 5.4 , generated the auth controller, views, etc. via php artisan make:auth when I try to register (or login) in some device I get the following error:

TokenMismatchException in VerifyCsrfToken.php line 68

I'm running this application in local on debian 8.7 and php7 (could it be related to the problem in some way ?)
From my pc, iphone 7, another windows 10 desktop it works perfectly, but on a Huawei p8 lite, ipad 2 and lubuntu (quite old version) I get that error. So it's really weird because it just happends with some device (no matter whaht O.S. no matter what browser).

I can already tell you that I tried grant permissions to sessions folder, change session_domain, clearing cache (but as I said I'm trying this on a fresh installation), change {{ csrf_token }} to {!! csrf_token !!} , etc.

Just to give you more information about my system, this is the php version i'm using:

```<code>php --version
PHP 7.0.17-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.17-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend
Technologies
</code>```

I'm really stuck on this for days. Got no more ideas.

答:
I'm assuming you added $this->middleware('auth'); inside the constructor of your controller to get the authentication working. Add the following at the top as well, under your login/register forms, if you are using {!! Form::someElement !!}:

```<code>{!! csrf_field() !!}
</code>```

Or if you are using input tags inside your forms, just add this just after the <form> tag:

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}">
</code>```

Body:
I know it's one of the most asked question around here, but I really read everything on the first 10 pages results on google and nothing solved my problem.

On a fresh installation of laravel 5.4 , generated the auth controller, views, etc. via php artisan make:auth when I try to register (or login) in some device I get the following error:

TokenMismatchException in VerifyCsrfToken.php line 68

I'm running this application in local on debian 8.7 and php7 (could it be related to the problem in some way ?)
From my pc, iphone 7, another windows 10 desktop it works perfectly, but on a Huawei p8 lite, ipad 2 and lubuntu (quite old version) I get that error. So it's really weird because it just happends with some device (no matter whaht O.S. no matter what browser).

I can already tell you that I tried grant permissions to sessions folder, change session_domain, clearing cache (but as I said I'm trying this on a fresh installation), change {{ csrf_token }} to {!! csrf_token !!} , etc.

Just to give you more information about my system, this is the php version i'm using:

php --version
PHP 7.0.17-1~dotdeb+8.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.17-1~dotdeb+8.1, Copyright (c) 1999-2017, by Zend
Technologies

I'm really stuck on this for days. Got no more ideas.

Body:
I'm assuming you added $this->middleware('auth'); inside the constructor of your controller to get the authentication working. Add the following at the top as well, under your login/register forms, if you are using {!! Form::someElement !!}:

{!! csrf_field() !!}

Or if you are using input tags inside your forms, just add this just after the <form> tag:

<input type="hidden" name="_token" value="{{ csrf_token() }}">


问:
Is there an open source C visual debugger for windows?
Is there an open source C visual debugger for windows?
I have heard about the visual C++ express free edition, but does it have a visual debugger?

Thanks.

答: I found a claim that the DDD debugger will run on Windows under Cygwin.  I've used DDD quite a bit and like it.</p>

OwnerDisplayName: linkedlist

LastEditorDisplayName: splattne

OwnerDisplayName: Norman Ramsey


问:
async process dialog not showing in application in android
async process dialog is not showing in application in android. Can anybody tell me what the problem is?

My code

```<code>public void onClick(View v)
{
  new FetchTask(getBaseContext()).execute(null);
}

 public class FetchTask extends AsyncTask<Object, ArrayList,ArrayList>
 {

     private ProgressDialog dlg;
     private Context ctx;

     public FetchTask(Context context) {
         ctx = context;
     }

     @Override
     protected void onPreExecute() {
         dlg = new ProgressDialog(ctx);
         dlg.setMessage("Loading....");
         dlg.show();
         super.onPreExecute();
     }

     @Override
     protected void onPostExecute(ArrayList parserValue) {
         dlg.dismiss();

           for(int i=0;i<parservalue.size();i++)
             {
                DomParserDataSet dataset=(DomParserDataSet)parservalue.get(i);
                 if(dataset.getToken_string().length()>1)
                      {

                  Intent homeIntent=new Intent(ctx,HelloTabWidget.class);
                  homeIntent.putExtra("strUserName", username);
                  homeIntent.putExtra("strPassword",password );
                  homeIntent.putExtra("questGroupId",dataset.getQuest_group_id());
                  homeIntent.putExtra("userid",dataset.getUser_id());
                  homeIntent.putExtra("systemuserid", dataset.getSystem_user_id());
                  homeIntent.putExtra("providerid",dataset.getIndex_provider_id());
                       startActivity(homeIntent);
                   //startActivity(new Intent(this,HelloTabWidget.class));

                   }
                   else
                   {

                     DomParserDataSet dataset1=(DomParserDataSet)parservalue.get(i);
                     AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
                      alertbox.setMessage(dataset1.getError_value());
                         alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                           public void onClick(DialogInterface dialog, int arg1) {
                               // the button was clicked

                            dialog.cancel();

                           }
                       });

                       // show it
                       alertbox.show();
                   }

             }

             // display data
         }

  @Override
  protected ArrayList doInBackground(Object... arg0) {

   try
      {
          username=edtUserName.getText().toString();
          password=edtPassword.getText().toString();
          WebService service=new WebService();
          String webservicevalue=service.callServer(SOAP_ACTION,"", username,password,URL);
            webservicevalue=decodeXMLData(webservicevalue);
            DomParser xmlParser=new DomParser();
           parservalue=xmlParser.parseXmlFile(webservicevalue);

           String parservalue1=Integer.toString(parservalue.size());

           Log.d("parser value size is",parservalue1);

            }
             catch (Exception e) {
       // TODO: handle exception
              e.printStackTrace();
      }

             return parservalue;
       }

 }
</code>```

Can anybody tell me what I have to change?

答:
Ok, in addition to Nailuj's guess here is another couple of qualified guesses:

Could it be ProgressDialog constructor expects an instance of a wrapping Activity as a context instead of Activity.getBaseContext() (BTW, I hope the getBaseContext() is called on an Activity instance (?))?

Could it be FetchTask.doInBackground() runs so quickly (maybe some error happens, see what LogCat says) that ProgressDialog just have no time to show up?

Body:
async process dialog is not showing in application in android. Can anybody tell me what the problem is?

My code

public void onClick(View v)
{
  new FetchTask(getBaseContext()).execute(null);
}

 public class FetchTask extends AsyncTask<Object, ArrayList,ArrayList>
 {

     private ProgressDialog dlg;
     private Context ctx;

     public FetchTask(Context context) {
         ctx = context;
     }

     @Override
     protected void onPreExecute() {
         dlg = new ProgressDialog(ctx);
         dlg.setMessage("Loading....");
         dlg.show();
         super.onPreExecute();
     }

     @Override
     protected void onPostExecute(ArrayList parserValue) {
         dlg.dismiss();

           for(int i=0;i<parservalue.size();i++)
             {
                DomParserDataSet dataset=(DomParserDataSet)parservalue.get(i);
                 if(dataset.getToken_string().length()>1)
                      {

                  Intent homeIntent=new Intent(ctx,HelloTabWidget.class);
                  homeIntent.putExtra("strUserName", username);
                  homeIntent.putExtra("strPassword",password );
                  homeIntent.putExtra("questGroupId",dataset.getQuest_group_id());
                  homeIntent.putExtra("userid",dataset.getUser_id());
                  homeIntent.putExtra("systemuserid", dataset.getSystem_user_id());
                  homeIntent.putExtra("providerid",dataset.getIndex_provider_id());
                       startActivity(homeIntent);
                   //startActivity(new Intent(this,HelloTabWidget.class));

                   }
                   else
                   {

                     DomParserDataSet dataset1=(DomParserDataSet)parservalue.get(i);
                     AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
                      alertbox.setMessage(dataset1.getError_value());
                         alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

                           public void onClick(DialogInterface dialog, int arg1) {
                               // the button was clicked

                            dialog.cancel();

                           }
                       });

                       // show it
                       alertbox.show();
                   }

             }

             // display data
         }

  @Override
  protected ArrayList doInBackground(Object... arg0) {

   try
      {
          username=edtUserName.getText().toString();
          password=edtPassword.getText().toString();
          WebService service=new WebService();
          String webservicevalue=service.callServer(SOAP_ACTION,"", username,password,URL);
            webservicevalue=decodeXMLData(webservicevalue);
            DomParser xmlParser=new DomParser();
           parservalue=xmlParser.parseXmlFile(webservicevalue);

           String parservalue1=Integer.toString(parservalue.size());

           Log.d("parser value size is",parservalue1);

            }
             catch (Exception e) {
       // TODO: handle exception
              e.printStackTrace();
      }

             return parservalue;
       }

 }

Can anybody tell me what I have to change?


问:
How can I implement a view such that it increase like a rounded circle
I have a task in which I have to increase the view size depending on timer value. I know view frame will be increased, however I am searching the way like the first round completed then another layer round comes on it so that the view frame size increased and the desired output will also shows.

答:
Here is Code.</p>

```<code>import UIKit

class ViewController: UIViewController{
    var offsetx:CGFloat!
    var offsety:CGFloat!
    var size: CGFloat!
    var timer: Timer!

    override func viewDidLoad() {
        super.viewDidLoad()
        offsetx = view.frame.size.width/2.0;
        offsety = view.frame.size.height/2.0;
        size = 1.0
        timer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(drawCircle), userInfo: nil, repeats: true)
    }

    func drawCircle() {
        let cirecle:UIView = UIView()
        cirecle.frame = CGRect(x: offsetx, y: offsety, width: size, height: size);
        cirecle.layer.borderColor = UIColor.green.cgColor
        cirecle.layer.borderWidth = 1.0
        cirecle.backgroundColor = UIColor.clear
        cirecle.layer.cornerRadius = size / 2.0
        offsetx = offsetx - 6.0
        offsety = offsety - 6.0
        size = size + 12.0
        view.addSubview(cirecle)

    }
</code>```

Body:
Here is Code.

import UIKit

class ViewController: UIViewController{
    var offsetx:CGFloat!
    var offsety:CGFloat!
    var size: CGFloat!
    var timer: Timer!

    override func viewDidLoad() {
        super.viewDidLoad()
        offsetx = view.frame.size.width/2.0;
        offsety = view.frame.size.height/2.0;
        size = 1.0
        timer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(drawCircle), userInfo: nil, repeats: true)
    }

    func drawCircle() {
        let cirecle:UIView = UIView()
        cirecle.frame = CGRect(x: offsetx, y: offsety, width: size, height: size);
        cirecle.layer.borderColor = UIColor.green.cgColor
        cirecle.layer.borderWidth = 1.0
        cirecle.backgroundColor = UIColor.clear
        cirecle.layer.cornerRadius = size / 2.0
        offsetx = offsetx - 6.0
        offsety = offsety - 6.0
        size = size + 12.0
        view.addSubview(cirecle)

    }


问:
Neural Network to predict nth square
I am trying to use multi-layer neural network to predict nth square.

I have the following training data containing the first 99 squares

```<code>1    1
2    4
3    9
4    16
5    25
...
98   9604
99   9801
</code>```

This is the code:

```<code>import numpy as np
import neurolab as nl

# Load input data
text = np.loadtxt('data_sq.txt')

# Separate it into datapoints and labels
data = text[:, :1]
labels = text[:, 1:]

# Define a multilayer neural network with 2 hidden layers;
# First hidden layer consists of 10 neurons
# Second hidden layer consists of 6 neurons
# Output layer consists of 1 neuron
nn = nl.net.newff([[0, 99]], [10, 6, 1])

# Train the neural network
error_progress = nn.train(data, labels, epochs=2000, show=10, goal=0.01)

# Run the classifier on test datapoints
print('\nTest results:')
data_test = [[100], [101]]
for item in data_test:
    print(item, '-->', nn.sim([item])[0])
</code>```

Which prints 1 for both 100th and 101st squares:

```<code>Test results:
[100] --> [ 1.]
[101] --> [ 1.]
</code>```

What is the right way to do this?

答:
Checked the docs for neurolab - newff creates NN with sigmoid transfer function in all neurons by default. Sigmoid value is always in (-1; 1) range, so your output will never leave this range.

Second square (4) is already out of this range, so your code doesn't match your problem at all.

Try using other functions (I'd propose SoftPlus or ReLU). They work quite well with feed-forward networks, allow for backpropagation training (as they are derivable in whole domain) and have values in range (0, ∞), just as you need.

Also: first param to newff defines ranges for input data - you're using [0, 99] which matches all the training data, but doesn't match values that you've tried while testing (since 100 and 101 are bigger than 99). Change this value to something way bigger, so the values you test on are not "special" (meaning "on the end of the range") - I'd propose something like [-300, 300].

Besides, as stated by Seanny123 in a comment, I don't think it's gonna work at all, but with current setup I can be sure of that. Good luck. Let me know (for example in comments) if you succeeded.

Last, but not least - what you're trying to do is extrapolation (figuring out values out of some range based on values in that range). NN are better suited for interpolation (figuring out values in the range based on samples from that range), as they are supposed to generalize data used in training. Try teaching it squares of, for example, every 3rd square (so 1, 16, 49, ...) and then testing by asking for squares of the rest (for example asking for square of 2 or 8).

Title: Neural Network to predict nth square

Body:
I am trying to use multi-layer neural network to predict nth square.

I have the following training data containing the first 99 squares

1    1
2    4
3    9
4    16
5    25
...
98   9604
99   9801

This is the code:

import numpy as np
import neurolab as nl

# Load input data
text = np.loadtxt('data_sq.txt')

# Separate it into datapoints and labels
data = text[:, :1]
labels = text[:, 1:]

# Define a multilayer neural network with 2 hidden layers;
# First hidden layer consists of 10 neurons
# Second hidden layer consists of 6 neurons
# Output layer consists of 1 neuron
nn = nl.net.newff([[0, 99]], [10, 6, 1])

# Train the neural network
error_progress = nn.train(data, labels, epochs=2000, show=10, goal=0.01)

# Run the classifier on test datapoints
print('\nTest results:')
data_test = [[100], [101]]
for item in data_test:
    print(item, '-->', nn.sim([item])[0])

Which prints 1 for both 100th and 101st squares:

Test results:
[100] --> [ 1.]
[101] --> [ 1.]

What is the right way to do this?


问:
Picasso fail to load image locally
i am try to download a image and save it locally. Everything runs trough i didnt get any exceptions, but the file dont appear in my location

i searched for an solution but didnt find any.

Heres my code:

```<code>private void saveImages() {
    try{
        final File thumbsPath = new File(getExternalFilesDir(null), "thumbs");
        if (!thumbsPath.exists())
            thumbsPath.mkdirs();
        Target target = new Target(){
            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        File file = new File(thumbsPath.getAbsolutePath() + "/file.jpeg"); //folder exists
                        try {
                            file.createNewFile();
                            FileOutputStream ostream = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                            ostream.flush();
                            ostream.close();
                        } catch (Exception e) {
                            Log.e("ERROR", e.getMessage());
                        }
                    }
                }).start();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Log.e("ERROR", "");
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                Log.e("ERROR", "");
            }
        };
        Picasso.with(getApplicationContext())
                .load(myurltodownloadfrom)
                .into(target);
    }
    catch (Exception e){
        Log.e("ERROR",e.getMessage());
    }
}
</code>```

答:
Never store Files that way.
It is all covered here: https://developer.android.com/training/basics/data-storage/files.html</p>

Title: Picasso fail to load image locally

Body:
i am try to download a image and save it locally. Everything runs trough i didnt get any exceptions, but the file dont appear in my location

i searched for an solution but didnt find any.

Heres my code:

private void saveImages() {
    try{
        final File thumbsPath = new File(getExternalFilesDir(null), "thumbs");
        if (!thumbsPath.exists())
            thumbsPath.mkdirs();
        Target target = new Target(){
            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        File file = new File(thumbsPath.getAbsolutePath() + "/file.jpeg"); //folder exists
                        try {
                            file.createNewFile();
                            FileOutputStream ostream = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                            ostream.flush();
                            ostream.close();
                        } catch (Exception e) {
                            Log.e("ERROR", e.getMessage());
                        }
                    }
                }).start();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Log.e("ERROR", "");
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                Log.e("ERROR", "");
            }
        };
        Picasso.with(getApplicationContext())
                .load(myurltodownloadfrom)
                .into(target);
    }
    catch (Exception e){
        Log.e("ERROR",e.getMessage());
    }
}


问:
SourceTree - rebase - Errors During Merge
I'm trying to do something simple like editing the commit message for a previous commit.

Checking git status I have:

```<code>nothing to commit, working directory clean
</code>```

I then click on the commit and do SourceTree > Repository > Interactive Rebase...

but get this dialog box, and a completely blank/empty description area:

Note: I read somewhere that this might be due to FileMerge creating a .orig backup file. However, looking through FileMerge preferences I don't see anything about backup files

答:
Branch is not tracked:</p>

```<code>git branch --set-upstream-to=origin/<your_branch_name>
</code>```

Body:
I'm trying to do something simple like editing the commit message for a previous commit.

Checking git status I have:

nothing to commit, working directory clean

I then click on the commit and do SourceTree > Repository > Interactive Rebase...

but get this dialog box, and a completely blank/empty description area:

Note: I read somewhere that this might be due to FileMerge creating a .orig backup file. However, looking through FileMerge preferences I don't see anything about backup files

Body:
Branch is not tracked:

git branch --set-upstream-to=origin/<your_branch_name>


问:
How to break out of switch case from inside a function defined inside the switch case in golang?
The question sounds weird but I didn't know any better way to put it. I am using goquery and I am inside a switch-case:

```<code>switch{
    case url == url1:
        doc.Find("xyz").Each(func(i int,s *goquery.Selection){
            a,_ := s.Attr("href")
            if a== b{
                //I want to break out of the switch case right now. I dont want to iterate through all the selections. This is the value.
                break
            }
        })
}
</code>```

Using break gives the following error:
break is not in a loop

What should I use here to break out of the switch-case instead of letting the program iterate over each of the selections and run my function over each of them?

答:
You should make use of goquery's EachWithBreak method to stop iterating over the selection:

```<code>switch {
    case url == url1:
        doc.Find("xyz").EachWithBreak(func(i int,s *goquery.Selection) bool {
            a,_ := s.Attr("href")
            return a != b
        })
}
</code>```

As long as there's no remaining code in your switch case, you do not need to use a break.

Body:
The question sounds weird but I didn't know any better way to put it. I am using goquery and I am inside a switch-case:

switch{
    case url == url1:
        doc.Find("xyz").Each(func(i int,s *goquery.Selection){
            a,_ := s.Attr("href")
            if a== b{
                //I want to break out of the switch case right now. I dont want to iterate through all the selections. This is the value.
                break
            }
        })
}

Using break gives the following error:
break is not in a loop

What should I use here to break out of the switch-case instead of letting the program iterate over each of the selections and run my function over each of them?

Body:
You should make use of goquery's EachWithBreak method to stop iterating over the selection:

switch {
    case url == url1:
        doc.Find("xyz").EachWithBreak(func(i int,s *goquery.Selection) bool {
            a,_ := s.Attr("href")
            return a != b
        })
}

As long as there's no remaining code in your switch case, you do not need to use a break.


问:
Passing an object to custom view in Google maps SDK
I have custom view (a nib with its class) that I show when user taps on map marker. I also have an array of objects from where I'd like to show data of selected object when user taps on one of the markers. I create markers from the same array in a separate method. How to I get my element in array (to show additional data) when user taps the marker ? Or is there another way to get the object from array based on pressed marker. Apart from regexing based on lon and lat etc ?</p>

答:
I solved this by adding my model to

```<code>marker.userData
</code>```

example:

```<code>func addMarkers(){

    for place in places{

        let marker = GMSMarker()
        let placeLat = place.latitude
        let placeLon = place.longitude
        marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(placeLat), longitude: CLLocationDegrees(placeLon))
        marker.appearAnimation = .pop
        marker.map = mpView
        marker.userData = place

    }

}
</code>```

Then later I access it in:

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

```<code>    let title = (marker.userData as! placeModel).name
    let add = (marker.userData as! placeModel).address
    let id = (marker.userData as! placeModel).id
    let image = (marker.userData as! placeModel).image
    let imageAddressInDocuments = ("\(getDocumentsDirectory())\(image)")
    print("image address in documents %@", imageAddressInDocuments )
    var infoWindow = Bundle.main.loadNibNamed("custView", owner: self, options: nil)?.first as! custView
    infoWindow.titleLabel.text = title
    infoWindow.addressLabel.text = add
    infoWindow.restaurantImage.image = image != "" ? UIImage(contentsOfFile: imageAddressInDocuments) : UIImage(named: "addImage")

    return infoWindow
}
</code>```

Body:
I solved this by adding my model to

marker.userData

example:

func addMarkers(){

    for place in places{

        let marker = GMSMarker()
        let placeLat = place.latitude
        let placeLon = place.longitude
        marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(placeLat), longitude: CLLocationDegrees(placeLon))
        marker.appearAnimation = .pop
        marker.map = mpView
        marker.userData = place

    }

}

Then later I access it in:

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

    let title = (marker.userData as! placeModel).name
    let add = (marker.userData as! placeModel).address
    let id = (marker.userData as! placeModel).id
    let image = (marker.userData as! placeModel).image
    let imageAddressInDocuments = ("\(getDocumentsDirectory())\(image)")
    print("image address in documents %@", imageAddressInDocuments )
    var infoWindow = Bundle.main.loadNibNamed("custView", owner: self, options: nil)?.first as! custView
    infoWindow.titleLabel.text = title
    infoWindow.addressLabel.text = add
    infoWindow.restaurantImage.image = image != "" ? UIImage(contentsOfFile: imageAddressInDocuments) : UIImage(named: "addImage")

    return infoWindow
}


问:
Configurable .NET Analyzer
I created a DiagnosticAnalyzer + CodeFixProvider that checks all public properties/methods of a class if they have virtual modifier (because of NHibernate proxies). But this should only be done on classes that implements some interface. For now I hardcoded those interfaces into analyzer code. What is the best option to make them configurable via configuration file included in project? Example configuration file:

```<code><VirtualAnalzyer>
    <ValidTypes>
        <ValidType>IEntity</ValidType>
        <ValidType>IVersionedEntity</ValidType>
    </ValidTypes>
<VirtualAnalzyer>
</code>```

答: I solved it by using additional files. Read this answer on how to include AdditionalFile in csproj.</p>

Title: Configurable .NET Analyzer

Body:
I created a DiagnosticAnalyzer + CodeFixProvider that checks all public properties/methods of a class if they have virtual modifier (because of NHibernate proxies). But this should only be done on classes that implements some interface. For now I hardcoded those interfaces into analyzer code. What is the best option to make them configurable via configuration file included in project? Example configuration file:

<VirtualAnalzyer>
    <ValidTypes>
        <ValidType>IEntity</ValidType>
        <ValidType>IVersionedEntity</ValidType>
    </ValidTypes>
<VirtualAnalzyer>


问:
Why can't I input it at once and output it?
This code was run through Atom.

Why can't I input it once and then output it?

Once the desired temperature is entered, the converted temperature should be output.

Conditions: Keep Three Functions, Using a main function to run three functions

```<code>def main():
    print("This program converts Celsius into fahrenheit.")
    print("============================")
    # ===Modify codes below=================
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
    print_fahrenheit_value(celsius_value, fahrenheit_value)
    print("===========================")
    print("Program has ended.")

def input_celsius_value():
    celsius_value = float(input("Enter desired temperature to convert.: "))
    return celsius_value

def convert_celsius_fahrenheit(fahrenheit_value):
    celsius_value = float(input())
    fahrenheit_value = ((9/5) * float(celsius_value)) + 32
    return fahrenheit_value

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(fahrenheit_value)
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)
    return print_fahrenheit_value

if __name__ == '__main__':
    main()
</code>```

答:
In your convert_celsius_fahrenheit method you are taking user input for celsius value again which is not required as you have already taken the user input in input_celsius_value method and have stored the provided value in celsius_value variable in main method while doing celsius_value = input_celsius_value().

Similarly in your print_fahrenheit_value method you are calling input_celsius_value method and convert_celsius_fahrenheit which are again taking a user input for celsius value.

So in all, you are taking user input four times and doing celsius to fahrenheit conversion twice.

Moreover your convert_celsius_fahrenheit method should take celsius value as an argument.

Change your convert_celsius_fahrenheit and print_fahrenheit_value methods to something like this:

```<code>def convert_celsius_fahrenheit(celsius_value):
    return 9 / 5 * celsius_value + 32

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)
</code>```

Body:
This code was run through Atom.

Why can't I input it once and then output it?

Once the desired temperature is entered, the converted temperature should be output.

Conditions: Keep Three Functions, Using a main function to run three functions

def main():
    print("This program converts Celsius into fahrenheit.")
    print("============================")
    # ===Modify codes below=================
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
    print_fahrenheit_value(celsius_value, fahrenheit_value)
    print("===========================")
    print("Program has ended.")

def input_celsius_value():
    celsius_value = float(input("Enter desired temperature to convert.: "))
    return celsius_value

def convert_celsius_fahrenheit(fahrenheit_value):
    celsius_value = float(input())
    fahrenheit_value = ((9/5) * float(celsius_value)) + 32
    return fahrenheit_value

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(fahrenheit_value)
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)
    return print_fahrenheit_value

if __name__ == '__main__':
    main()

Body:
In your convert_celsius_fahrenheit method you are taking user input for celsius value again which is not required as you have already taken the user input in input_celsius_value method and have stored the provided value in celsius_value variable in main method while doing celsius_value = input_celsius_value().

Similarly in your print_fahrenheit_value method you are calling input_celsius_value method and convert_celsius_fahrenheit which are again taking a user input for celsius value.

So in all, you are taking user input four times and doing celsius to fahrenheit conversion twice.

Moreover your convert_celsius_fahrenheit method should take celsius value as an argument.

Change your convert_celsius_fahrenheit and print_fahrenheit_value methods to something like this:

def convert_celsius_fahrenheit(celsius_value):
    return 9 / 5 * celsius_value + 32

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)


问:
Google endpoint method keeps returning "name must not be empty" exception
The endpoint method looks like this:

```<code>@Api(
    name = "gameape",
    version = "v1",
    description = "Game App API",
    audiences = { "mynumber.apps.googleusercontent.com" },
    clientIds = { "mynumber.apps.googleusercontent.com", Constant.API_EXPLORER_CLIENT_ID },
    defaultVersion = AnnotationBoolean.TRUE)
public class GameApp {

    private final AccountDao accountDao = new AccountDaoImpl();

    @ApiMethod(name = "LoginUser", path = "LoginUser", httpMethod = HttpMethod.POST)
    public void LoginUser(LoginData request) {
        long phone = request.getPhone();
        String deviceId = request.getDeviceId();
        String gcmToken = request.getGcmToken();
        Account acc = new Account(phone, deviceId, gcmToken);
        accountDao.put(acc);
        ApiHelper.sendGCM(phone, "welcome to my game app");
    }
}
</code>```

The snippet from android looks like this:

```<code>@Override
protected Boolean doInBackground(Void... params) {
    LoginData request = new LoginData();
    request.setUsername(username);
    request.setPassword(password);

   try {
     RegisterUser reg = service.registerUser(request);
     reg.execute();
     return true;
   } catch (Exception e) {
     Log.e(LoginActivity.class.getName(),
        "Exception received from server at "
         + service.getRootUrl(), e);
   }
   return false;
}
</code>```

Calling reg.execute() keeps throwing the exception:

```<code>java.lang.IllegalArgumentException: the name must not be empty: null
</code>```

From the server console, it does not even look like the server is being hit. Even when I try running the server in debug mode, my breakpoint (first line inside method) is not reached.

EDIT: adding stack trace:

```<code>04-03 13:38:42.688: I/com.me.gameapp.LoginActivity$UserLoginTask(11255): Enter doInBackground
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255): Exception received from server at https://1.myapp.appspot.com/_ah/api/
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255): java.lang.IllegalArgumentException: the name must not be empty: null
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.Parcel.readException(Parcel.java:1251)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.Parcel.readException(Parcel.java:1235)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.internal.x$a$a.a(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:192)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:217)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:836)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.me.gameapp.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:262)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.me.gameapp.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:1)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.lang.Thread.run(Thread.java:1096)
04-03 13:38:42.786: I/com.me.gameapp.LoginActivity$UserLoginTask(11255): Leave doInBackground with false
</code>```

In the line Exception received from server at https://1.myapp.appspot.com/_ah/api/, I am running everything on localhost. Maybe https://1.myapp.appspot.com/_ah/api/ is wrong. My code is very close to the template, though, so I am not sure that's a change I committed.

答:
My solution was to use

```<code>credential.setSelectedAccount(new Account(settings.getString(Constants.PREF_ACCOUNT_NAME, null), "com.example.myapplication"));
</code>```

So I used setSelectedAccount instead of setSelectedAccountName

Body:
The endpoint method looks like this:

@Api(
    name = "gameape",
    version = "v1",
    description = "Game App API",
    audiences = { "mynumber.apps.googleusercontent.com" },
    clientIds = { "mynumber.apps.googleusercontent.com", Constant.API_EXPLORER_CLIENT_ID },
    defaultVersion = AnnotationBoolean.TRUE)
public class GameApp {

    private final AccountDao accountDao = new AccountDaoImpl();

    @ApiMethod(name = "LoginUser", path = "LoginUser", httpMethod = HttpMethod.POST)
    public void LoginUser(LoginData request) {
        long phone = request.getPhone();
        String deviceId = request.getDeviceId();
        String gcmToken = request.getGcmToken();
        Account acc = new Account(phone, deviceId, gcmToken);
        accountDao.put(acc);
        ApiHelper.sendGCM(phone, "welcome to my game app");
    }
}

The snippet from android looks like this:

@Override
protected Boolean doInBackground(Void... params) {
    LoginData request = new LoginData();
    request.setUsername(username);
    request.setPassword(password);

   try {
     RegisterUser reg = service.registerUser(request);
     reg.execute();
     return true;
   } catch (Exception e) {
     Log.e(LoginActivity.class.getName(),
        "Exception received from server at "
         + service.getRootUrl(), e);
   }
   return false;
}

Calling reg.execute() keeps throwing the exception:

java.lang.IllegalArgumentException: the name must not be empty: null

From the server console, it does not even look like the server is being hit. Even when I try running the server in debug mode, my breakpoint (first line inside method) is not reached.

EDIT: adding stack trace:

04-03 13:38:42.688: I/com.me.gameapp.LoginActivity$UserLoginTask(11255): Enter doInBackground
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255): Exception received from server at https://1.myapp.appspot.com/_ah/api/
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255): java.lang.IllegalArgumentException: the name must not be empty: null
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.Parcel.readException(Parcel.java:1251)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.Parcel.readException(Parcel.java:1235)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.internal.x$a$a.a(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:192)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:217)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:836)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.me.gameapp.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:262)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at com.me.gameapp.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:1)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-03 13:38:42.786: E/com.me.gameapp.LoginActivity(11255):  at java.lang.Thread.run(Thread.java:1096)
04-03 13:38:42.786: I/com.me.gameapp.LoginActivity$UserLoginTask(11255): Leave doInBackground with false

In the line Exception received from server at https://1.myapp.appspot.com/_ah/api/, I am running everything on localhost. Maybe https://1.myapp.appspot.com/_ah/api/ is wrong. My code is very close to the template, though, so I am not sure that's a change I committed.

Body:
My solution was to use

credential.setSelectedAccount(new Account(settings.getString(Constants.PREF_ACCOUNT_NAME, null), "com.example.myapplication"));

So I used setSelectedAccount instead of setSelectedAccountName


问:
System.Reflection.MissingMetadataException with Newtonsoft.Json in Xamarin project
I have Xamarin Project UWP. I need to parse data in json format with Newtonsoft.Json, taking method Newtonsoft.Json.JsonConvert.DeserializeObject() with Converter. I implement CustomCreationConverter and method ReadJson().
In Release after optimasation it does not work. And I have sush errors as:
"The value of the local variable or the "reader" argument can not be obtained because it is not available at this execution point, it may have been discarded during optimization. Newtonsoft.Json.JsonReader"

I want to try adding runtime directivesin in rd.xml, but don't sure what I should what need to add.

答:
UWP apps are compiled using .NET Native tool chain by default when they're compiled in Release mode. .NET Native compiler does some optimalizations (for example removes any classes, fields and so on that haven't been referenced anywhere) and generates static code, however Reflection uses dynamic features of .NET. So in order get rid of the System.Reflection.MissingMetadataException you'll have to write some Runtime Directives.

There is also a good series of five blog posts about this issue on .NET Blog:

.NET Native Deep Dive: Dynamic Features in Static Code

.NET Native Deep Dive: Help! I Hit a MissingMetadataException!

.NET Native Deep Dive: Help! I Didn’t Hit a MissingMetadataException!

.NET Native Deep Dive: Making Your Library Great

.NET Native Deep Dive: Optimizing with Runtime Directives

I suggest reading all of them since it could help you to understand what is happening and how to prevent experiencing similar issues in the future.


问:
Entity framework core can allow to specify two different length for column one for database and other for modal.validation?
Entity framework core can allow to specify two different length of column one for database and other for modal.validation?</p>

答: It's better to use separate modal for Database and View.</p>


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
Use ToTitleCase() first and then keep a list of applicable words and Replace back to the all-lower-case version of those applicable words (provided that list is small).

The list of applicable words could be kept in a dictionary and looped through pretty efficiently, replacing with the .ToLower() equivalent.

Title: Capitalizing words in a string using C#


问:
Shared preference value is null in my second acivity
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file

```<code> SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
    @Override
    public void onReceivedData(byte[] arg0) {

        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
             sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor et = sp.edit();
            et.putString("key",data);
            et.apply();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};
</code>```

In second activity

```<code>    protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    desiredPreference =  sharedPreferences.getString("key","data");
    Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();

}
</code>```

答:
The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.

```<code>SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference =  sharedPreferences.getString("key","data");
</code>```

To know more about the difference you can check the documentation and this answer.

Body:
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file

 SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
    @Override
    public void onReceivedData(byte[] arg0) {

        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
             sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor et = sp.edit();
            et.putString("key",data);
            et.apply();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};

In second activity

    protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    desiredPreference =  sharedPreferences.getString("key","data");
    Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();

}

Body:
The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.

SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference =  sharedPreferences.getString("key","data");

To know more about the difference you can check the documentation and this answer.


问:
Can you split/explode a field in a MySQL query?
I have to create a report on some student completions. The students each belong to one client. Here are the tables (simplified for this question).

```<code>CREATE TABLE  `clients` (
  `clientId` int(10) unsigned NOT NULL auto_increment,
  `clientName` varchar(100) NOT NULL default '',
  `courseNames` varchar(255) NOT NULL default ''
)
</code>```

The courseNames field holds a comma-delimited string of course names, eg "AB01,AB02,AB03"

```<code>CREATE TABLE  `clientenrols` (
  `clientEnrolId` int(10) unsigned NOT NULL auto_increment,
  `studentId` int(10) unsigned NOT NULL default '0',
  `courseId` tinyint(3) unsigned NOT NULL default '0'
)
</code>```

The courseId field here is the index of the course name in the clients.courseNames field. So, if the client's courseNames are "AB01,AB02,AB03", and the courseId of the enrolment is 2, then the student is in AB03.

Is there a way that I can do a single select on these tables that includes the course name? Keep in mind that there will be students from different clients (and hence have different course names, not all of which are sequential,eg: "NW01,NW03")

Basically, if I could split that field and return a single element from the resulting array, that would be what I'm looking for. Here's what I mean in magical pseudocode:

```<code>SELECT e.`studentId`, SPLIT(",", c.`courseNames`)[e.`courseId`]
FROM ...
</code>```

OwnerDisplayName: nickf

Body:
I have to create a report on some student completions. The students each belong to one client. Here are the tables (simplified for this question).

CREATE TABLE  `clients` (
  `clientId` int(10) unsigned NOT NULL auto_increment,
  `clientName` varchar(100) NOT NULL default '',
  `courseNames` varchar(255) NOT NULL default ''
)

The courseNames field holds a comma-delimited string of course names, eg "AB01,AB02,AB03"

CREATE TABLE  `clientenrols` (
  `clientEnrolId` int(10) unsigned NOT NULL auto_increment,
  `studentId` int(10) unsigned NOT NULL default '0',
  `courseId` tinyint(3) unsigned NOT NULL default '0'
)

The courseId field here is the index of the course name in the clients.courseNames field. So, if the client's courseNames are "AB01,AB02,AB03", and the courseId of the enrolment is 2, then the student is in AB03.

Is there a way that I can do a single select on these tables that includes the course name? Keep in mind that there will be students from different clients (and hence have different course names, not all of which are sequential,eg: "NW01,NW03")

Basically, if I could split that field and return a single element from the resulting array, that would be what I'm looking for. Here's what I mean in magical pseudocode:

SELECT e.`studentId`, SPLIT(",", c.`courseNames`)[e.`courseId`]
FROM ...

Body:
MySQL's only string-splitting function is SUBSTRING_INDEX(str, delim, count). You can use this, to, for example:

Return the item before the first separator in a string:

mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', 1);
+--------------------------------------------+
| SUBSTRING_INDEX('foo#bar#baz#qux', '#', 1) |
+--------------------------------------------+
| foo                                        |
+--------------------------------------------+
1 row in set (0.00 sec)

Return the item after the last separator in a string:

mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', -1);
+---------------------------------------------+
| SUBSTRING_INDEX('foo#bar#baz#qux', '#', -1) |
+---------------------------------------------+
| qux                                         |
+---------------------------------------------+
1 row in set (0.00 sec)

Return everything before the third separator in a string:

mysql> SELECT SUBSTRING_INDEX('foo#bar#baz#qux', '#', 3);
+--------------------------------------------+
| SUBSTRING_INDEX('foo#bar#baz#qux', '#', 3) |
+--------------------------------------------+
| foo#bar#baz                                |
+--------------------------------------------+
1 row in set (0.00 sec)

Return the second item in a string, by chaining two calls:

mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('foo#bar#baz#qux', '#', 2), '#', -1);
+----------------------------------------------------------------------+
| SUBSTRING_INDEX(SUBSTRING_INDEX('foo#bar#baz#qux', '#', 2), '#', -1) |
+----------------------------------------------------------------------+
| bar                                                                  |
+----------------------------------------------------------------------+
1 row in set (0.00 sec)

In general, a simple way to get the nth element of a #-separated string (assuming that you know it definitely has at least n elements) is to do:

SUBSTRING_INDEX(SUBSTRING_INDEX(your_string, '#', n), '#', -1);

The inner SUBSTRING_INDEX call discards the nth separator and everything after it, and then the outer SUBSTRING_INDEX call discards everything except the final element that remains.

If you want a more robust solution that returns NULL if you ask for an element that doesn't exist (for instance, asking for the 5th element of 'a#b#c#d'), then you can count the delimiters using REPLACE and then conditionally return NULL using IF():

IF(
    LENGTH(your_string) - LENGTH(REPLACE(your_string, '#', '')) / LENGTH('#') < n - 1,
    NULL,
    SUBSTRING_INDEX(SUBSTRING_INDEX(your_string, '#', n), '#', -1)
)

Of course, this is pretty ugly and hard to understand! So you might want to wrap it in a function:

CREATE FUNCTION split(string TEXT, delimiter TEXT, n INT)
RETURNS TEXT DETERMINISTIC
RETURN IF(
    (LENGTH(string) - LENGTH(REPLACE(string, delimiter, ''))) / LENGTH(delimiter) < n - 1,
    NULL,
    SUBSTRING_INDEX(SUBSTRING_INDEX(string, delimiter, n), delimiter, -1)
);

You can then use the function like this:

mysql> SELECT SPLIT('foo,bar,baz,qux', ',', 3);
+----------------------------------+
| SPLIT('foo,bar,baz,qux', ',', 3) |
+----------------------------------+
| baz                              |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SPLIT('foo,bar,baz,qux', ',', 5);
+----------------------------------+
| SPLIT('foo,bar,baz,qux', ',', 5) |
+----------------------------------+
| NULL                             |
+----------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SPLIT('foo###bar###baz###qux', '###', 2);
+------------------------------------------+
| SPLIT('foo###bar###baz###qux', '###', 2) |
+------------------------------------------+
| bar                                      |
+------------------------------------------+
1 row in set (0.00 sec)


问:
what should be the value of referer in curl_setopt in php when we are communicating with the google's search api with our own localhost server?
what should be the value of referer in curl_setopt in php when we are communicating with the google's search api with our own localhost server?
curl_setopt($ch, CURLOPT_REFERER, $referer);
usually we are placing our sitename as 3'rd parameter.But what we want to put when we are running this in our local server?
im using apche in ubuntu.</p>

答: Why do you even care about referrer? This is totally unnecessary to set any value. The only valid reason to set referrer is when you know that program requires it and will not work without a valid referrer. The other reason people set referrer in curl is when they want to scrape web page or do other sneaky things where they trying to hide the fact that they are not accessing the page with a regular browser.</p>