问:
Shorter way to test range for a certain string
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

```<code>Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub
</code>```

答:
Based on what brettdj has suggested, you can use the proposed code like below...

```<code>Sub ExportToPDF()
    Dim file_path As String
    Dim search_range As String
    Dim each_cell As Range
    Dim rng1 As Range
    ' Set search_range as desired search range
    search_range = ActiveSheet.Range("A53:R56")

    Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart)
    If Not rng1 Is Nothing Then
        file_path = Some_path_A
    Else
        file_path = Some_path_B
    End If

    'Export the sheet as PDF
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=file_path, Quality:=xlQualityStandard _
            , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
            True
End Sub
</code>```

Body:
Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub

Body:
Based on what brettdj has suggested, you can use the proposed code like below...

Sub ExportToPDF()
    Dim file_path As String
    Dim search_range As String
    Dim each_cell As Range
    Dim rng1 As Range
    ' Set search_range as desired search range
    search_range = ActiveSheet.Range("A53:R56")

    Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart)
    If Not rng1 Is Nothing Then
        file_path = Some_path_A
    Else
        file_path = Some_path_B
    End If

    'Export the sheet as PDF
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=file_path, Quality:=xlQualityStandard _
            , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
            True
End Sub


来源: stackexchange

问:
Import from github to android studio
Hey I am trying to build an android application regarding google adsense.
I want to import the android sample.
https://github.com/Ishaan-Kumar/googleads-adsense-examples

Since I am only interested in android I want to import only this.
https://github.com/Ishaan-Kumar/googleads-adsense-examples/tree/master/android

I tried to import via VCS in android studio by url https://github.com/Ishaan-Kumar/googleads-adsense-examples.git

But it imported the whole project including all the platforms(PHP,dontnet,ruby).
The thing is I want the android only plus the android files are not detected (I think there is not gradle file in here)

How do I overcome this problem?

答:
Step 1: Download Zip. Don't Fork the project or use git command or VCS in android studio.

Step 2: Open Android Studio->New Project->Open->Select android directory.

Step 3: Android Studio tells you this is a eclipse project (Convert it to gradle blah blah). Hit Next. This is the time I came to know this is an eclipse project and why android studio is not detecting it.

Step 4: Done.

PS: Thanks to comments(Comment Author has deleted his comment).

ContentLicense: CC BY-SA 3.0

Title: Import from github to android studio


问:
Handle Ajax Auto Suggest Drop List using selenium
I want to enter value to the From field of http://busindia.com/ using the following code

```<code>driver.findElement(By.id("matchFromPlace")).sendKeys("Udupi");
</code>```

while typing udupi in the from input there appears a list of options beneath from which we select to select udupi.

答:
please try below code:</p>

```<code>Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN);
action.sendKeys(Keys.ENTER);
action.perform()
</code>```

Body:
I want to enter value to the From field of http://busindia.com/ using the following code

driver.findElement(By.id("matchFromPlace")).sendKeys("Udupi");

while typing udupi in the from input there appears a list of options beneath from which we select to select udupi.

Body:
please try below code:

Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN);
action.sendKeys(Keys.ENTER);
action.perform()


问:
Running an executable binary made w/ JET Excelsior in Docker
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

```<code>#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]
</code>```

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?

答:
Is "myapp" file exist in WORKDIR directory (WORKDIR/myapp) ?
Now you copy all local root directory (/) to /sandbox container dir.

```<code>COPY ["/", "/sandbox"]
</code>```

if you need/want to copy root directory to container you need use full path of the the "myapp", example:

```<code>ENTRYPOINT /full/path/in/container/to/myapp
</code>```

Or just update the PATH:

```<code>ENV PATH="/full/path/in/container/to/:${PATH}"
</code>```

But maybe best decision would be change COPY command to:

```<code>COPY [".", "/sandbox"]
</code>```

Body:
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?

Body:
Is "myapp" file exist in WORKDIR directory (WORKDIR/myapp) ?
Now you copy all local root directory (/) to /sandbox container dir.

COPY ["/", "/sandbox"]

if you need/want to copy root directory to container you need use full path of the the "myapp", example:

ENTRYPOINT /full/path/in/container/to/myapp

Or just update the PATH:

ENV PATH="/full/path/in/container/to/:${PATH}"

But maybe best decision would be change COPY command to:

COPY [".", "/sandbox"]


问:
How should I structure user login and others in this website I am working on? Please see description
I apologize if the question is not too clear.

As a background, I am working with ExpressJS and MongoDB (with mongoose etc). Also, I am a bit familiar with the topic, but I would like to do this the right way. I also use Handlebars as a view engine.

What I am trying to get at is, how do make it so that the server knows that a user is logged in and sends the right page, navigation bar, and other things?

I worked on a hackathon where I did something like this. Basically, it worked like this. When a user created an account, their informations were saved in a database. Inside the index js, I would check if the password and all matched (they were encrypted with Passport), then it they do, send the page with a parameter logged = true. If they weren't logged in, I would send the page with logged = false. Here's an example for logged out:

```<code>router.get('/', function(req, res, next) {
    res.render('index', {title:'randomtitle', logged=false});
});
</code>```

An example for logged in:

```<code>router.get('/', function(req, res, next) {
// code checks for cookies. Results shows that user exists. So we send this. we also find the username saved in the variable "someuser"
    res.render('index', {title:'randomtitle', logged=true, username: someuser});
});
</code>```

Then, the handlebars page will check if the user is logged in. For example:

```<code><body>
{{if logged}}
    <li> Hello {{username}}! </li>
{{else}}
    <li> LOGIN </li>
{{/if}}
</body>
</code>```

Hopefully, that makes sense. But I think that's a very sketchy approach of doing this! How do professional websites do it? Is there somewhere I can find examples for this?

Also, when I create initialize a server with express for example, it creates 2 routes automatically: index.js and user.js. What is the user.js for?

If anyone knows how it works in general (not specific to Node or Express), also please let me know.

答:
A lot of people use passportjs.org for authentication in express. You have a lot of work to do. basically you can save user info from frontend form (html) to the database with get and post requests then add user info to session. This way at your routes you know who is authenticated. You could send the session to the front end template.

you could check to see if the user object is in the session and if it is that means they are logged in.

passportjs helps out with this a lot.

you could do req.session.logged = true

Body:
I apologize if the question is not too clear.

As a background, I am working with ExpressJS and MongoDB (with mongoose etc). Also, I am a bit familiar with the topic, but I would like to do this the right way. I also use Handlebars as a view engine.

What I am trying to get at is, how do make it so that the server knows that a user is logged in and sends the right page, navigation bar, and other things?

I worked on a hackathon where I did something like this. Basically, it worked like this. When a user created an account, their informations were saved in a database. Inside the index js, I would check if the password and all matched (they were encrypted with Passport), then it they do, send the page with a parameter logged = true. If they weren't logged in, I would send the page with logged = false. Here's an example for logged out:

router.get('/', function(req, res, next) {
    res.render('index', {title:'randomtitle', logged=false});
});

An example for logged in:

router.get('/', function(req, res, next) {
// code checks for cookies. Results shows that user exists. So we send this. we also find the username saved in the variable "someuser"
    res.render('index', {title:'randomtitle', logged=true, username: someuser});
});

Then, the handlebars page will check if the user is logged in. For example:

{{if logged}}

 Hello {{username}}!

{{else}}

 LOGIN

{{/if}}

Hopefully, that makes sense. But I think that's a very sketchy approach of doing this! How do professional websites do it? Is there somewhere I can find examples for this?

Also, when I create initialize a server with express for example, it creates 2 routes automatically: index.js and user.js. What is the user.js for?

If anyone knows how it works in general (not specific to Node or Express), also please let me know.


问:
Web API – authenticate with bearer token
I have created a MVC application for allowing external authentication/registration. It has been created with all the necessary components (Owin, EF, register, login, logout) and I am able to perform all the basic activities in the application.

Now, I want to integrate the web application with the Web API which is going to be used by my mobile app too. I stuck in the authentication in the Web API calls (with the bearer token I received from the web application).

I saw examples to create WEB API projects with OWIN middleware enabled. But i dont know how to centralize the external authentication process and use the token for both my web application and the mobile application
And I don't want to go for the ANGULAR or Single page application.
Can anyone suggest me the right technical path to fix this issue.
Thank you.

Step 1:

I created a MVC project in visual studio 2015 with Individual Login Enabled. And configured the Keys that i configured everything in the google developer console. My Startup.cs will have the following code

```<code> public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
</code>```

Step 2:

Changed the webconfig file to point my local DB and run the app, i am able to successfully login through google with my gmail account and user details are added to ASPUSerTables in the DB successfully

Step 3:

Now I wanted to create a WEB API Project which will be connected to the DB and retrive some data to the MVC web application and Mobile application (I am stuck on authentication part  here). I need to use third party authentication to my mobile app too (Xamarin) and use the common API from my mobile app and MVC website

Step 4
So I thought, Instead of WEB application (Step 1), I should have created WEB API Project which will look like below to return the auth token in Startup.cs and store that cookie in the website to pass in the subsequent requests.

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };
</code>```

I don't want to go with ANGULAR and I need my WebApplication(MVC) and WEB API project Authenticates properly for all the requests. Please advise me the
right path.
Thanks

答:
What you need to do is follow these steps

Create a Web API project with Individual User Accounts Authentication.

Now, you will have all ready to use API's for Register, change password, as well as API endpoint to generate token for a user.

Create another project but this time it is MVC with No Authentication in same solution.

well this will be our architecture

This is API controller

```<code>[Authorize]
public class ValuesController : ApiController
{
      [HttpGet]
      public IEnumerable<string> Get()
      {
         return new string[] { "values1", "values2" };
      }
}
</code>```

This is your MVC controller

```<code>public class MVCValuesController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/api/Values");
     string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);
     }

     public ActionResult GetValues()
     {
         HttpResponseMessage responseMessage = client.Get(url);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync().Result;
             var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}
</code>```

I have not used async here, but you can do it. and also you need to start both of your projects when you run it. right click on solution and click Set Start Up projects then you can select multiple projects and set action as Start.

```<code>public class MVCAccountController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/");
     //string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         // just adding a JObject you can create a class

         JObject tokenJobject = new JObject(
                                        new JProperty("Email", "someone@example.com"),
                                        new JProperty("Password", "Pass123"));
                                        new JProperty("ConfirmPassword", "Pass123"));
            HttpContent baseContent = new StringContent(tokenJobject.ToString(), Encoding.UTF8, "application/json");
        //client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);

     }

     public async Task<ActionResult> GetValues()
     {
         string requestUri = string.Format("api/Account/Register");
         HttpResponseMessage responseMessage = await client.PostAsync(requestUri, baseContent);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync();
             var jsonResponse = JsonConvert.DeserializeObject<string>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a MVC application for allowing external authentication/registration. It has been created with all the necessary components (Owin, EF, register, login, logout) and I am able to perform all the basic activities in the application.

Now, I want to integrate the web application with the Web API which is going to be used by my mobile app too. I stuck in the authentication in the Web API calls (with the bearer token I received from the web application).

I saw examples to create WEB API projects with OWIN middleware enabled. But i dont know how to centralize the external authentication process and use the token for both my web application and the mobile application
And I don't want to go for the ANGULAR or Single page application.
Can anyone suggest me the right technical path to fix this issue.
Thank you.

Step 1:

I created a MVC project in visual studio 2015 with Individual Login Enabled. And configured the Keys that i configured everything in the google developer console. My Startup.cs will have the following code

 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

Step 2:

Changed the webconfig file to point my local DB and run the app, i am able to successfully login through google with my gmail account and user details are added to ASPUSerTables in the DB successfully

Step 3:

Now I wanted to create a WEB API Project which will be connected to the DB and retrive some data to the MVC web application and Mobile application (I am stuck on authentication part  here). I need to use third party authentication to my mobile app too (Xamarin) and use the common API from my mobile app and MVC website

Step 4
So I thought, Instead of WEB application (Step 1), I should have created WEB API Project which will look like below to return the auth token in Startup.cs and store that cookie in the website to pass in the subsequent requests.

app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

I don't want to go with ANGULAR and I need my WebApplication(MVC) and WEB API project Authenticates properly for all the requests. Please advise me the
right path.
Thanks

Body:
What you need to do is follow these steps

Create a Web API project with Individual User Accounts Authentication.

Now, you will have all ready to use API's for Register, change password, as well as API endpoint to generate token for a user.

Create another project but this time it is MVC with No Authentication in same solution.

well this will be our architecture

This is API controller

[Authorize]
public class ValuesController : ApiController
{
      [HttpGet]
      public IEnumerable<string> Get()
      {
         return new string[] { "values1", "values2" };
      }
}

This is your MVC controller

public class MVCValuesController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/api/Values");
     string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);
     }

     public ActionResult GetValues()
     {
         HttpResponseMessage responseMessage = client.Get(url);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync().Result;
             var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}

I have not used async here, but you can do it. and also you need to start both of your projects when you run it. right click on solution and click Set Start Up projects then you can select multiple projects and set action as Start.

public class MVCAccountController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/");
     //string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         // just adding a JObject you can create a class

         JObject tokenJobject = new JObject(
                                        new JProperty("Email", "someone@example.com"),
                                        new JProperty("Password", "Pass123"));
                                        new JProperty("ConfirmPassword", "Pass123"));
            HttpContent baseContent = new StringContent(tokenJobject.ToString(), Encoding.UTF8, "application/json");
        //client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);

     }

     public async Task<ActionResult> GetValues()
     {
         string requestUri = string.Format("api/Account/Register");
         HttpResponseMessage responseMessage = await client.PostAsync(requestUri, baseContent);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync();
             var jsonResponse = JsonConvert.DeserializeObject<string>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}


问:
How to bind the json output from SOAP web service to UItableView using Objective C?
I got an following output from SOAP service. How can I bind it in UItableView using Objective-C (iOS).?

My code is:

```<code>-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{

//converting values to array
NSArray *value = [_data valueForKey:@"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@",json);
</code>```

}

Output:

```<code>2017-04-04 11:39:26.499 SoapService[16524:545663] (
    {
    firstName = "1 Jhon";
    lastName = Macay;
},
    {
    firstName = "2 William";
    lastName = Proter;
},
    {
    firstName = "3 Joe";
    lastName = Root;
},
    {
    firstName = "4 Brendon";
    lastName = Haejoy;
},
    {
    firstName = "5 Jhon";
    lastName = Snow;
},
    {
    firstName = "6 Theon";
    lastName = Greyjoy;
}
</code>```

)

How can I bind the above output to a tableView?

答: This looks like JSON. You can use NSJSONSerialization to convert it into Cocoa objects like instances of NSArray, NSDictionary, NSString, and so on. Then you take the usual way to fill a table view with it.

Body:
I got an following output from SOAP service. How can I bind it in UItableView using Objective-C (iOS).?

My code is:

-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{

//converting values to array
NSArray *value = [_data valueForKey:@"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@",json);

}

Output:

2017-04-04 11:39:26.499 SoapService[16524:545663] (
    {
    firstName = "1 Jhon";
    lastName = Macay;
},
    {
    firstName = "2 William";
    lastName = Proter;
},
    {
    firstName = "3 Joe";
    lastName = Root;
},
    {
    firstName = "4 Brendon";
    lastName = Haejoy;
},
    {
    firstName = "5 Jhon";
    lastName = Snow;
},
    {
    firstName = "6 Theon";
    lastName = Greyjoy;
}

)

How can I bind the above output to a tableView?


问:
MERN React/Redux/MongoDB solid isomorphic boilerplate with authentication
I have a task to build a boilerplate for our future web applications using ReactJS/Redux/MongoDB/Node (MERN) as a basic technology stack.

Basically all of our web applications are dashboards, with a login landing page (with register/login/forgot pwd/reset pwd). The boilerplate should be driven by microservices and needs to support both web and mobile integration (using ReactJS Native). Both client and server will call my APIs, that needs to be available also as REST services for integration. The app should be isomorphic as a best practice today.

I decided to start from react-redux-universal-hot-example, but as we can see the its landing page, it may be outdated (was written in June 2015).

The basic structure of my project is being tought as the following modules:

api: The API services (REST)
auth: To handle authentication
server: Server
client: client
models: Mongo models and database access
static: Static files (images, etc.)

These are the modules I'm planning to use (mainly from react-redux-universal-hot-example):

React (basic)

React Router (to route)

Express (basic)

Babel (basic)

Webpack (basic)

Webpack Dev Middleware (for development)

Webpack Hot Middleware (for development)

Redux (for data update)

Redux Dev Tools (for development)

React Router Redux Redux/React Router bindings.

ESLint (for code styling)

redux-form (to help with forms)

lru-memoize (to form validation)

multireducer (to build a key based reducer)

style-loader  (to work with css and sass)

bootstrap-sass-loader (to easily customize bootstrap colors)

font-awesome-webpack (to easily customize fa colors)

react-helmet (to manage meta tags)

webpack-isomorphic-tools (for isomorphic app)

mocha (for unit testing)

Not present in the react-redux-universal-hot-example, I would addÇ

mongoose (for Mongo access)

Auth0, JWT and passport (for authentication)

From the above path, I have the following doubts:

a) Are the modules listed above updated as for today ? Should I use something newer to the given list ?

b) Is react-redux-universal-hot-example a good starting point or shall I look for something newer, better organized or just more up to date ?

c) Is my modules/directories structure correct ? Any comments on that ?

d) Generally speaking, is this a solid base to start from ?

b) Is there something missing that would help

答:
check out:

https://github.com/bertho-zero/react-redux-universal-hot-example#server-side-data-fetching

This is an updated fork. It has a lot of things that you want, and more. I am using it myself and I am mighty impressed.


问:
how to add background music
The duplicate answer does not works at all

```<code>import Cocoa
    import AVFoundation

    var error: NSError?

    println("Hello, Audio!")
    var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
    var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
    if midi == nil {
        if let e = error {
            println("AVMIDIPlayer failed: " + e.localizedDescription)
        }
    }
    midi.play(nil)
    while midi.playing {
        // Spin (yeah, that's bad!)
    }
</code>```

答:
I've made a couple of changes to your code but this seems to "work" (we'll get to that)

First off, import the MP3 file to your playground as described in this answer

Then you can use your file like so:

```<code>import UIKit
import AVFoundation

print("Hello, Audio!")
if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
    do {
        let midi = try AVMIDIPlayer(contentsOf: url, soundBankURL: nil)
        midi.play(nil)
        while midi.isPlaying {
            // Spin (yeah, that's bad!)
        }
    } catch (let error) {
        print("AVMIDIPlayer failed: " + error.localizedDescription)
    }
}
</code>```

Notice:

printinstead of println

In Swift 3 a lot of things was renamed and some of the "old" methods that took an &error parameter was changed to use do try catch instead. Therefore the error has gone from your call and has been replaced with a try.

The above will fail! You will see error code -10870 which can be found in the AUComponent.h header file and which translates to:

kAudioUnitErr_UnknownFileType

If an audio unit uses external files as a data source, this error is returned

if a file is invalid (Apple's DLS synth returns this error)

So...this leads me to thinking you need to do one of two things, either:

find a .midi file and use that with the AVMidiPlayer

find something else to play your file, for instance AVFilePlayer or AVAudioEngine

(you can read more about error handling in Swift here).

Hope that helps you.

Title: how to add background music

Body:
The duplicate answer does not works at all

import Cocoa
    import AVFoundation

    var error: NSError?

    println("Hello, Audio!")
    var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
    var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
    if midi == nil {
        if let e = error {
            println("AVMIDIPlayer failed: " + e.localizedDescription)
        }
    }
    midi.play(nil)
    while midi.playing {
        // Spin (yeah, that's bad!)
    }

Body:
I've made a couple of changes to your code but this seems to "work" (we'll get to that)

First off, import the MP3 file to your playground as described in this answer

Then you can use your file like so:

import UIKit
import AVFoundation

print("Hello, Audio!")
if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
    do {
        let midi = try AVMIDIPlayer(contentsOf: url, soundBankURL: nil)
        midi.play(nil)
        while midi.isPlaying {
            // Spin (yeah, that's bad!)
        }
    } catch (let error) {
        print("AVMIDIPlayer failed: " + error.localizedDescription)
    }
}

Notice:

printinstead of println

In Swift 3 a lot of things was renamed and some of the "old" methods that took an &error parameter was changed to use do try catch instead. Therefore the error has gone from your call and has been replaced with a try.

The above will fail! You will see error code -10870 which can be found in the AUComponent.h header file and which translates to:

kAudioUnitErr_UnknownFileType

If an audio unit uses external files as a data source, this error is returned

if a file is invalid (Apple's DLS synth returns this error)

So...this leads me to thinking you need to do one of two things, either:

find a .midi file and use that with the AVMidiPlayer

find something else to play your file, for instance AVFilePlayer or AVAudioEngine

(you can read more about error handling in Swift here).

Hope that helps you.


问:
how to convert json object into class object
How to convert this json clsError and userId values:

```<code>String temp = "{"clsError":{"ErrorCode":110,"ErrorDescription":" Request Added"},"UserID":36}"
</code>```

And pass them as parameters:

```<code>clsError errorObject=new clsError(UserID,clsError);
</code>```

答:
First use this: http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)

```<code>JSONObject tempJson = new JSONObject(temp);
JSONObject clsErrorJson = tempJson.getJSONObject("clsError");
clsError errorObject = new clsError(tempJson.getString("UserID"),
                                    clsErrorJson.getInt("clsError") + ": "
                                    + clsErrorJson.getString("ErrorDescription"));
</code>```

that is basically it. but i was not sure about the second parameter of the clsError constructor. i just assumed it is a string in my example :) but this should give you the idea how to do this. and you will have to surround that with try/catch. eclipse will tell you how :)

Body:
How to convert this json clsError and userId values:

String temp = "{"clsError":{"ErrorCode":110,"ErrorDescription":" Request Added"},"UserID":36}"

And pass them as parameters:

clsError errorObject=new clsError(UserID,clsError);

Body:
First use this: http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)

JSONObject tempJson = new JSONObject(temp);
JSONObject clsErrorJson = tempJson.getJSONObject("clsError");
clsError errorObject = new clsError(tempJson.getString("UserID"),
                                    clsErrorJson.getInt("clsError") + ": "
                                    + clsErrorJson.getString("ErrorDescription"));

that is basically it. but i was not sure about the second parameter of the clsError constructor. i just assumed it is a string in my example :) but this should give you the idea how to do this. and you will have to surround that with try/catch. eclipse will tell you how :)

ContentLicense: CC BY-SA 2.5


问:
When autocomplete is params returns nil
Doing autocomplete. In controller format.json returns an array of names. from json I take the values for autocomplete. But when I start to enter in the input, then in the logs I have:

```<code>Started GET "/search.json" for 127.0.0.1 at 2017-03-30 09:41:28 +0300
Processing by PagesController#search as JSON
   (3.1ms)  SELECT "items"."name" FROM "items" WHERE (name LIKE '%%')
Completed 200 OK in 34ms (Views: 19.2ms | ActiveRecord: 3.1ms)
</code>```

The problem is that params[:q] (in controller) is coming up nil.

In controller:

```<code>def search
  @words = Item.where("name LIKE '%#{params[:q]}%'")
  respond_to do |format|
    format.html
    format.json { render json: @words.pluck(:name) }
  end
end
</code>```

JS:

```<code>$(function(){
    $('input[name="q"]').autoComplete({
        minChars: 1,
        source: function(term, response){
            $.getJSON('/search.json', function (data) {
                term = term.toLowerCase();
                var matches = [];
                for (i = 0; i < data.length; i++)
                    if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
                response(matches.slice(0,5));
            });
        }
    });
});
</code>```

.erb

```<code><input id="hero-demo" autofocus type="text" name="q" style="width:100%;max-width:600px;outline:0">
</code>```

use a plugin autocomplete

P.S. On the client autocomplete is working fine.

答:
Pass term as query param:</p>

```<code>$(function(){
    $('input[name="q"]').autoComplete({
        minChars: 1,
        source: function(term, response) {
            term = term.toLowerCase();
            $.getJSON('/search.json?q='+ term, function (data) {
                var matches = [];
                for (i = 0; i < data.length; i++)
                    if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
                response(matches.slice(0,5));
            });
        }
    });
});
</code>```

Title: When autocomplete is params returns nil

Body:
Doing autocomplete. In controller format.json returns an array of names. from json I take the values for autocomplete. But when I start to enter in the input, then in the logs I have:

Started GET "/search.json" for 127.0.0.1 at 2017-03-30 09:41:28 +0300
Processing by PagesController#search as JSON
   (3.1ms)  SELECT "items"."name" FROM "items" WHERE (name LIKE '%%')
Completed 200 OK in 34ms (Views: 19.2ms | ActiveRecord: 3.1ms)

The problem is that params[:q] (in controller) is coming up nil.

In controller:

def search
  @words = Item.where("name LIKE '%#{params[:q]}%'")
  respond_to do |format|
    format.html
    format.json { render json: @words.pluck(:name) }
  end
end

JS:

$(function(){
    $('input[name="q"]').autoComplete({
        minChars: 1,
        source: function(term, response){
            $.getJSON('/search.json', function (data) {
                term = term.toLowerCase();
                var matches = [];
                for (i = 0; i < data.length; i++)
                    if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
                response(matches.slice(0,5));
            });
        }
    });
});

.erb

<input id="hero-demo" autofocus type="text" name="q" style="width:100%;max-width:600px;outline:0">

use a plugin autocomplete

P.S. On the client autocomplete is working fine.

Body:
Pass term as query param:

$(function(){
    $('input[name="q"]').autoComplete({
        minChars: 1,
        source: function(term, response) {
            term = term.toLowerCase();
            $.getJSON('/search.json?q='+ term, function (data) {
                var matches = [];
                for (i = 0; i < data.length; i++)
                    if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
                response(matches.slice(0,5));
            });
        }
    });
});


问:
Is it save to store server response in SharedPreferences
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

```<code>private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}
</code>```

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.

答:
My question is whether the response will be lost in Shared Preferences

Shared preferences won't be removed/lost, unless:

you remove them

user clears app data

So, you are safe to store there necessary data.

Body:
I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method

   parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));
works properly first time when directly from server but when we use this method in another it does not work.


问:
converting elements of a list to string
I would like to obtain the string text of the elements stored in a list, say List<Car>. Would the toArray() and the toString() methods be the best options?

答:
You can use Java 8 Streams

```<code>List<Car> carList = new ArrayList<>();
//Add some elemts to carList
carList.stream()
.map(Car::toString) // maps Car Object to a value returned by toString method
.collect(Collectors.joining(","));
</code>```

Refer JavaDoc about Collectors for more info.

Title: converting elements of a list to string

Body:
You can use Java 8 Streams

List<Car> carList = new ArrayList<>();
//Add some elemts to carList
carList.stream()
.map(Car::toString) // maps Car Object to a value returned by toString method
.collect(Collectors.joining(","));

Refer JavaDoc about Collectors for more info.


问:
Editing properties of an SKSpriteNode custom class?
In my custom SKSpriteNode class, I want to be able to change properties such as anchorPoint, posistion, etc. within the custom class so I don't need to elsewhere.

```<code>import Foundation
import SpriteKit

open class Crank:SKSpriteNode {

init() {
    super.init(texture: SKTexture(imageNamed: "crank"), color:
        NSColor.white, size: CGSize(width: 155.0, height: 188.0))

    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

How would I edit other properties?

答:
```<code>import Foundation
import SpriteKit

class Crank: SKSpriteNode {

    init(imageNamed image: String, position at: CGPoint, withAnchor anchor: CGPoint) {

        super.init(imageNamed: image)
        self.position = position
        self.anchorPoint = anchor
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

(Written from memory, so may contain small errors, but is broadly correct).

and then in your main code:

```<code>let myCrank = Crank(imageNamed: "Crank.png", at: CGPoint(300, 500), withAnchor: CGpointZero)
</code>```

My answer notwithstanding, Alessandro has a point. I think that it's better to set 'standard' properties in the normal place.

If you are going to set any of the standard SKSpriteNode properties inside the actual class, then I think specifying them in an initialiser is good practice as it makes the m more visible,. Debugging a program where you don't appears to set a node's position, or texture etc. would be problematic.

Body:
In my custom SKSpriteNode class, I want to be able to change properties such as anchorPoint, posistion, etc. within the custom class so I don't need to elsewhere.

import Foundation
import SpriteKit

open class Crank:SKSpriteNode {

init() {
    super.init(texture: SKTexture(imageNamed: "crank"), color:
        NSColor.white, size: CGSize(width: 155.0, height: 188.0))

    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

How would I edit other properties?

Body:
import Foundation
import SpriteKit

class Crank: SKSpriteNode {

    init(imageNamed image: String, position at: CGPoint, withAnchor anchor: CGPoint) {

        super.init(imageNamed: image)
        self.position = position
        self.anchorPoint = anchor
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

(Written from memory, so may contain small errors, but is broadly correct).

and then in your main code:

let myCrank = Crank(imageNamed: "Crank.png", at: CGPoint(300, 500), withAnchor: CGpointZero)

My answer notwithstanding, Alessandro has a point. I think that it's better to set 'standard' properties in the normal place.

If you are going to set any of the standard SKSpriteNode properties inside the actual class, then I think specifying them in an initialiser is good practice as it makes the m more visible,. Debugging a program where you don't appears to set a node's position, or texture etc. would be problematic.


问:
Environment variable assignment in Docker Compose - colon way
This is the question about docker-compose.yml file syntax. I met the variable assignment like this on the internet:

environment:
    PMA_HOST: mysql
```
<p>http://tech.osteel.me/posts/2017/01/15/how-to-use-docker-for-local-web-development-an-update.html</p>
<hr />
<p>On the other hand the documentation tells like this:</p>
<pre class="lang-yaml prettyprint-override"><code>environment:
  - DEBUG=1
</code>```

https://docs.docker.com/compose/environment-variables/

Is the way without the dash and with the colon proper? What is the difference?

答:
The documentation itself says both methods are working:

You can use either an array or a dictionary.

Now let's forgive Docker for failing to use the proper terminology (an array is actually a sequence in YAML, a dictionary is a mapping) and have a look from the YAML perspective:

A mapping is part of the YAML syntax and therefore parsed by the YAML parser, which enables a syntax-aware editor to do proper highlighting and such. Like the docs say, values like true and false will be converted to a boolean by YAML, so you need to be aware of that. Example from docs:

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:
```
<p>Would we not quote <code>'true'</code>, it would be parsed as a boolean value, which is not what we want.</p>
<p>Using a sequence on the other hand leaves the space of YAML syntax. The sequence itself is YAML, but the values are just parsed as one scalar each. For example, the first scalar value in the sequence here:</p>
<pre class="lang-yaml prettyprint-override"><code>environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET
</code>```

Will be parsed by YAML as RACK_ENV=development. Docker will do post-processing to separate variable name from value. So using this method means that you are using two parsing steps, which makes it more difficult for a syntax-aware editor to properly highlight it. Also, you impose on the user the decision about where to use = and where :, which is not immediately obvious for people who don't know YAML well. It can confuse people.

Looking at escaping, the true does not need to be quoted anymore. This is because it is in the middle of a YAML scalar and therefore is not parsed as standalone value. In fact, quoting it would make YAML treat the quotes as content.

This also means that if you need quoting (for example because you want to use escape sequences), you need to quote the whole scalar. For example, if you want to have a tab character inside your value, it'll look like this:

environment:
  - "MY_VAR=some\tvalue"
```

It will not work if you only quote the part after =. Again, this may be confusing.

Conclusion: For me it seems that using a mapping is more consistent and confuses the user less, and it is therefore preferable. ymmv.

Body:
This is the question about docker-compose.yml file syntax. I met the variable assignment like this on the internet:

environment:
    PMA_HOST: mysql

http://tech.osteel.me/posts/2017/01/15/how-to-use-docker-for-local-web-development-an-update.html

On the other hand the documentation tells like this:

environment:
  - DEBUG=1

https://docs.docker.com/compose/environment-variables/

Is the way without the dash and with the colon proper? What is the difference?

Body:
The documentation itself says both methods are working:

You can use either an array or a dictionary.

Now let's forgive Docker for failing to use the proper terminology (an array is actually a sequence in YAML, a dictionary is a mapping) and have a look from the YAML perspective:

A mapping is part of the YAML syntax and therefore parsed by the YAML parser, which enables a syntax-aware editor to do proper highlighting and such. Like the docs say, values like true and false will be converted to a boolean by YAML, so you need to be aware of that. Example from docs:

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:

Would we not quote 'true', it would be parsed as a boolean value, which is not what we want.

Using a sequence on the other hand leaves the space of YAML syntax. The sequence itself is YAML, but the values are just parsed as one scalar each. For example, the first scalar value in the sequence here:

environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET

Will be parsed by YAML as RACK_ENV=development. Docker will do post-processing to separate variable name from value. So using this method means that you are using two parsing steps, which makes it more difficult for a syntax-aware editor to properly highlight it. Also, you impose on the user the decision about where to use = and where :, which is not immediately obvious for people who don't know YAML well. It can confuse people.

Looking at escaping, the true does not need to be quoted anymore. This is because it is in the middle of a YAML scalar and therefore is not parsed as standalone value. In fact, quoting it would make YAML treat the quotes as content.

This also means that if you need quoting (for example because you want to use escape sequences), you need to quote the whole scalar. For example, if you want to have a tab character inside your value, it'll look like this:

environment:
  - "MY_VAR=some\tvalue"

It will not work if you only quote the part after =. Again, this may be confusing.

Conclusion: For me it seems that using a mapping is more consistent and confuses the user less, and it is therefore preferable. ymmv.


问:
@for loop in Razor
I have a foreach loop @foreach (var t in Model) how I can transfer it to @for loop? And I need browse elements from the end. Example: if I have array {1,2,3} I need display it like   3,2,1

答:
This is a horribly worded question.. but here's a little pity code.

add your own Razor markup as appropriate...

```<code>if ( (null != Model) && (0 < Model.Count) ) {
    for (int index = Model.Count - 1; 0 < index; index--) {
        // show some Model[index] goodness...
    }
}
</code>```

Title: @for loop in Razor

Body:
This is a horribly worded question.. but here's a little pity code.

add your own Razor markup as appropriate...

if ( (null != Model) && (0 < Model.Count) ) {
    for (int index = Model.Count - 1; 0 < index; index--) {
        // show some Model[index] goodness...
    }
}


问:
How to get underlined text from active Word document?
I have a some word documents in an directory. i am developing a code in vb.net for extracting the text succeeding any underlined text from the word documents.

Is there any way to get underlined text from active word document using vb.net.

答:
yes you can use </p>

```<code>pWordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle
</code>```

Body:
yes you can use

pWordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle


问:
Implementing extensible code in C++
I am currently busy with a project where the main focus of the application is to be extensible (allow 3rd party developers to write plugins / their own implementations of interfaces).

Until now, I have been using Java, and built the application on the NetBeans platform. This has works perfectly fine and is quite easy to implement.

However, the program is quite computationally intense, and must be run on a grid of computers. I think C++ might be better suited for massive computations like I need.

What I would like to know. Is there any libraries like the NetBeans platform for C++. Or would I have to implement everything from scratch (not that I mind, I just wat to know)? Also, how easy is it to write extensible code with C++ and implement something like an update center? This is stuff you get for free with the NetBeans platform. My experience with the using the platform is that it allows you to write very modular code, which is something I like. New modules can be installed independantly, while the platform provides discovery of services to find all the installed plugins / impementations.

Can this be done similarly in C++?

Thanks!

答:
For modularity on binary level Boost.Extension might be a good choice.

For autoupdate there is for example Google's Omaha (Windows) or Update Engine (OS X)

Title: Implementing extensible code in C++


问:
Error SQL72014: The variable DatabaseName could not be found - DacPac, SSDT, SqlPackage.exe
I cannot realize what I did wrong and find something in the Internet.

Does anybody knows what the reason for the following deploy stopper?

Possibly this is those numerous settings of DacPac bublishing.

```<code>Error SQL72014: SQL Execution error: A fatal error occurred. The variable DatabaseName could not be found.
Error SQL72045: Script execution error.  The executed script:
USE [$(DatabaseName)];

Error SQL72014: SQL Execution error: A fatal error occurred. Incorrect syntax was encountered while USE [$(DatabaseName)]; was being parsed.
Error SQL72045: Script execution error.  The executed script:
USE [$(DatabaseName)];
</code>```

答:
Set "CommentOutSetVarDeclarations" to false or delete it in XML.

For Visual Studio UI:

Publish Database (PopUp) -> Advanced... (button) -> General (Tab) ->

uncheck the Comment out SetVar declarations

By chance, I clicked on it.

And yet I found it: https://stackoverflow.com/a/15158985/390940 ))

Body:
I cannot realize what I did wrong and find something in the Internet.

Does anybody knows what the reason for the following deploy stopper?

Possibly this is those numerous settings of DacPac bublishing.

Error SQL72014: SQL Execution error: A fatal error occurred. The variable DatabaseName could not be found.
Error SQL72045: Script execution error.  The executed script:
USE [$(DatabaseName)];

Error SQL72014: SQL Execution error: A fatal error occurred. Incorrect syntax was encountered while USE [$(DatabaseName)]; was being parsed.
Error SQL72045: Script execution error.  The executed script:
USE [$(DatabaseName)];


问:
Reset timer on msp430
Using CCS, embededded programming, MSP430F63736A

In my app I´m usingTimer A to switching LED(ON/OFF) for various time.

For example:
Led is ON - 0.5 sec
Led is OFF- 3 sec

I need to reset timer when it reach the value in register TA1CCR0. These times(0.5 s and 3 s) are in the register TA1CCR0. The problem is, that if I change the value of register TA1CCR0 from 0.5 sec to 3 sec, it will count from 0.5 to 3 sec. And I need a full 3 sec so I need a reset timer.

Thats the interrupt routine where I´m switching LED

```<code>    if (P4OUT == 0x00)
    {

        P4OUT ^= BIT6; // LED ON
        TA1CCR0 = (sekunda*t1);  //t1- 3 s.... pc 2s
    }

    else
    {

        P4OUT = 0x00;
        TA1CCR0 = (sekunda*t2);
    }
}
</code>```

答:
In your ISR add an offset to TA1CCR0 and not reset it:

Say you want a 1 sec delay after the first interrupt, and let's say to generate 1 sec delay the timer must count up to 50000. So what you need to do in you ISR is TA1CCR0 +=50000.

In your case:

```<code>if (P4OUT == 0x00)
{

    P4OUT ^= BIT6; // LED ON
    TA1CCR0    +=    (sekunda*t1);  //t1- 3 s.... pc 2s
}

else
{

    P4OUT = 0x00;
    TA1CCR0    +=    (sekunda*t2);
}
</code>```

}

For an a complete example please see

Title: Reset timer on msp430

Body:
Using CCS, embededded programming, MSP430F63736A

In my app I´m usingTimer A to switching LED(ON/OFF) for various time.

For example:
Led is ON - 0.5 sec
Led is OFF- 3 sec

I need to reset timer when it reach the value in register TA1CCR0. These times(0.5 s and 3 s) are in the register TA1CCR0. The problem is, that if I change the value of register TA1CCR0 from 0.5 sec to 3 sec, it will count from 0.5 to 3 sec. And I need a full 3 sec so I need a reset timer.

Thats the interrupt routine where I´m switching LED

    if (P4OUT == 0x00)
    {

        P4OUT ^= BIT6; // LED ON
        TA1CCR0 = (sekunda*t1);  //t1- 3 s.... pc 2s
    }

    else
    {

        P4OUT = 0x00;
        TA1CCR0 = (sekunda*t2);
    }
}

Body:
In your ISR add an offset to TA1CCR0 and not reset it:

Say you want a 1 sec delay after the first interrupt, and let's say to generate 1 sec delay the timer must count up to 50000. So what you need to do in you ISR is TA1CCR0 +=50000.

In your case:

if (P4OUT == 0x00)
{

    P4OUT ^= BIT6; // LED ON
    TA1CCR0    +=    (sekunda*t1);  //t1- 3 s.... pc 2s
}

else
{

    P4OUT = 0x00;
    TA1CCR0    +=    (sekunda*t2);
}

}

For an a complete example please see


问:
Spring crypto invalid key size
I am getting an error I can't explain.

```<code>public static String encrypt(String plain, SaltPasswordPair saltPassword) {
    String password = saltPassword.getPassword();
    String salt = saltPassword.getSalt();

    TextEncryptor encryptor = Encryptors.text(password, salt);
    String encrypted = encryptor.encrypt(plain);

    return encrypted;
}
</code>```

This is my code.
No matter what password length (4, 16, any other) or salt length or whatever value I pass (I also tried 1:1 copy&paste from the examples from here[Stackoverflow] and a few other pages), I get this exception:

```<code>java.lang.IllegalArgumentException: Unable to initialize due to invalid secret key
at org.springframework.security.crypto.encrypt.CipherUtils.initCipher(CipherUtils.java:120)
at org.springframework.security.crypto.encrypt.AesBytesEncryptor.encrypt(AesBytesEncryptor.java:115)
at org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor.encrypt(HexEncodingTextEncryptor.java:36)
at de.thyaris.hydrogen.core.sec.Security.encrypt(Security.java:32)
at de.thyaris.hydrogen.core.sec.SecurityTest.testCryption(SecurityTest.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Caused by: java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
at org.springframework.security.crypto.encrypt.CipherUtils.initCipher(CipherUtils.java:113)
... 27 more
</code>```

Am I missing something?
Crypto version is 4.2.2.RELEASE

EDIT:
Is there a way to fix this without adding external JARs to my JDK directory?

答:
private String cryptKey = "qkjll5@2md3gs5Q@FDFqf";

By default Java supports only 128-bit encryption (128bits == 16Bytes == 16 Chars)

Removing the 128-bit key restriction in Java

Title: Spring crypto invalid key size

Body:
I am getting an error I can't explain.

public static String encrypt(String plain, SaltPasswordPair saltPassword) {
    String password = saltPassword.getPassword();
    String salt = saltPassword.getSalt();

    TextEncryptor encryptor = Encryptors.text(password, salt);
    String encrypted = encryptor.encrypt(plain);

    return encrypted;
}

This is my code.
No matter what password length (4, 16, any other) or salt length or whatever value I pass (I also tried 1:1 copy&paste from the examples from here[Stackoverflow] and a few other pages), I get this exception:

java.lang.IllegalArgumentException: Unable to initialize due to invalid secret key
at org.springframework.security.crypto.encrypt.CipherUtils.initCipher(CipherUtils.java:120)
at org.springframework.security.crypto.encrypt.AesBytesEncryptor.encrypt(AesBytesEncryptor.java:115)
at org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor.encrypt(HexEncodingTextEncryptor.java:36)
at de.thyaris.hydrogen.core.sec.Security.encrypt(Security.java:32)
at de.thyaris.hydrogen.core.sec.SecurityTest.testCryption(SecurityTest.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Caused by: java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
at javax.crypto.Cipher.implInit(Cipher.java:805)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1396)
at javax.crypto.Cipher.init(Cipher.java:1327)
at org.springframework.security.crypto.encrypt.CipherUtils.initCipher(CipherUtils.java:113)
... 27 more

Am I missing something?
Crypto version is 4.2.2.RELEASE

EDIT:
Is there a way to fix this without adding external JARs to my JDK directory?


问:
Unable to resume alarm after reboot android
I need to resume an alarm after reboot. I am saving alarm time in SharedPreferences before reboot and after reboot i am setting an alarm with that time but it doesn't fire at all.
Here is my code for the alarm in my Helpers class:

```<code>public static void scheduleNotification(Notification notification, long delay) {

    Intent notificationIntent = new Intent(AppGlobals.getContext(), AlarmReceiver.class);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(AppGlobals.getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)AppGlobals.getContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    AppGlobals.putAlarmTime(futureInMillis);
    System.out.println("Alarm time before: " + futureInMillis);
}
</code>```

I am using the above code for scheduling an alarm before reboot in another class and it works fine until a reboot.

Here is my AlarmReceiver class code:

```<code>public class AlarmReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);
    Toast.makeText(context, "Alarm!!!", Toast.LENGTH_LONG).show();
}
</code>```

Code for BootStateListener class:

```<code>public class BootStateListenerService extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, AppGlobals.getAlarmTime(), pendingIntent);
        System.out.println("Alarm time after reboot: " + AppGlobals.getAlarmTime());
    }
}
</code>```

AndroidManifest Code:

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:name=".utils.AppGlobals"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".services.LocationService" />
    <receiver android:name=".services.BootStateListenerService"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <receiver android:name=".receivers.AlarmReceiver" />
</application>
</code>```

I am getting the same time after reboot in Logs which means my bootstatelistener class code is also working but it doesn't fire alarm at all.

答:
Can you try this code inside onReceive()

```<code>AlarmManager mgr=
    (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, SomeActivity.class);
PendingIntent pendingIntent =PendingIntent.getService(ctxt, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
                 AppGlobals.getAlarmTime() + 10000, 10000, pendingIntent);
</code>```

Body:
I need to resume an alarm after reboot. I am saving alarm time in SharedPreferences before reboot and after reboot i am setting an alarm with that time but it doesn't fire at all.
Here is my code for the alarm in my Helpers class:

public static void scheduleNotification(Notification notification, long delay) {

    Intent notificationIntent = new Intent(AppGlobals.getContext(), AlarmReceiver.class);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(AlarmReceiver.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(AppGlobals.getContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    long futureInMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager)AppGlobals.getContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
    AppGlobals.putAlarmTime(futureInMillis);
    System.out.println("Alarm time before: " + futureInMillis);
}

I am using the above code for scheduling an alarm before reboot in another class and it works fine until a reboot.

Here is my AlarmReceiver class code:

public class AlarmReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);
    notificationManager.notify(id, notification);
    Toast.makeText(context, "Alarm!!!", Toast.LENGTH_LONG).show();
}

Code for BootStateListener class:

public class BootStateListenerService extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, AppGlobals.getAlarmTime(), pendingIntent);
        System.out.println("Alarm time after reboot: " + AppGlobals.getAlarmTime());
    }
}

AndroidManifest Code:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:name=".utils.AppGlobals"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".services.LocationService" />
    <receiver android:name=".services.BootStateListenerService"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <receiver android:name=".receivers.AlarmReceiver" />
</application>

I am getting the same time after reboot in Logs which means my bootstatelistener class code is also working but it doesn't fire alarm at all.

Body:
Can you try this code inside onReceive()

AlarmManager mgr=
    (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, SomeActivity.class);
PendingIntent pendingIntent =PendingIntent.getService(ctxt, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
                 AppGlobals.getAlarmTime() + 10000, 10000, pendingIntent);


问:
Calculating the current member balance based on transactional data
I have a MySQL table of financial transactions.

The table is like so:

```<code>+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+
</code>```

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.

答:
There is an oversight in ajreal's solution - it doesn't reset the balance variables for different member ids. This version fixes that.

This works (I tested it):

```<code>set @clo:=0, @opn:=0, @mem:=0;
update member_txns
set
  opening=if(status=1, @opn:=if(@mem=(@mem:=member_id), @clo, 0), @clo),
  closing=if(status=1, @clo:=@opn+amount, @clo)
order by member_id, id;
</code>```

Body:
I have a MySQL table of financial transactions.

The table is like so:

+----+-----------+--------+--------+---------+---------+
| id | member_id | status | amount | opening | closing |
+----+-----------+--------+--------+---------+---------+
| 1  | 2         | 1      | 1000   | 0       | 1000    |
| 2  | 2         | 2      | 100    | 1000    | 1000    |
| 3  | 2         | 1      | -20    | 1000    | 980     |
| 4  | 2         | 1      | 10     | 980     | 990     |
+----+-----------+--------+--------+---------+---------+

Currently the opening and closing fields are empty. Status 1 is committed, and 2 is uncommitted.

Can some one please tell me how I would write a query to scan the entire table and update all the opening and closing balances?

There is almost 1,000,000 records in this table so it would be nice if the query was quite optimized. Also this is not going to be needed for real time mission critical data. It would only be the current estimation of the members balance.

Body:
There is an oversight in ajreal's solution - it doesn't reset the balance variables for different member ids. This version fixes that.

This works (I tested it):

set @clo:=0, @opn:=0, @mem:=0;
update member_txns
set
  opening=if(status=1, @opn:=if(@mem=(@mem:=member_id), @clo, 0), @clo),
  closing=if(status=1, @clo:=@opn+amount, @clo)
order by member_id, id;


问:
How do I list block devices in Go?
I want to get the data shown by lsblk command in Linux 64-bit systems. Obviously I can call lsblk and parse the output. My question is if there is a better way to do this in Go?

Thanks.

答:
Since lsblk is already available and already does what you want (gathering information from the system and synthesizing that information into the form you want), I'd think using it would be the best way.

The lsblk source code is here: https://github.com/karelzak/util-linux/blob/master/misc-utils/lsblk.c.  At first glance, personally, this seems nontrivial to replicate in Go, and probably worth the hassle of parsing output and testing for breakage when the util-linux package is updated.

That's ultimately a decision that has to be made for your individual project based on your particular criteria.

Title: How do I list block devices in Go?


问:
Is it ok to still use tables?

Possible Duplicate:

  Why not use tables for layout in HTML?

Just wondering, I thought I have read before that it is bad to use tables, so my question is, is it still acceptable to use tables in development?

答: If you're presenting tabular data, it's fine to use tables. If you're doing layout, it's usually easier and lighter to use a few divs (and use a CSS framework like YUI or Blueprint) to do your work. </p>

Title: Is it ok to still use tables?


Title: @for loop in Razor

Body: I have a foreach loop @foreach (var t in Model) how I can transfer it to @for loop? And I need browse elements from the end. Example: if I have array {1,2,3} I need display it like   3,2,1

Body:
    for(var i = Model.length-1; i >= 0 ; i--) {
        ...
    }