Q: NetworkAvailability check returns false yet the phone is online I have am having some issues with getting consistent results when checking if the network is available or not.
I use this code snippet inside a class AppPreferences to check the availability of a network.
/**
     * @return the networkAvailable
     */
    public boolean isNetworkAvailable() {
        connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        networkAvailable = connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isConnected();
        return networkAvailable;
    }

Before each run I set the context as below:
timer.scheduleAtFixedRate(

                new TimerTask() {

                    public void run() {

                        appPreferences.setContext(getBaseContext());

                        if (appPreferences.isNetworkAvailable()){

                            // perform task

                        }

                    }
                },
                0,
                UPDATE_INTERVAL);

I do know it is not tied to the background thread as I have a onReceive call doing the same logic and still this check fails.
It seems to predominantly happen when it moves between a cellular data connection and to wifi, or vice versa. The Context in which it was started seems to stay even though I update it.
Does anyone have any idea what could be the issue here?

A: It seems as if the active network info will stay on the state of when the Context of the Service/Activity/Receiver is started. Hence if you start it on a network, and then later disconnect from that (i.e. moves from 3G to Wifi and disconnect the 3G connection) it will stay on the first active connection making the app believe the phone is offline even though it is not.
It seems to me that the best solution is to user getApplicationContext instead as that will not be tied to when you started the particular "task".
Update: Related is that if you run applications on Androids (in particular Nexus One) for a long period of time when connected to Wifi do check that you make sure you do not let the Wifi sleep when the screen sleeps. You will be able to set that at the Advanced option under Wireless Networks.


Q: Yii2: can't create sql command using innerJoin I am not that good at SQL but i do as much as i can for the little knowledge i have..
I have made a single a flat SQL string with the help from a friend that gathers data from a table using a relative table from an initial data from the first table, the SQL was made like this:
SELECT id, username, auth_assignment.created_at
FROM `user` JOIN `auth_assignment`
ON (user.id = auth_assignment.user_id)
JOIN `auth_item`
ON (auth_item.name = auth_assignment.item_name)
WHERE auth_item.name = 'Admin'

the initial data to look is Admin so everything works in that side, but i tried to simulate this SQL using Yii2 functions.. so far i have made this code
$query = new Query;

$command = $query->select('id, username')
    ->innerJoin('auth_assignment', ['user.id'=>'auth_assignment.user_id'])
    ->innerJoin('auth_item', ['auth_item.name'=>'auth_assignment.item_name'])
    ->where('auth_item.name = :name', [':name'=>$name])->createCommand();

var_dump($command->query());

this returns an SQLSTATE error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN `auth_assignment` ON `user`.`id`='auth_assignment.user_id' INNER JOIN' at line 1
The SQL being executed was: SELECT `id`, `username` INNER JOIN `auth_assignment` ON `user`.`id`='auth_assignment.user_id' INNER JOIN `auth_item` ON `auth_item`.`name`='auth_assignment.item_name' WHERE auth_item.name = 'Admin'

i checked the method $command->sql; to know how the SQL was being generated.. but i really don't know how to fix it due to my lack of my knowledge to SQL and lack of understanding to yii2 api documentation
SQL is generated like this:
SELECT `id`, `username` INNER JOIN `auth_assignment` ON `user`.`id`=:qp1 INNER JOIN `auth_item` ON `auth_item`.`name`=:qp2 WHERE auth_item.name = :name

i appreciate any help

A: Try This Query
$query = (new yii\db\Query())
         ->select('id, username, auth_assignment.created_at')
         ->from('user')
         ->innerJoin('auth_assignment','user.id=auth_assignment.user_id')
         ->innerJoin('auth_item','auth_item.name = auth_assignment.item_name')
         ->where([
               'auth_item.name' => 'Admin'
         ])->all();


Q: Automatic OpenAPI generation in Spring with multipart requests I have a problem with the OpenAPI generator in a spring boot application generating the definition of a REST endpoint that accepts a multipart request.
When I am explicitly defining the parts like shown below. It generates an OpenAPI definition that is working/valid when used in for example in Azure API Management.
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public List<String> upload(@RequestPart MultipartFile file, @RequestPart UploadMetaData data) {

  . . .

}

paths:
  /api/v1/upload:
    post:
      operationId: upload
      requestBody:
        content:
          multipart/form-data:
            schema:
              required:
              - data
              - file
              type: object
              properties:
                gatewayId:
                  type: string
                file:
                  type: string
                  format: binary
                data:
                  $ref: '#/components/schemas/UploadMetaData'
      responses:
        "200":
          description: OK
          content:
            '*/*':
              schema:
                type: array
                items:
                  type: string

But when I am trying to use MultipartRequest instead of the annotated -File, the controller itself is still working as expected accepting an arbitrary list of multipart segments when I call it directly, but the OpenAPI definition that is generated is not reflecting the actual interface because it is trying to use the request parameter as an URL path parameter, so when I import this spec into Azure API Management it is not working.
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public List<String> upload(MultipartRequest request) {

  . . .

}

paths:
  /api/v1/upload:
  post:
    operationId: upload
    parameters:
    - name: request
      in: query
      required: true
      schema:
        $ref: '#/components/schemas/MultipartRequest'
    requestBody:
      content:
        multipart/form-data:
          schema:
            type: string
    responses:
      "200":
        description: OK
        content:
          '*/*':
            schema:
              type: array
              items:
                type: string

Other than giving my API a name, I didn't configure anything special for the generator:
@OpenAPIDefinition(info = @Info(title = "My REST API", version = "1.0"))
public class MySpringApplication {

. . .

}

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.5.12</version>
</dependency>

Is this a bug or am I missing some annotation or other configuration here?

A: The MultipartRequest, is not supported out of the box.
You can use the following code to enable the support.
static{
    SpringDocUtils.getConfig().addFileType(MultipartRequest.class);
}

This support will be added for the future release.


Q: What is the optimal strategy in a game where players subtract 7 or add or divide by 2? I made up a nim type game where players start with a relatively high number and then for each turn if the number is odd, the player either subtracts 7 from the number or alternately if the number is even divides by 2 or if the number is odd adds 2. The player may not choose a negative number, though. The player to reach 7 wins.
Example: if the number is 11 the player may either subtract 7 to get 4 or add 2 to get 13. If the number is 16 the player may subtract 7 to get 9 or divide by 2 to get 8.
Example game:
The players start with 18
Player 1: 18/2=9
Player 2: 9+2=11
Player 1: 11-7=4
Player 2: 4/2=2
Player 1: 2/2=1
Player 2: 1+2=3
Player 1: 3+2=5
Player 2: 5+2=7
Player 2 wins.
How can we predict whether at any large number the player with the move is in a winning or losing position? Is it possible that for numbers over a certain limit the best strategy for both players will be to always add 2 to keep from losing?
Winning and losing numbers for 1-100:
1 Losing
2 Winning
3 Winning
4 Losing
5 Losing
6 Losing
7 Winning
8 Winning
9 Losing
10 Winning
11 Winning
12 Winning
13 Winning
14 Losing
15 Losing
16 Winning
17 Winning
18 Winning
19 Losing
20 Losing
21 Winning
22 Winning
23 Winning
24 Losing
25 Losing
26 Winning
27 Winning
28 Winning
29 Losing
30 Winning
31 Winning
32 Winning
33 Winning
34 Losing
35 Losing
36 Winning
37 Winning
38 Winning
39 Losing
40 Winning
41 Winning
42 Winning
43 Winning
44 Losing
45 Losing
46 Winning
47 Winning
48 Winning
49 Losing
50 Winning
51 Winning
52 Winning
53 Winning
54 Losing
55 Losing
56 Winning
57 Winning
58 Winning
59 Losing
60 Losing
61 Winning
62 Winning
63 Winning
64 Losing
65 Losing
66 Winning
67 Winning
68 Winning
69 Losing
70 Winning
71 Winning
72 Winning
73 Winning
74 Losing
75 Losing
76 Winning
77 Winning
78 Winning
79 Losing
80 Losing
81 Winning
82 Winning
83 Winning
84 Losing
85 Losing
86 Winning
87 Winning
88 Winning
89 Losing
90 Winning
91 Winning
92 Winning
93 Winning
94 Losing
95 Losing
96 Winning
97 Winning
98 Winning
99 Losing
100 Losing

A: Lemma $1.1$: A player loses if $N \in \{2,3,7,8\}$ directly before he/she has to make a move.
The proof is left as an exercise to the reader.
Lemma $1.2$: Let the starting $N$ be congruent to $0$, $1$, $4$, $5$, $6$, or $9$ (mod $10$) and suppose player A starts the game.
Then if player A follows the below strategy $N$ will always be congruent to $0$, $1$, $4$, $5$, $6$, or $9$ (mod $10$) before he/she moves and $N$ will always be congruent to $2$, $3$, $7$, or $8$ (mod $10$) after he/she moves.
$$\begin{array}{c|c|c|}
N \text{ % } 10 & \text{Move} \\ \hline
0 & -7 \\ \hline
1 & +2 \\ \hline
4 & \cdot \frac{1}{2} \\ \hline
5 & +2 \text{ if } N=5, -7 \text{ otherwise} \\ \hline
6 & \cdot \frac{1}{2} \\ \hline
9 & -7 \\ \hline
\end{array}$$
Note that moving from $0$ to $-7$ is not a legal move. However $N$ will never be $0$ because the only non-zero numbers to reach $0$ from are $-2$ and $7$.
Proof: Let $N_k$ be the value of $N$ before a player moves and $N_{k+1}$ the value of $N$ after that player moves.
Consider the following table of congruence classes (mod $10$) of $N_{k+1}$ for each of the ten possible congruence classes (mod $10$) of $N_k$ and the two possible moves.
$$\begin{array}{c|c|c|}
N_k \text{ % } 10 & \text{+2} & \text{-7} & \cdot \frac{1}{2} \\ \hline
0 & - & 3 & 0, 5 \\ \hline
1 & 3 & 4 & - \\ \hline
2 & - & 5 & 1, 6 \\ \hline
3 & 5 & 6 & - \\ \hline
4 & - & 7 & 2, 7 \\ \hline
5 & 7 & 8 & - \\ \hline
6 & - & 9 & 3, 8 \\ \hline
7 & 9 & 0 & - \\ \hline
8 & - & 1 & 4, 9 \\ \hline
9 & 1 & 2 & - \\ \hline
\end{array}$$
From $0$, $1$, $4$, $5$, $6$, and $9$ (mod $10$), the above strategy always results in a move such that $N_{k+1}$ is congruent to $2$, $3$, $7$, or $8$ (mod $10$).
From $2$, $3$, $7$, or $8$ (mod $10$), there is never an option to make a move such that $N_{k+1}$ is congruent to $2$, $3$, $7$, or $8$ (mod $10$).
Theorem $1.3$: Let the starting $N$ be congruent to $0$, $1$, $4$, $5$, $6$, or $9$ (mod $10$) and suppose player A starts the game.
Then if player A follows the above strategy, he/she will win the game.
Hint: So by Lemma $1.1$ and $1.2$ we know that player A will win if $N$ ever gets down to $2$, $3$, $7$, or $8$. The final piece is to show that if player A follows the strategy outlined in Lemma $1.2$, $N$ will always eventually reach $2$, $3$, $7$, or $8$. Note that the only cases in which player A will make an increase to $N$ is if $N$ is congruent to $1$ (mod $10$) or if $N$ is $5$ before he/she moves.

A: Call a number $n$ winning if $n$ is of the form $10k+b$ with $b \in \{2,3,7,8,11,16\}$, or if $n=10.4^k.(2b+1)$,
and call $n$ losing if $n$ is $1,6$ or of the form $10k+b$ with $b \in \{4,5,9\}$ or if $n = 20.4^k.(2b+1)$.
If $n$ is winning then you can move to a losing number :
if $n=10k+b$ with $b \in \{11,12,16\}$, remove $7$.
if $n=10k+b$ with $b \in \{3,7\}$, add $2$.
if $n=2$ or $n=10k+8$ or $n=10.4^k(2b+1)$, divide by $2$.
If $n$ is losing then you can only move to a winning number.
Furthermore, if you always move from a winning number to a losing number (that is, if the players don't mess up when they get told they can win), then the game will end eventually. To show this it is enough to look at the longest possible sequences of "add $2$" moves.
If $n=10k+3$, you can have $4$ "add $2$" moves in a row (or, if $k$ was $0$, you win in two moves), leading to $10k+11$ (or the losing player can choose to go to $10k-2$ or $10k+2$ and decrease the numbers earlier than he's forced to)
Adding $2$ to $10k+11$ would be handing a win to the losing player, so you're forced to remove $7$ and get to $10k+4$. And from there, the losing player can only go to $5k+2$ or $10k-3$ (if that's allowed).
So overall, either you win, or you get to one of $10k-3,10k-2,10k+2,5k+2$, all of which are smaller than the $10k+3$ we started from.
This is enough to show that the numbers will decrease overall until someone wins the game.

A: Unless the starting number is either $5$ or $14$ (or $7$ I guess?) the game will never end.
Here's why: It's easy to see that $5$ and $14$ are the only numbers from which $7$ can be reached.  Therefore, as long as each player can avoid making one of these numbers, they will never lose and the game will never end.
The only reason a player would play either $5$ or $14$, then, is if these two (or one of these two) are their only options.  But it's easy to check that there is no number which only allows you to play either $5$ or $14$.


Q: How to Automatically Tust Auto Enrolled Code Signing Certificates In my organization all developers are setup to be granted a Code signing certificate via Auto Enrollment. Additionally, PowerShell is configured by group policy to require all scripts to be signed. However, PowerShell does not trust any of the code signing certificates without manual intervention.
I saw this Are code signing certificates automatically trusted across the domain if the root CA is trusted? and have verified that the Code signing certificates are children of the root, and that the root is listed as a trusted CA on all machines in my organization.
However, according to this https://serverfault.com/a/542179 AuthentiCode (what PowerShell uses for validating signatures) does not follow certificate chains. So, I cannot simply add a root and be done. I have to add each certificate manually.
Thus leading to my question.
How can I get all of the Auto Enrollment generated code signing certificates automatically added to "Trusted Publishers"?
All I have been able to find is documentation on how to do it with group policy one certificate at a time, manually. (i.e. http://technet.microsoft.com/en-us/library/cc772491.aspx). I really want an automated process that happens seamlessly when the auto enrollment certificate is created. How can I do that?

A: In enterprise environments it is not possible. You will have to publish new code signing certificates via group policies manually: Computer Configuration\Windows Settings\Security Settings\Public Key Services\Trusted Publishers section.


Q: Is it possible/sensible to split ASP.Net Core 2 (.NET Framework) Web Api into Class Library and Hosting projects? I'm trying to port an existing WCF Web API (targeting .NET Framework 4.6.1) to ASP.Net Core 2 using Visual Studio 2017 (v15.4.5) and am having trouble figuring out good/common/supported ways to organize projects, and what types of project they should be.
For example:

*

*Single project for Server and Hosting, or Class Library for Server and Console application for Hosting

*Windows Classic Desktop project for Console application and (new style csproj) Web Application for Server library, or both Web Applications (one outputting a Class Library, the other a Console Application)
I have the sneaking suspicion that there is something fundamental that I'm missing which means that one approach should be favoured over the others, or is even mandatory, but have found it hard to discover this from the ASP.Net Core 2 documentation.
Specific Requirements

*

*Should target .NET Framework 4.6.1
Since I need to access the Windows Registry from the internals of the Web API, I am targeting .NET Framework 4.6.1 rather than .NET Core.

*Host using HTTP.sys
I intend to use Windows Authentication in future and believe that Kestrel will not support that (Based upon HTTP.sys features).

*Host should run as a Windows Service
Ultimately, the Web API should be installed by Windows Installer and run as a service.
For the moment, I'm just trying to get the API to build/work correctly stand-alone, but would also appreciate any insight into how the choice of projects might affect publishing/deployment.
Preferred Solution
Whilst, by default, a new ASP.NET Core 2 Web Application is a single project outputting a Console Application, I would prefer to split the solution into 2 main projects:

*

*"Server" - An ASP.NET Core 2 (.NET Framework) Class Library containing the business logic of the Web API, controllers and Startup class

*"Host" - Console application which references "Server" and is responsible for hosting the Web API

This arrangement seems appropriate to me since any unit/integration test projects can reference the "Server" class library, not an executable (according to advice in Is it a bad practice to reference an exe file in C# project).
Furthermore, I'm led to believe this is reasonable because I can change the Output Type to "Class Library" in the project properties.
I'm assuming that since I'm targeting the .Net Framework, so long as I install the same NuGet packages as the "Server" project, there is no reason why the "Host" project cannot be a Windows Classic Desktop Console application.
Are there any hidden issues, perhaps relating to publishing/deployment, that make this arrangement a bad idea?
Would there be any advantage to making the Hosting project a Web Application (which would still reference the Server project)?
Attempt
Here are the steps I used to try to achieve my preferred project organization. Whilst it works, I get warnings generated during the build - see below.
Server

*

*Add New Project "Server"

*

*Choose Visual C#,  Web, ASP.NET Core Web Application
In the following dialog, target .NET Framework, ASP.NET Core 2.0, and choose Web API

*Change Output Type in Project properties to "Class Library"

*Delete Program.cs

Host

*

*Add New Project "Host"

*

*Choose Visual C#, Windows Classic Desktop, Console App (.NET Framework)

*Replace contents of Program.cs with:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Server;

namespace Host
{
  internal class Program
  {
    private static void Main(string[] args)
    {
      BuildWebHost(args).Run();
    }

    private static IWebHost BuildWebHost(string[] args) =>
      new WebHostBuilder()
        .UseStartup<Startup>()
        .UseHttpSys(options =>
        {
          options.UrlPrefixes.Add("http://localhost:8080/");
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
          logging.AddConsole();
          logging.AddDebug();
        })
        .Build();
  }
}

*Add a reference to the Server project

*Install these NuGet packages

*

*Microsoft.AspNetCore (2.0.1)

*Microsoft.AspNetCore.Mvc (2.0.1)

*Microsoft.AspNetCore.Server.HttpSys (2.0.2)

*Set as Startup Project

Problem: Build generates warnings
This solution runs under debugging, and responds correctly to http://localhost:8080/api/values and http://localhost:8080/api/values/1, but the following warnings are shown after building the solution:

Warning     The referenced component 'System.Security.Cryptography.Encoding' could not be found.    Host
Warning     The referenced component 'System.Xml.XPath' could not be found. Host
Warning     The referenced component 'System.IO.FileSystem.Primitives' could not be found.  Host
Warning     The referenced component 'System.IO.FileSystem' could not be found. Host
Warning     The referenced component 'System.Diagnostics.StackTrace' could not be found.    Host
Warning     The referenced component 'System.Xml.XmlDocument' could not be found.   Host
Warning     The referenced component 'System.Security.Cryptography.X509Certificates' could not be found.    Host
Warning     The referenced component 'System.Diagnostics.FileVersionInfo' could not be found.   Host
Warning     The referenced component 'System.Security.Cryptography.Algorithms' could not be found.  Host
Warning     The referenced component 'System.Xml.ReaderWriter' could not be found.  Host
Warning     The referenced component 'System.Security.Cryptography.Primitives' could not be found.  Host
Warning     The referenced component 'System.ValueTuple' could not be found.    Host
Warning     The referenced component 'System.Xml.XPath.XDocument' could not be found.   Host
Warning     The referenced component 'System.IO.Compression' could not be found.    Host
Warning     The referenced component 'System.AppContext' could not be found.    Host
Warning     The referenced component 'System.Threading.Thread' could not be found.  Host
Warning     The referenced component 'System.Console' could not be found.   Host

If this is a reasonable arrangement of projects, why am I getting these warnings?

A: We are doing something similar. Our host is a .NET Framework 4.7.1 project:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net471</TargetFramework>
    <IsPackable>true</IsPackable>
    <PlatformTarget>x86</PlatformTarget>
    <OutputType>Exe</OutputType>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <Prefer32Bit>false</Prefer32Bit>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.6" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="2.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Business.csproj" />
    <ProjectReference Include="..\Apis.Shared.csproj" />
    <ProjectReference Include="..\Apis.Contracts.csproj" />
  </ItemGroup>

</Project>

And our library projects are NetStandard2.0:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

</Project>

Program.cs looks like this:
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .ConfigureServices(services => services.AddAutofac())
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

Startup.cs looks like this:
public class Startup
{
    public Startup(IHostingEnvironment hostingEnvironment)
    {
        Settings = new AppSettings(hostingEnvironment);
    }

    public AppSettings Settings { get; private set; }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddOptions();
        // any other services registrations...

        var builder = new ContainerBuilder();
        // all autofac registrations...
        builder.Populate(services);

        return new AutofacServiceProvider(builder.Build(););
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}


Q: Generating a new PDF using an existing PDF Document I'm trying to generate a new PDF document using an existing document as a base on a UWP application. I want to import the pages from the existing document, create annotations with information received from the application level and create a new PDF document combining both.
But it just creates a PDF document with the same number of pages but they are empty. When I analyze the created document the content is not available even though I imported it. But the created annotations are available in the document.
This is the file creation logic.
public async Task EmbedCurrentAnnotationsInStore(PdfDocument document)
{
    if (document is null || document.IsDisposed)
        return;

    try
    {
        var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("embedded_doc.pdf", CreationCollisionOption.ReplaceExisting);
        PdfDocument newDocument = new PdfDocument();
        PDFium.FPDF_ImportPages(newDocument.Handle, document.Handle, 0);

        foreach (var page in newDocument.Pages)
            await annotationConvertor.ConvertToFPDFAnnotations(page, annotationAdapter.GetAnnotations()
                .Where(x =>
                    x.Status != AnnotationStatus.Removed &&
                    x.PageIndex == page.Index)
                .OrderBy(x => x.AnnotationIndex));

        using (var stream = await file.OpenStreamForWriteAsync())
        {
            newDocument.Save(stream, SaveFlags.None, document.FileVersion);

            await stream.FlushAsync();
            newDocument.Close();
        }
    }
    catch (Exception ex)
    {
        var err = PDFium.FPDF_GetLastError();
        throw ex;
    }
}

ConvertToFPDFAnnotations()
public async Task ConvertToFPDFAnnotations(PdfPage page, IEnumerable<BaseAnnotation> annotations)
{
    foreach (var annotation in annotations)
    {
        switch (annotation.AnnotationType)
        {
            case FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT:
                await EmbedFPDFAnnotationFromHighlightAnnotation(page, annotation.AsHighlightAnnotation());
                break;
            default:
                break;
        }
    }
}

EmbedFPDFAnnotationFromHighlightAnnotation()
private async Task EmbedFPDFAnnotationFromHighlightAnnotation(PdfPage page, HighlightAnnotation annotation)
{
    if (page is null || page.IsDisposed)
        return;

    var fdfAnnotation = page.CreateAnnot(page, FPDF_ANNOTATION_SUBTYPE.FPDF_ANNOT_HIGHLIGHT);
    fdfAnnotation.SetColor(fdfAnnotation.Handle, FPDFANNOT_COLORTYPE.FPDFANNOT_COLORTYPE_Color,
        (uint)annotation.Color.R,
        (uint)annotation.Color.G,
        (uint)annotation.Color.B,
        (uint)annotation.Color.A);
    fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CA", annotation.Color.A.ToString());
    foreach (var quadpoint in annotation.Quadpoints)
    {
        var refQuadpoint = quadpoint;
        fdfAnnotation.AppendAttachmentPoints(fdfAnnotation.Handle, ref refQuadpoint);
    }
    fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Index", annotation.StartIndex.ToString());
    fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Count", annotation.CharCount.ToString());

    var rect = new FS_RECTF();
    rect = annotation.Rect;
    fdfAnnotation.SetRect(fdfAnnotation.Handle, ref rect);
    fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "CreationDate", annotation.CreationDate);
    fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "M", annotation.ModifiedDate);
    if (string.IsNullOrEmpty(annotation.Contents))
        fdfAnnotation.SetStringValue(fdfAnnotation.Handle, "Contents", annotation.Contents);

    fdfAnnotation.CloseAnnot(fdfAnnotation.Handle);
}

I used this (FPDF_ImportPages) method to import the pages from the existing document.
Could someone help me with the issue I'm facing? Maybe I'm missing something here.
Thanks.


Q: Programmatically selecting imageViews from ArrayList or HashMap I have a Farkle game that I am trying to create a "Computer" player for and I am having a tough time trying to get this to work.
Game Play: 1's & 5's are always scorable, Straight 1-6, 3-of-a-kind, 4-of-a-kind, 5-of-a-kind & 6-of-a-kind are scorable.  Pairs are only scorable if using all 6 dice. example: 2,2,5,5,4,4.
So here is my issue.  I have it selecting all dice just to make it work, but I want to find the Value of the dice that are showing on the board and these scorable combinations and select them programmatically 1-by-1. The screen shot shows the human player has selected the 5.  I  know the code is a mess (I have been told several times). FYI, I had to remove a lot of code to stay in the 30000 limit. Complete Code is here

Here are the files I think are needed.  You will see some Toasts, this was me trying to figure out the logic of what I need to do
AiOhFarkActivity - Main Class
public class AiOhFarkActivity extends Activity implements AnimationEndListener {

    private AiGameController controller;
    private DieManager dm;

    private ArrayList<MyImageView> imageViews = new ArrayList<MyImageView>();

    // Added for AI to set the starting
    // number of dice selected to 0
    private int selectedDie = -1;

    //public boolean performItemClick (View v, int position, long id);
    private int[] letters = new int[6];
    private boolean toFarkle = false;
    private int animationCount = 0;

    public Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        //Create, Initialize and then load the Sound manager and Volume Control
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        SoundManager.  ....

        r = getResources();
        initializeArrays();
        scoreBox = (TextView) ....
        numFarkles = (TextView) ....
        dieScore = (TextView) ....
        scoreButton = (Button) ....
        rollButton = (Button) ....
        finalButton = (Button) ....
        finalRoundLayout = (LinearLayout) ....
        winnerButton = (Button) ....
        winnerLayout = (LinearLayout) ....
        winnerTextView = (TextView) ....

        handler = new Handler();

        // Restore GameController
        if (getLastNonConfigurationInstance() != null) {
                controller = (AiGameController) getLastNonConfigurationInstance();
                controller.newUI(this);
                updateImages(false, false);
        } else {
                controller = new AiGameController(this);
        }

        // Restore UI elements
        if (savedInstanceState != null && savedInstanceState.getBoolean("hasState")) {

                scoreBox.setText ....
                numFarkles.setText ....
                dieScore.setText ....
                scoreButton.setText ....
                scoreButton.setEnabled ....
                rollButton.setEnabled ....
                finalButton.setEnabled ....
                finalRoundLayout.setEnabled ....
                winnerButton.setEnabled ....
                winnerButton.setText ....
                winnerLayout.setEnabled ....
        }
    }

    // These arrays allows the use of a for loop in updateImages()
    private void initializeArrays() {
            imageViews.add((MyImageView) findViewById(R.id.img_1));
            imageViews.add((MyImageView) findViewById(R.id.img_2));
            imageViews.add((MyImageView) findViewById(R.id.img_3));
            imageViews.add((MyImageView) findViewById(R.id.img_4));
            imageViews.add((MyImageView) findViewById(R.id.img_5));
            imageViews.add((MyImageView) findViewById(R.id.img_6));

            letters[0] = R.drawable.dief;
            letters[1] = R.drawable.diea;
            letters[2] = R.drawable.dier;
            letters[3] = R.drawable.diek;
            letters[4] = R.drawable.diel;
            letters[5] = R.drawable.diee;
    }

    public void onRoll(View v) {
        controller.onRoll();

    }

    // TODO AI
    public void disableButtons(){

    }

    // TODO AI
    public void enableButtons(){
        rollButton.setClickable(true);
        scoreButton.setClickable(true);
    }

    // TODO AI
    public void disableDice(){

    }

    // TODO AI
    public void enableDice(){

    }

    public void onScore(View v) {
    // Calculate Score
    controller.onScore();

    //Play Sound
    if (myPrefs.getBoolean("soundPrefCheck", true)) {
        SoundManager. ....
    }

    // After Player Scores
    // Check to see if the Current Player is now the Machine
    // If machine player, roll the dice and lock
    // the buttons so the human cannot cheat
    // TODO AI
    if (controller.isMachinePlayer() == true) {
        controller.machineRoll();
        disableButtons();
        disableDice();
    }else {
        enableButtons();
        enableDice();
    }
}

    public void updateImages(boolean toAnimate, boolean isFarkle) {
            // This is used in onAnimationEnd() to determine when all animations
            // have ended. Since all the animations are starting when this method is
            // called the count is 0
            animationCount = 0;

            MyImageView i = null;
            for (int j = 0; j < imageViews.size(); j++) {

                    Animation a = AnimationUtils.loadAnimation(this, R.anim.dice_animation);

                    i = imageViews.get(j);

                    // If were gonna animate we need to know when the animation ends.
                    // Hence were gonna attach this instance as a listener so
                    // onAnimationEnd() gets called when animations finish.
                    if (toAnimate) {
                            i.setAnimationEndListerner(this);
                    }

                    // Get the right image from the Resources. *See in DiceManager
                    // getImage()
                    i.setImageDrawable(r.getDrawable(controller.getImage(j)));
                    if (toAnimate && controller.shouldAnimate(j)) {
                            i.clearAnimation();
                            i.startAnimation(a);
                    }
            }

            // Used in onAnimatonEnds()
            if (isFarkle)
                    toFarkle = true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public Object onRetainNonConfigurationInstance() {
            return controller;
    }

    public void showFarkle() {

    }

    private void farkleAnimation() {

    }

    @Override
    public void onAnimationEnd(View v) {

    }

}

AiGameController
public class AiGameController extends PreferenceActivity {

        private ArrayList<Player> players = new ArrayList<Player>();

        public AiGameController(AiOhFarkActivity ui) {
                setupPlayers(ui);

                dM = new DieManager();
                UI = ui;
                updateUIScore();

                currPlayer = players.get(round % players.size());
                lastPlayer = null;
                machinePlayer = players.get(round % players.size());

        }

        public void setupPlayers(Context c) {

                int numOfPlayers = 1;

                for (int i = 1; i <= numOfPlayers; i++) {

                        // TODO AI
                        String player = "Human  ";
                        String machine = "Machine";
                        players.add(new Player(player));
                        players.add(new Player(machine));
                }
        }

        // If the currPlayer is the Machine
        // TODO AI
        public void machineRoll() {
                // Check for Machine Player, if found Roll the dice
            // Check for Machine Player, if found Roll the dice
            if (currPlayer.getName() == "Machine"){
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                    onRoll();
                                    handler.postDelayed(new Runnable() {
                                            public void run() {

                                                    onClickDice(0, false);
                                                    onClickDice(1, false);
                                                    onClickDice(2, false);
                                                    onClickDice(3, false);
                                                    onClickDice(4, false);
                                                    onClickDice(5, false);

                                                    android.os.SystemClock.sleep(350);

                                                    if (ppossibleScore >= GOB_SCORE){

                                                            handler.postDelayed(new Runnable() {
                                                                    public void run() {
                                                                            //Play Sound
                                                                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(UI);
                                                                            if (prefs.getBoolean("soundPrefCheck", true)) {
                                                                                SoundManager.playSound(11, 1);  // Flip Sound
                                                                            }
                                                                            onScore();
                                                                    }

                                                            }, 750);
                                                    }else {
                                                            handler.postDelayed(new Runnable() {
                                                                    public void run() {
                                                                            // If the highest score possible on the table is 0 then its a farkle
                                                                            if (Scorer.calculate(dM.diceOnTable(DieManager.ABS_VALUE_FLAG), true,
                                                                                UI) == 0) {
                                                                                currPlayer.setInRoundScore(0);
                                                                                currPlayer.incrementNumOfFarkles();
                                                                                // True because its a Farkle
                                                                                endRound(true);
                                                                                // Else just show what the player rolled
                                                                            } else
                                                                                repaetMachineRoll();
                                                                    }
                                                            }, 750);
                                                    }
                                            }
                                    }, 1750);

                                    // If all dice are selected (Hot Dice) onRoll again

                                    // Not sure if this belongs here ..... But,
                                    // If the numDiceRemaining <= 2 and the CurrScoreOnTable >= 300
                                    // bank the points - call onScore
                                    // if numDiceRemaining > 2 and CurrScoreOnTable <= 250 - call onRoll
                            }
                    }, 1750);
            }

        // If the currPlayer is the Machine
        public boolean isMachinePlayer() {
                // TODO Alert AI
                // Check for Machine Player, if found Roll the dice
                if (currPlayer.getName() == "Machine"){
                        return true;
                }
                return false;
        }

        // Always called from onRoll method
        public void startRound() {
                isRoundEnded = false;
                currPlayer = players.get(round % players.size());
                currPlayer.resetInRoundScore();
                machinePlayer = players.get(round % players.size());
                machinePlayer.resetInRoundScore();
                updateUIScore();

                // Show the Current Players Number of Farkles
                String fmessage = "";
                fmessage += UI.getString(R.string.stYouHave) + " " + currPlayer.getNumOfFarkles() + " " +  UI.getString(R.string.stFarkles);
                UI.updatenumOfFarkles(UTILS.setSpanBetweenTokens(fmessage, "$$", new StyleSpan(Typeface.NORMAL)));
        }

        // Can be called from onRoll or onScore
        public void endRound(boolean isFarkle) {

                if (!isFarkle)

                        UI.rollButtonState(true);
                UI.scoreButtonState(false);

                String pscore = UI.getString(R.string.stScore);
                UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));

                // show penalty
                SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(UI);
                int farklePenaltyScore = Integer.valueOf(pref.getString("farklePenaltyPref", "-1000"));

                // Checks to see if Farkle Penalty is on
                if (pref.getBoolean("farklePenalty", true)) {
                        if (isFarkle && currPlayer.getNumOfFarkles() == 3) {
                                currPlayer.setInRoundScore(farklePenaltyScore);
                                // Show a -1000 next to his name
                                updateUIScore();
                                // There is a penalty *See animationsEnded()
                                negateFarklePenalty = true;
                        }
                }

                // Alert the UI a farkle is rolled
                UI.updateImages(false, isFarkle);

                // If its not a farkle then just clear the table and Update the images
                if (!isFarkle) {
                        dM.clearTable();
                        UI.updateImages(false, false);
                }

                isRoundEnded = true;

                round++;
                lastPlayer = currPlayer;
                currPlayer = players.get(round % players.size());

                // Usually updateUIScore() is called to erase the "+Score" but it
                // shouldn't be called if the last player farkled three times because it
                // erases the -1000
                if (lastPlayer.getNumOfFarkles() != 3)
                        updateUIScore();

                if (!isFarkle && currPlayer.hasHighestScore()) {
                        alertOfWinner();

                }
        }

        private void alertOfWinner() {

                showGameOver();
        }

        // Finds the player with the Highest score
        private int findHighestScore() {
                for (Player p : players) {
                        if (p.hasHighestScore())
                                return players.indexOf(p);
                }
                return -1;
        }

        // Updates the ScoreBox
        private void updateUIScore() {

                String message = "";

                for (Player p : players) {
                        if (p.equals(currPlayer)) {

                                int currInRoundScore = p.getInRoundScore();
                                String temp = "$$            ";
                                String sign = (currInRoundScore > 0) ? "+" : "";

                                if (currInRoundScore != 0 && !isRoundEnded)
                                        temp = "$$   " + sign + currInRoundScore + "    ";

                                message += "$$" + p.getName() + temp + p.getScore() + "\n";

                        } else {
                                message += p.getName() + "             " + p.getScore() + "\n";

                        }

                }

                // The $$ tell setSpanBetweenTokens() what to make bold
                UI.updateScoreBox(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));

        }

        // Number of Current Die remaining on the table
        public int numOnTable() {
                return dM.numOnTable();
        }

        // Called when the roll button is clicked or can be called from the AI
        public void onRoll() {
                UI.finalRoundLayout.setVisibility(View.GONE);

                // Sounds
                SharedPreferences mySoundPref=PreferenceManager.getDefaultSharedPreferences(UI);
                if (mySoundPref.getBoolean("soundPrefCheck", true)) {

                }

                // Reset Score Button
                String message = "";

                //message += "Dice Score: 0";

                // onRoll
                if (isRoundEnded)
                        startRound();

                UI.rollButtonState(false);
                UI.scoreButtonState(false);

                if (dM.getHighlighted(DieManager.INDEX_FLAG).length > 0) {

                        int scoreOnTable = Scorer.calculate(
                                dM.getHighlighted(DieManager.ABS_VALUE_FLAG), true, UI);

                        currPlayer.incrementInRoundScore(scoreOnTable);
                        // Show how much was picked up
                        updateUIScore();

                        dM.pickUp(dM.getHighlighted(DieManager.INDEX_FLAG));
                }

                dM.rollDice();

                UI.updateImages(true, false);

                // If the highest score possible on the table is 0 then its a farkle
                if (Scorer.calculate(dM.diceOnTable(DieManager.ABS_VALUE_FLAG), true,
                        UI) == 0) {
                        currPlayer.setInRoundScore(0);
                        currPlayer.incrementNumOfFarkles();
                        // True because its a Farkle
                        endRound(true);
                        // Else just show what the player rolled
                } else
                        UI.updateImages(true, false);
                // Check for isMachinePlayer
        }

        // When a dice is clicked the GameController determines which dice to
        // highlight and whether to enable the buttons
        public void onClickDice(int index, boolean isFarkle) {

                // Play Select Sound
                SharedPreferences mySoundPref=PreferenceManager.getDefaultSharedPreferences(UI);
                if (mySoundPref.getBoolean("soundPrefCheck", true)) {
                        SoundManager.playSound(10, 1);  // Select Sound
                }

                String message = "";
                String pscore = "";

                if (isRoundEnded)
                        return;

                int value = dM.getValue(index, DieManager.ABS_VALUE_FLAG);

                // A letter was clicked
                if (value == 0)
                        return;

                // Always highlight 5's and 1's
                if (value == 5 || value == 1) {

                        dM.toggleHighlight(index);

                } else {

                        // This method determines if the dice should be highlighted
                        if (shouldHighlight(index)) {

                                // if true then get the pairs of this dice
                                int[] pairs = dM.findPairs(index, DieManager.INDEX_FLAG);

                                // Highlight them
                                for (int i : pairs)
                                        dM.toggleHighlight(i);

                                // And highlight the original dice
                                dM.toggleHighlight(index);
                        }
                }

                // The score of the highlighted dice
                int highlightedScore = Scorer.calculate(dM.getHighlighted(DieManager.ABS_VALUE_FLAG), false, UI);
                // Second parameter is false to not ignore any extra dice

                // The score the player picked up
                int possibleScore = currPlayer.getInRoundScore() + highlightedScore + currPlayer.getScore();

                // Display the Current Score of the selected Dice
                //message += "Dice Score: " + highlightedScore;
                message += (UI.getString(R.string.stDiceScore)) + ": " + highlightedScore;
                UI.updateCurrentScore(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));

                // Display the Potential Points in the Score Button
                int ppossibleScore = currPlayer.getInRoundScore() + highlightedScore;

                pscore = "+ " + ppossibleScore;
                UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));

                if (highlightedScore != 0) {
                        UI.rollButtonState(true);

                        // Play Hot Dice sound
                        if (mySoundPref.getBoolean("soundPrefCheck", true)) {
                                if (dM.numDiceRemain() == 0){
                                        SoundManager.playSound(8, 1);  // HotDice Sound
                                }
                        }

                        // Tells it when to enable the Score Button
                        // based on the Get-On-Board Value
                        if (possibleScore >= GOB_SCORE) {
                                UI.scoreButtonState(true);
                                showToast("GOB Score met");
                        }

                        // If a player is past the winning score
                        if (isPlayerPastWinScore) {

                                // Disable the score button
                                UI.scoreButtonState(false);

                                // The highest score so far
                                int scoreOfWinnerToBe = players.get(findHighestScore())
                                        .getScore();

                                // If the player can get a higher score then enable the score
                                // button
                                if (possibleScore > scoreOfWinnerToBe) {
                                        UI.scoreButtonState(true);
                                }
                        }
                } else {
                        UI.rollButtonState(false);
                        UI.scoreButtonState(false);
                }

                UI.updateImages(false, false);
        }

        // Calculate the current Score that is possible if banked.
        public int CurrScoreOnTable() {
                int highlightedScore = Scorer.calculate(dM.getHighlighted(DieManager.ABS_VALUE_FLAG), false, UI);
                int possibleScore = lastPlayer.getInRoundScore() + highlightedScore;
                return possibleScore;
        }

        // Determines whether to highlight the dice clicked
        private boolean shouldHighlight(int index) {

                // Gets the pairs (if any)
                int[] pairs = dM.findPairs(index, DieManager.INDEX_FLAG);

                int[] valuesOfPairs = new int[pairs.length + 1];

                // Takes the value of the pairs and puts them into the valueOfPairs
                // array
                System.arraycopy(dM.findPairs(index, DieManager.ABS_VALUE_FLAG), 0, valuesOfPairs, 0, pairs.length);

                // Adds the dice that was clicked to the array
                valuesOfPairs[pairs.length] = dM.getValue(index, DieManager.ABS_VALUE_FLAG);

                // True if the value of the pairs and the dice clicked is 0
                boolean isZero = Scorer.calculate(valuesOfPairs, false, UI) == 0;

                int[] diceOnTable = dM.diceOnTable(DieManager.ABS_VALUE_FLAG);

                // True is there are three pairs on the table
                boolean isThreePair = Scorer.isThreePair(diceOnTable, UI, true) != 0;

                // True if there is a straight on the table
                boolean isStraight = Scorer.isStraight(diceOnTable, UI, true) != 0;

                return (!isZero || isThreePair || isStraight);
        }

        // Score button is clicked.
        public void onScore() {
                // Reset the Current Dice Score and Make Roll Button Active
                String message = "";
                // message += "Dice Score: 0";

                message += (UI.getString(R.string.stDiceScore)) + ": 0";

                UI.updateCurrentScore(UTILS.setSpanBetweenTokens(message, "$$", new StyleSpan(Typeface.BOLD)));

                String pscore = UI.getString(R.string.stScore);
                UI.updatepPoints(UTILS.setSpanBetweenTokens(pscore, "$$", new StyleSpan(Typeface.BOLD)));

                // Values of highlighted dice on table
                int[] highlighted = dM.getHighlighted(DieManager.ABS_VALUE_FLAG);
                // Score of the highlighted dice
                int onTable = Scorer.calculate(highlighted, false, UI);
                // The players new Score
                int newScore = currPlayer.getScore() + onTable + currPlayer.getInRoundScore();
                currPlayer.setScore(newScore);

                if (newScore >= WINNING_SCORE) {
                        //SharedPreferences myPrefs=PreferenceManager.getDefaultSharedPreferences(this);
                        isPlayerPastWinScore = true;
                        // If no one is over the WINNING_SCORE findWinnerToBe() returns -1
                        if (findHighestScore() == -1) {
                                // Player is the first one to pass the score
                                currPlayer.setOriginalWinner(true);
                                currPlayer.setHasHighestScore(true);

                        } else {
                                currPlayer.setHasHighestScore(true);
                        }
                }

                currPlayer.resetInRoundScore();

                // False because its not a Farkle

                endRound(false);

                // Show the Current PLayers Number of Farkles

        }

        public int getImage(int index) {
                return dM.getImage(index);
        }

        public void newUI(AiOhFarkActivity newUI) {
                UI = newUI;
        }

        // Should not animate if value of dice is 0 ie its a letter
        public boolean shouldAnimate(int index) {
                return (dM.getValue(index, DieManager.VALUE_FLAG) > 0);
        }

        public void clearTable() {
                dM.clearTable();
        }

        public void animationsEnded(boolean isFarkle) {

        }

}

DieManager
public class DieManager {

    // Will return the Indexes of the dice when this is used
    public static final int INDEX_FLAG = 1;
    // Will return the values of the dice when this is used
    public static final int VALUE_FLAG = 2;
    // Will return the absolute values of the dice when this is used
    public static final int ABS_VALUE_FLAG = 3;

    // The array that holds the dice
    private int[] diceValues = { 0, 0, 0, 0, 0, 0 };

    private HashMap<Integer, Integer> diceImages = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> deadImages = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> letterImages = new HashMap<Integer, Integer>();

    // Sets @newValue to dieValues[@index]
    public void setValue(int index, int newValue) {
        Log.w(getClass().getName(), "Index = " + index + " Value = " + newValue);
        diceValues[index] = newValue;
    }

    public DieManager() {
        super();
        initializeMaps();

    }

    private void initializeMaps() {

        // Shows Selected
        diceImages.put(-6, R.drawable.die6_select);
        diceImages.put(-5, R.drawable.die5_select);
        diceImages.put(-4, R.drawable.die4_select);
        diceImages.put(-3, R.drawable.die3_select);
        diceImages.put(-2, R.drawable.die2_select);
        diceImages.put(-1, R.drawable.die1_select);

        // Shows Rolled
        diceImages.put(1, R.drawable.die1_roll);
        diceImages.put(2, R.drawable.die2_roll);
        diceImages.put(3, R.drawable.die3_roll);
        diceImages.put(4, R.drawable.die4_roll);
        diceImages.put(5, R.drawable.die5_roll);
        diceImages.put(6, R.drawable.die6_roll);

        // dice are dead
        deadImages.put(0, R.drawable.die1_dead);
        deadImages.put(1, R.drawable.die2_dead);
        deadImages.put(2, R.drawable.die3_dead);
        deadImages.put(3, R.drawable.die4_dead);
        deadImages.put(4, R.drawable.die5_dead);
        deadImages.put(5, R.drawable.die6_dead);

        // Shows blank
        letterImages.put(0, R.drawable.die_no);
        letterImages.put(1, R.drawable.die_no);
        letterImages.put(2, R.drawable.die_no);
        letterImages.put(3, R.drawable.die_no);
        letterImages.put(4, R.drawable.die_no);
        letterImages.put(5, R.drawable.die_no);

    }

    public void rollDice() {

        showToast("Rolling Dice");

        boolean isNewRound = (numOnTable() == 0);
        for (int j = 0; j < 6; j++) {
            if (isNewRound || diceValues[j] != 0)
                diceValues[j] = (int) ((Math.random() * 6) + 1);
        }
    }

    // Returns the value or absolute value
    public int getValue(int index, int flag) {
        if (flag == ABS_VALUE_FLAG)
            return Math.abs(diceValues[index]);
        return diceValues[index];
    }

    // If a dice value is 0 then its a letter
    public int numOnTable() {
        int count = 6;
        for (int i : diceValues) {
            if (i == 0)
                count--;
        }
        return count;
    }

    // Picking up makes the dice value 0
    public void pickUp(int[] highlighted) {

        for (int i = 0; i < highlighted.length; i++)
            diceValues[highlighted[i]] = 0;

    }

    // A negative value means a die is highlighted
    public void toggleHighlight(int index) {
        diceValues[index] *= -1;
    }

    public void clearTable() {
        diceValues[0] = 0;
        diceValues[1] = 0;
        diceValues[2] = 0;
        diceValues[3] = 0;
        diceValues[4] = 0;
        diceValues[5] = 0;

    }

    // Return the dice that aren't 0
    public int[] diceOnTable(int flag) {
        showToast("Getting Dice Values");
        if (flag == ABS_VALUE_FLAG) {
            int[] array = new int[diceValues.length];

            for (int i = 0; i < diceValues.length; i++)
                array[i] = Math.abs(diceValues[i]);

            return array;
        }

        return diceValues;
    }

    //Returns dice that are negative
    public int[] getHighlighted(int flag) {
        int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
        int count = 0;

        for (int j = 0; j < 6; j++) {
            if (diceValues[j] < 0) {

                if (flag == INDEX_FLAG)
                    dirtyArray[count++] = j;

                if (flag == VALUE_FLAG)
                    dirtyArray[count++] = diceValues[j];

                if (flag == ABS_VALUE_FLAG)
                    dirtyArray[count++] = Math.abs(diceValues[j]);
            }
        }

        int[] cleanArray = new int[count];

        //Returns an array of length 0
        if (count == 0)
            return cleanArray;

        System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
        return cleanArray;

    }

    // Finds in dieValues same @value and excludes @index
    public int[] findPairs(int index, int flag) {

        int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };

        int count = 0;

        for (int j = 0; j < 6; j++) {

            if (j != index
                    && Math.abs(diceValues[j]) == Math.abs(diceValues[index])) {

                if (flag == INDEX_FLAG)
                    dirtyArray[count++] = j;

                if (flag == VALUE_FLAG)
                    dirtyArray[count++] = diceValues[j];

                if (flag == ABS_VALUE_FLAG)
                    dirtyArray[count++] = Math.abs(diceValues[j]);
            }

        }

        int[] cleanArray = new int[count];

        if (count == 0)
            return cleanArray;

        System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
        return cleanArray;
    }

    //Get the Dice Images
    public Integer getImage(int index) {
        if (diceValues[index] == 0) {
            return letterImages.get(index);
        } else {
            return diceImages.get((diceValues[index]));
        }
    }

    //Get the Number of dice remaining that are not 0
    public int numDiceRemain() {
        int counter = 0;
        for (int j = 0; j < diceValues.length; j++) {
            if (diceValues[j] > 0)
                counter++;
        }
        return counter;
    }

    public void selectDice() {
        // TODO Alert AI

    }

    public void selectAllDice() {
        // TODO Alert AI
    }

}


Q: Laravel 5.2 -> 5.3 Infinite Redirect Loop after upgrade I have upgraded from Laravel 5.2 to 5.3. All URI now lead to an infinite (ERR_TOO_MANY_REDIRECTS) redirection loop at /auth/login. I tried to remove my middleware one after the other to try to find the problem. I even commented out the whole Http\Kernel and removed middleware from the RouteServiceProviders.
When I artisan route:list, I can see that now my routes have no middleware, but I still get the infinite redirection. For example, if I try to access a route without middleware my.app/foo/bar or use a random string my.app/somerandomstringthatisnotaroute I always get ERR_TOO_MANY_REDIRECTS at my.app/auth/login.
I also tried to artisan clear-compiled and artisan route:clear.


Q: Very Tricky Double Integral Problem Evaluate the Integral:
\begin{align}
\int_{0}^{4}\int_{\sqrt{x}}^{2}{\mathrm{d} y\,\mathrm{d}x \over 1 + y^{3}}
\end{align}
I can't understand how this would be possible. There IS a formula for evaluating $1/\left(1+y^{3}\right)$, but it becomes an extremely complicated mess that I can't imagine could be re-integrated. Is there a simplification technique that I'm missing here $?$.

A: Reverse the order of integration.  How?  Plot the region of integration.  It is all $y \in [\sqrt{x},2]$, and then $x \in [0,4]$.  So, imagine enclosing the graph of $y=\sqrt{x}$ in a box $[0,4] \times [0,2]$.  Then we are integrating the top part of the box, above the curve, $y$ first, then $x$.
Reversing means integrate over the same region, $x$ first, then $y$.  The resulting integral is very straightforward, and the answer is $(2/3) \log{3}$.

A: change the order of integral to get
$$\int_{0}^{2}\int_{0}^{y^2}\frac{1}{1+y^3}dxdy$$

A: There are many double integral questions like this. The idea is that by changing the order of integration, an integral that might be difficult or even impossible to compute becomes much easier.
We can see from the integration bounds that we are integrating over the region bounded by $y=\sqrt{x}$, $y=2$, $x=0$ and $x=4$.
Swapping integration means integrating by $x$ first, so that $x$ goes from $0$ to $y^2$ and $y$ goes from $0$ to $2$.
$$\int_{0}^2 \int_{0}^{y^2} \frac{1}{1+y^3} dx dy = \int_{0}^2 \frac{y^2}{1+y^3} dy$$
This can be completed by using the substitution method.


Q: How to take mac address of iBeacon in Ionic Framework for the app build on android platform I am trying to build an application for android devices with ionic framework to scan the ibeacons in an environment with the help of https://www.thepolyglotdeveloper.com/2015/09/support-ibeacons-in-your-ionic-framework-mobile-app/ . I just want to know few things before stepping into this ionic framework.
1. Is it possible to scan ibeacons on android devices without giving UUID's?
2. Is it possible to fetch the mac address of ibeacons on android devices?

If the above things are not possible in Ionic Framework, which stack or framework should I use to build an application for android devices to scan both ibeacons and non ibeacons to get the mac address and RSSI?


Q: Send Image to server using File input type I have a screen where I am capturing video from camera, taking a snap. I also have a file input and I want to set this option to the captured image from the camera, i.e..snap.
I do not want to store the snap as a cookie and later retrieve it, as it will later make the users computer heavy and will require cleaning everytime.
so the code is
<input type="file" id="visitorphoto" name="visitorPhoto" accept="image/*" capture>

which is according to this w3 document.
Any Ideas using javascript?
Thanks,
Abhijeet.

A: Use formData to upload file.
HTML:
<input type="file" id="filechooser">

Javascript Code
function uploadFile() {
    var blobFile = $('#filechooser').files[0];
    var formData = new FormData();
    formData.append("fileToUpload", blobFile);

    $.ajax({
       url: "upload.php",
       type: "POST",
       data: formData,
       processData: false,
       contentType: false,
       success: function(response) {
           // .. do something
       },
       error: function(jqXHR, textStatus, errorMessage) {
           console.log(errorMessage); // Optional
       }
    });
}

Compatibility:
http://caniuse.com/xhr2


Q: Select specif row data (numeric) from list of 5 (dimnames) in a $ : chr row in multiple tables Hy everybody. I'm kind of stuck with simple code. In fact I have this output:
roc_value

, , MAXENT.Phillips, RUN1, PA1

         Testing.data Cutoff Sensitivity Specificity
KAPPA           0.558  484.0      63.713      90.667
TSS             0.555  354.0      73.840      81.667
ROC             0.863  369.5      72.996      83.000
ACCURACY        0.788  484.0      63.713      90.667
BIAS            0.996  344.0      73.840      79.667

, , GLM, RUN1, PA1

         Testing.data Cutoff Sensitivity Specificity
KAPPA           0.565    422      83.122      74.333
TSS             0.575    422      83.122      74.333
ROC             0.843    420      83.122      74.333
ACCURACY        0.782    422      83.122      74.333
BIAS            0.979    518      72.574      79.667

, , GAM, RUN1, PA1

         Testing.data Cutoff Sensitivity Specificity
KAPPA           0.664  554.0      81.435      85.000
TSS             0.664  554.0      81.435      85.000
ROC             0.885  557.5      81.435      85.333
ACCURACY        0.834  595.0      76.793      88.667
BIAS            0.996  554.0      81.435      85.000

, , RF, RUN1, PA1

         Testing.data Cutoff Sensitivity Specificity
KAPPA           0.768    404      83.544      92.000
TSS             0.762    404      83.544      92.000
ROC             0.950    406      83.544      92.667
ACCURACY        0.886    485      81.435      94.333
BIAS            0.987    343      84.810      89.000

, , MAXENT.Tsuruoka, RUN1, PA1

         Testing.data Cutoff Sensitivity Specificity
KAPPA           0.509    368      86.498      66.000
TSS             0.527    321      90.717      61.667
ROC             0.838    372      86.498      66.333
ACCURACY        0.756    479      74.262      76.333
BIAS            0.970    488      70.464      78.667

the str(roc_value) is:
num [1:5, 1:4, 1:5, 1, 1] 0.558 0.555 0.863 0.788 0.996 ...
 - attr(*, "dimnames")=List of 5
  ..$ : chr [1:5] "KAPPA" "TSS" "ROC" "ACCURACY" ...
  ..$ : chr [1:4] "Testing.data" "Cutoff" "Sensitivity" "Specificity"
  ..$ : chr [1:5] "MAXENT.Phillips" "GLM" "GAM" "RF" ...
  ..$ : chr "RUN1"
  ..$ : Named chr "PA1"
  .. ..- attr(*, "names")= chr ""

I want to select only ROC values from Testing.data column in a single object (to continue my script), for instance:
whatidlike <- c(0.863,0.843,0.885,0.950,0.838) # only a single object with ROC values.

Tried dplyr, subset etc. and can't move on. Could someone, please, give me a hand?

A: You list object names look strange ', , RF, RUN1, PA1' but you should be able to access them using index. e.g. roc_value[[1]], roc_value[[2]]... etc
so, then further to select Testing.data would be simply as
roc_value[[1]]['Testing.data']


Q: Why does `fatrace` not detect certain open events (udisks /dev/sda)?
Why is `ioerr_cnt` rising, without showing any messages in the log?
I'm struggling a bit to work out what process does this. sudo lsof +D /dev/ doesn't seem to show any processes with a SCSI device currently open, but I don't see any relevant open() calls at the time of the errors either (cd /dev && sudo fatrace -c)...
[Answer:] udisks polls drives every ten minutes e.g. for SMART data.
$ ps -ax|grep udisksd
  810 ?        Ssl    0:13 /usr/libexec/udisks2/udisksd
$ sudo strace -t -f -p 810
[pid   810] 14:11:09 clone(strace: Process 26543 attached
child_stack=0x7f8fc551ddf0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7f8fc551e9d0, tls=0x7f8fc551e700, child_tidptr=0x7f8fc551e9d0) = 26543
[pid 26543] 14:11:09 set_robust_list(0x7f8fc551e9e0, 24 <unfinished ...>
[pid   810] 14:11:09 poll([{fd=4, events=POLLIN}, {fd=8, events=0}, {fd=9, events=0}, {fd=11, events=POLLIN}, {fd=13, events=POLLIN}], 5, 599968 <unfinished ...>
[pid 26543] 14:11:09 <... set_robust_list resumed> ) = 0
[pid 26543] 14:11:09 prctl(PR_SET_NAME, "pool") = 0
[pid 26543] 14:11:09 openat(AT_FDCWD, "/dev/sda", O_RDONLY|O_NONBLOCK) = 14
[pid 26543] 14:11:09 ioctl(14, SG_IO, {guard='Q', protocol=BSG_PROTOCOL_SCSI, subprotocol=BSG_SUB_PROTOCOL_SCSI_CMD, ...

I don't know why fatrace did not seem to show this device being opened by udisks. It managed to show other device opens (like when I ran lsof, or when I started firefox and it opened /dev/dri/card0).

^ Does anybody know?

A: It seems that fatrace does not show any device opens.  You can use it to see processes opening directories under /dev, like /dev/dri, but not device nodes like /dev/dri/card0.


Q: javascript link to another javascript i want create an program using javascript, but i want my file be more organize, is there some way that i can implement the concept of include or require of php. example: javascript file that only contains function let say function.js, then another javascript file main.js. is there a way that in main.js i can call a function in the function.js?
function.js

function test(){
   alert("hello world");
}

main.js

$(document).ready(function(){
    test();
});

A: Yes, you can always use functions out of another javascript file.
though if you executed the code immediately you need to specify the right order: First the function definition, then the function call so:
<head>
    <script src="javascript.js" type="text/javascript"></script>
    <script src="main.js" type="text/javascript"></script>
</head>


Q: Amplifying the WiFi signal I am writing to find out the best option to amplify the existing WiFi signal in my house in order to be able to be online in my backyard with my MacBook Air. Would purchasing an AirPort Express be a good solution, or a simple extender/repeater would do the job?

A: An Access Point would be sufficient - & cheapest.
[just some examples from Amazon, no recommendations specifically. Note, the filter on Amazon isn't great, there are other device types in there, as well as simple Access Points]
An Access Point needs no additional functionality other than being able to push a signal further.
You wire it via your existing Ethernet to where the signal will reach the garden. All routing/DHCP functionality is then still provided by your existing router.
If you can't, for any reason, get an Ethernet cable far enough to reach, then you would need a Range Extender, which is in essence the same thing, but wireless throughout. I'd still go for an AP as first choice, if at all possible.


Q: Google Directions API Polyline not added to map I have a problem using the Google Directions API.
I'm getting the JSON string and parsing it, getting the overview_polylines string
NSString *allPolylines = [NSString stringWithFormat:[[[routes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"]];

This thing works.
I'm having trouble adding it to the map.
I'm using this post http://iosguy.com/tag/directions-api/ which seems to be exactly what I'm after.
I've implemented the
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr

method, and it works great.  I NSLogged the results and it shows up as if I'm outputting CLLocation objects.
The problem is that I can't make it show up on the map. This is the code that follows
    NSMutableArray *_path = [self decodePolyLine:allPolylines];
    NSInteger numberOfSteps = _path.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [_path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[index] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [_mapView addOverlay:polyLine];
    [self mapView:_mapView viewForOverlay:polyLine];

I also tried adding an explicit call to
[self mapView:_mapView viewForOverlay:polyLine];

which is:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor redColor];
    polylineView.lineWidth = 1.0;

    return polylineView;
}

The last method gets called, I checked using NSLog, but nothing shows up on the map.
Any thoughts?
Thanks in advance!

A: The code shown looks OK except that you're not supposed to call viewForOverlay directly.
The map view will call that delegate method when it needs to show the overlay.
The simplest reason it would not be calling the delegate method is that the map view's delegate property is not set.
If the delegate property is set, then verify that the coordinates are what you're expecting and also make sure they are not flipped (latitude in longitude and vice versa).
Another thing to check:
If _mapView is an IBOutlet, make sure it is actually connected to the map view in the xib.


Q: autossh pid is not equal to the one in pidfile when using start-stop-daemon I am trying to create a service on my Debian Wheezy system.
When trying to use start-stop-daemon to run autossh, the pid contained into the pidfile does not match with the autossh process.
$ AUTOSSH_PIDFILE=/var/run/padstunnel.pid
$ sudo start-stop-daemon --make-pidfile --background --name mytunnel --start --pidfile /var/run/mytunnel.pid --exec /usr/lib/autossh/autossh -- -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222
$ ps -elf |grep autossh
1 S root       447     1  0  80   0 -   329 pause  19:07 ?        00:00:00 /usr/lib/autossh/autossh -M 0 -p 22 ...
$ cat /var/run/mytunnel.pid
446

This behaviour prevents from stopping autossh using start-stop-daemon or kill it using the pid from the pidfile.
Is there any reason to this behaviour ?
How to workaround it and make autossh's pid matches the pidfile ?

A: The solution I found is inspired by this answer.
Actually, the AUTOSSH_PIDFILE variable could not be used by autossh (because start-stop-daemon runs in a different environment).
So the workaround is to use :
$ sudo start-stop-daemon --background --name mytunnel --start --exec /usr/bin/env AUTOSSH_PIDFILE="/var/run/mytunnel.pid" /usr/lib/autossh/autossh -- -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222

*

*/usr/bin/env AUTOSSH_PIDFILE="/var/run/mytunnel.pid" correctly defines the necessary environment variable

*--make-pidfile and --pidfile are no longer required by start-stop-daemon

*sudo start-stop-daemon --pidfile /var/run/mytunnel.pid  --stop now works to kill autossh

*--background option makes the ssh's -f optional (using -f or not does not change anything if --background is used)

The reason for the behaviour is not completely clear to me. However, it seems that autossh automatically creates several processes to handle correctly ssh instances when it does not see AUTOSSH_PIDFILE variable.
Edit:
When using it from a service init script (in /etc/init.d/servicename), the syntax has to be modified:
sudo start-stop-daemon --background --name mytunnel --start --exec /usr/bin/env -- AUTOSSH_PIDFILE="/var/run/mytunnel.pid" /usr/lib/autossh/autossh -M 0 -p 22 user@server -f -T -N -R 31022:localhost:31222

Notice the -- that must come just after the /usr/bin/env command (it was after the /usr/lib/autossh/autossh from command line).

A: Just an update for a working solution from 7 years into the future as I recently came across this exact same issue.
The AUTOSSH_PIDFILE variable for some reason will make the program fail without any output, including when using -v. What I found would work is simply foregoing -f on autossh and using --background on the start-stop-daemon. Apparently this also necessitates the -N flag on autossh, which is as best I can tell undocumented.
Could be a new development or upstream issues, but in any case the answer by OP did not work for me, but this did:
start-stop-daemon --start --background --user myuser --quiet --make-pidfile --pidfile "/var/run/myhost_autossh.pid" --exec autossh -- -M 0 -N myhost


Q: What data structure should I use to keep track of recently used items? I need something like a bounded queue where I can only insert say 10 elements. A new element should override the last inserted element.  There should be only n distinct elements
I am looking for suggestions in Java by the way.

A: ITYM an implementation of a LRU algorithm.

*

*How to set up a simple LRU cache using LinkedHashMap

*Simple LRU Caching with Expiration

A: This is a classic application for a queue data structure. A stack of size 10 would keep track of the first 10 elements you added to it, whereas a queue of size 10 would keep track of the 10 most recent elements. If you are looking for a "recent items" list, as suggested by the title of your question, then a queue is the way to go.
edit: Here is an example, for visualization purposes:
Let's say you want to keep track of the most recent 4 items, and you access eight items in the following order:

F, O, R, T, Y, T, W, O

Here is what your data structures would look like over time:
access  item      queue          stack
  1      F     [ F . . . ]    [ . . . F ]
  2      O     [ O F . . ]    [ . . O F ]
  3      R     [ R O F . ]    [ . R O F ]
  4      T     [ T R O F ]    [ T R O F ]
  5      Y     [ Y T R O ]    [ Y R O F ]
  6      T     [ T Y T R ]    [ T R O F ]
  7      W     [ W T Y T ]    [ W R O F ]
  8      O     [ O W T Y ]    [ O R O F ]

Removing the top element from a stack removes the item that was most recently added, not the oldest item.
Removing one element from a queue removes the oldest item, so your queue will automatically hold the most recent items.
edit: with thanks to Adam Jaskiewicz, here is some documentation on Java's Queue implementation.


Q: React unit testing Leaflet I have problem with unit testing Map component.
My class component:
componentDidMount() {
    const { zoom, data, center } = this.props;
    const { activeButton } = this.state;
    if (data[activeButton] != null) {
      this.map = map('map', {
        center: data[activeButton].points ? data[activeButton].points[0] : center,
        zoom,
        layers: [tileLayer(...SETTINGS.mapTileLayer)],
      });
      if (data[activeButton].points != null) {
        this.addPolyline(data[activeButton].points);
      }
    }
  }

  addPolyline = (points: Points) => {
    if (this.polyline != null) {
      this.map.removeLayer(this.polyline);
      this.map.removeLayer(this.marker.start);
      this.map.removeLayer(this.marker.stop);
    }

    if (points != null && points[0] != null) {
      this.polyline = new Polyline(points, SETTINGS.polyline);

      this.marker.start = new Marker(points[0]);
      this.marker.stop = new Marker(points[points.length - 1]);

      this.polyline.addTo(this.map);
      this.marker.start.addTo(this.map);
      this.marker.stop.addTo(this.map);

      this.map.panTo(points[0]);
    }
  };

Unit test with Jest and Enzyme
function getComponent(mockData) {
  return <Map data={mockData} />;
}

const mockData = [
  { id: 0, name: '1', distance: '1', points: [[0, 0], [1, 1]] },
  { id: 1, name: '2', distance: '2', points: [[0, 0], [1, 1]] },
];

describe('LastActivity component', () => {
  it('button click', () => {
    const wrapper = mount(getComponent(mockData), { attachTo: document.body });

...etc...
});

With this test I get

TypeError: Cannot read property '_layerAdd' of null
this.polyline.addTo(this.map);

When I comment out line this line

this.polyline.addTo(this.map);

Everything works fine and tests pass
package.json:
"enzyme-adapter-react-16": "1.2.0",
"enzyme": "3.4.4",
"react": "16.4.2",
"react-dom": "16.4.2",
"leaflet": "1.3.4",
"jest": "23.5.0",
"jest-cli": "23.5.0",

A: I see a bunch of related issues on leaflet's github. The maintainer seems to have something against frameworks.
Check out https://react-leaflet.js.org/ that should work better with react.


Q: What is the limit $\lim_{s \to 0}\frac{1}{\pi s^2} e^{-r^2/s^2}$ There is a typo in one of the papers I just read and instead of the known delta function limit
$\lim_{s \to 0}\frac{1}{\pi s} e^{-r^2/s^2}$
it says
$\lim_{s \to 0}\frac{1}{\pi s^2} e^{-r^2/s^2}$
Note the $1/s^2$ instead of the $1/s$. I was wondering what that limit might yield if applied to a proper test function and integrated.

A: Let $u_s=\frac{1}{\pi s} e^{-r^2/s^2}$. Observe that if $\frac{1}{s} u_s\rightarrow u$ as $s\rightarrow 0$, then $u_s\rightarrow 0$ as $s\rightarrow 0$. It follows, since $u_s\rightarrow \delta$ and $\delta\neq 0$, that $\frac{1}{s}u_s$ does not converge.

A: Let $\phi$ a test function such that $\phi(0) = 1$
then
$$\frac{1}{\pi s^2} \int_{\mathbb R}e^{-\frac{r^2}{s^2}} \phi(r)dr = \frac{1}{s}\frac{1}{\pi s} \int_{\mathbb R}e^{-\frac{r^2}{s^2}} \phi(r)dr $$
and if $s\rightarrow 0^+$
$$\frac{1}{\pi s} \int_{\mathbb R}e^{-\frac{r^2}{s^2}} \phi(r)dr \rightarrow \phi(0) = 1$$
$$\frac{1}{s} \rightarrow \infty$$
so
$$\frac{1}{\pi s^2} \int_{\mathbb R}e^{-\frac{r^2}{s^2}} \phi(r)dr \rightarrow \infty $$
so it doesn't converge.


Q: Service is not running when OS is upgraded from Windows 8.1 to Windows 10 We have upgraded windows from 8.1 to 10.
Now in Windows 10 services installed by us are not running.
The same services are running properly if we install these services on Windows 8.1.
ON windows 10, we tried below things which didn't solve the problem.

*

*services-> select service -> properties -> Set [Log on] as LOCAL SERVICE

*Set full permission to "perticuler" user or "everyone" user for the folder where service files exist.

*Change owner of folder as "everyone", "system" or "perticuler" user where service files exist.
Below is a workaround which works but not feasible for us since it requires password and actually we want to know the actual reason behind this problem.
workaround :
1. services-> select service -> properties -> Set [Log on] as "This account" where user can be selected and it also requires password. Refer attached image.
Please note that the service is a dot net(c#) service and it runs internally a jar file. if it is able to run jar file then only service starts successfully.

Thanks in advance

A: I have found the cause and solution.
[Cause of problem]
Service unable to understand that, to run JAR file, which program should be run.
[Detail]
I tried to debug the code.
At the location where process is started, popup message like shown in below image is occurred.
location : processSample.Start()

*

*It means that atleast once user need to select the program.

*If we select [Java(TM) Platform SE binary] once, then after that the
service always runs successfully.

*This behavior is in Windows 10 only.

*In addition to program selection, user setting shown in image in question is also required to run the service.

*I want to say that, in default program setting already correct program is selected for .jar files as shown in below image, but still windows 10 asks user to select program once.

[Solution]
Run JAR file from windows(c#) service with settings below :
sampleProcess.StartInfo.FileName = "javaw.exe";
sampleProcess.StartInfo.Arguments = "-jar Sample.jar";
sampleProcess.StartInfo.WorkingDirectory = @"C:\SampleFolder";
sampleProcess.StartInfo.UseShellExecute = false;
sampleProcess.EnableRaisingEvents = true;
sampleProcess.StartInfo.CreateNoWindow = false;

Here working directory is the location where the [Sample.jar] does exist.
additinally a Path environment variable must be set in order to execure "javaw.exe".
Before fix I had implementation as below which is not proper for every system environment :
sampleProcess.StartInfo.FileName = "Sample.jar";
sampleProcess.StartInfo.WorkingDirectory = @"C:\SampleFolder";
sampleProcess.EnableRaisingEvents = true;
sampleProcess.StartInfo.CreateNoWindow = false;


Q: "CORS: No 'Access-Control-Allow-Origin' header is present ", but it is present I'm trying to log in or register in my Angular app, but whenever I access to the php file which does the HTTP calls to the DB regarding users (authentication.php), I get three errors:

*

*Access to XMLHttpRequest at 'http://localhost/authentication.php?command=login' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

*ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost/authentication.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost/authentication.php: 0 Unknown Error","error":{"isTrusted":true}}

*GET http://localhost/authentication.php?command=login net::ERR_FAILED
(The last one says GET for login, POST for register)
In authentication.php I have the following code regarding headers:
require "openDB.php";
include "validators/usuarioValidator.php";

In openDB.php:
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');

In validators/usuarioValidator.php:
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: PUT, DELETE, POST, GET');

I've tried writing those headers in authentication.php, adding OPTIONS to Allow-Methods and allow all origins with *, but I still get the same three errors.
My user.service.ts has the following code regarding these operations:
register(user : any, key : string) : Promise<any>{
    let parametros = new HttpParams().set("command", "register");

    user.verif = key;

    return this.http.post(this.url, user, {params: parametros}).toPromise();
  }

(I'm just pasting register because login is a bit weirdly done and the problem here seems to be with authentication.php, no matter what operation it makes)
I've also tried adding withCredentials: true and responseType: "blob" to params since I'm not receiving a json in the TS, but still nothing.

A: It seems like you are not setting Headers properly in your HTTP Request body, try the following code,
register(user : any, key : string) : Promise<any>{
    let parametros = new HttpParams().set("command", "register");

    user.verif = key;

    return this.http.post(this.url, user, {Headers: parametros}).toPromise();
  }

Also, if you use the HTTPClient package to make requests then it's a bit hard to set custom headers.
If you can prevent some issues (like CORS Access-Control Errors) by using axios or a similar package


Q: VHDL - Error comparing std_logic_vector with declared constant unsigned? The unsigned has been cast to std_logic_vector I am trying to create a Seven Segment Display controller in Vivado 2020.2 using VHDL 2008. The entity needs to be parametrizable by system clock rate and time to display each digit in the display (there are 8 digits). Here is the code I have so far:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.numeric_std_unsigned.all;

entity SevenSeg is
    generic (
        -- Rate in HZ
        CLK_RT          : integer := 100000000;
        -- Time in ms
        DISPLAY_TIME    : integer := 20
    );
    port (
        clk             : in std_logic;
        rst             : in std_logic;
        dataIn          : in std_logic_vector(31 downto 0);
        digitDisplay    : in std_logic_vector(7 downto 0);
        digitPoint      : in std_logic_vector(7 downto 0);
        anode           : out std_logic_vector(7 downto 0);
        segment         : out std_logic_vector(7 downto 0)
    );
end SevenSeg;

architecture rtl of SevenSeg is
    constant ROLL_OVER : unsigned := to_unsigned(20 * 1000000 / (1000000000 / CLK_RT), 32);
    signal cnt       : std_logic_vector(31 downto 0);
    signal anode_sel : std_logic_vector(2 downto 0);
begin

     process (clk)
     begin
         if (clk'EVENT AND clk = '1') then
             if rst = '1' then
                 anode_sel <= (others => '0');
             else if cnt = std_logic_vector(ROLL_OVER) then
                 anode_sel <= anode_sel + 1;
             end if;
         end if;
     end process;
end rtl;

With the current state of the code, Vivado is flagging a syntax error "near end process." I am pretty sure something is wrong with cnt = std_logic_vector(ROLL_OVER) because when I comment that part of the if clause out, there is no longer any syntax errors. I have been researching comparisons in vhdl as well as the constant unsigned/vector types and nothing seems to be working. I would appreciate any insight into what is causing this error.

A: There are two alternatives, either with elsif:
if rst = '1' then
   anode_sel <= (others => '0');
elsif cnt = std_logic_vector(ROLL_OVER) then
   anode_sel <= anode_sel + 1;
end if;

or: else if
if rst = '1' then
   anode_sel <= (others => '0');
else
   if cnt = std_logic_vector(ROLL_OVER) then
      anode_sel <= anode_sel + 1;
   end if;
end if;

A: You are not following standard VHDL.  The else if is introducing a new if condition which requires an additional end if to be correct syntax.  You could use elsif instead and your code would not generate errors.


Q: Postfix - allow sending e-mail just to authenticated users I would like to set up postfix in order to send e-mail just if I give a user  and password to my customers. I would like to use debian users (even to track malicious users and suspend them eventually). I've followed postfix guide lines, but even specifying a fake user by sendmail, postfix send it without stopping it. How can I handle this thing?


Q: Как выровнять по центру список рубрик в wordpress? Создал отдельную страницу в Wordpress и хочу вывести на ней список рубрик. Я использовал функцию wp_list_categories.
Все выводит только не могу применить стили чтобы рубрики выводились по центру.
Вот мой код:

<?php get_header(); ?>

    <div class="illustration">Пример текста

        <?php wp_list_categories('orderby=name&child_of=54');  ?>

    </div>

<?php get_footer(); ?>

В css прописал следующий код:
.illustration {
    text-align: center;
    border: 3px solid green;
   }


Q: Which is better to use for Google Assistant? Actions SDK or JSON request response I have built multiple actions on Google Assistant using the JSON request and response V2 but I have heard that using Actions SDK for building actions specifically for Google Assistant should be preferred. I am confused whether to use Actions SDK or JSON request response?
For example - On this link, for every sample code there are two tabs, Node.js using Actions SDK and JSON using the JSON request response.
Which one should be preferred and in which scenarios?
Thanks!

A: Let's first look at what those tabs mean, and then discuss what your best approach should be.
node.js vs JSON tabs
The "node.js" tab shows what the code looks like using the actions-on-google library. For the most part, this library uses the same code if you're using either the Action SDK or using Dialogflow to implement. Where there are differences, the documentation does note how you have to handle them - this is particularly true when it comes to how you have to handle responses.
The "JSON" tab shows what the JSON would look like if you are not using the actions-on-google library and need to send JSON yourself. You might do this because you're using a language besides node.js, or you just want to know what the underlying protocol looks like.
The catch is that the JSON illustrated here is what would be used by the Action on Google JSON protocol. If you're using Dialogflow, then this JSON would be wrapped inside the payload.google field and there are a couple of other differences documented. So when generating JSON for a Dialogflow response, you should use this as a guide, but need to be aware of how it might differ.
What should you use?
What you use depends on what your needs are and what your goals are for developing.
If you are trying to develop something you intend to release, or might do so someday, and you are new to voice or bot interfaces, then you'll probably want to use Dialogflow - no matter what other choices you may make.
If you have your own Natural Language Processing (NLP) system, then you will want to use the Action SDK instead of Dialogflow. How you handle it (using the actions-on-google library or using JSON) will depend on how you need to integrate with that NLP.
If you're familiar with node.js, or want to learn it, then using the actions-on-google library is a good choice and that first tab will help you. (There are other choices. Dialogflow also has a dialogflow-fulfillment library, which is good if you want to be able to support the bot platforms it supports as well. The multivocal library has a more configuration-driven template approach to building a conversational backend that was designed to work with the Assistant and Dialogflow. Both of these illustrate how to do the same things that Google's documentation does.)
If you would rather use another language, you'll need to reference the JSON documentation because there are few complete libraries for these platforms. Your best bet would be to use Dialogflow with JSON. Dialogflow has some example JSON for how to apply the Google documentation you cite to their fulfillment protocol.
Summary

*

*You should probably use Dialogflow.

*If you can, use actions-on-google or another library.

*If you have a need to use another language or want to use the JSON, be aware of the possible differences.


Q: Retain color of Switch when disabeld I am using a Switch in xamarin forms. When I toggle, the color is Pink when true and grey when false.
When I disable the switch as I do not want the user to toggle. then the color change to Grey.
How can i retain the color of the Switch. When it is disable and it is true it should be in default color but not grey,
Could you please suggest how can i achieve this.
<Switch IsToggled="True" IsEnabled="False"/>

Thanks
Rao

A: I have investigated a bit this problem and I can see two solutions:
Easy way
Use a private boolean variable instead of using the IsEnabled property. Then when the clicked event is handled, check the switch's status with the variable.
Hard way
Overwrite the Switch control to get this behaviour. You can follow this guide.

A: As seen from the Switch for Xamarin.Forms, there is currently no option of specifying the color. Conclusively, you will have to create your own renderer for both iOS and Android.
Android
Essentially, what you need to do is to override the OnElementChanged and OnCheckChanged events and check for the Checked Property of the Control. Afterwards, you can set the ThumbDrawable of the Control and execute SetColorFilter with the color you want to apply. Doing so although requires Android 5.1+. An example is given here.
You could also create utilise the StateListDrawable and add new ColorDrawables for the StateChecked, StateEnabled and lastly, a default value as well. This is supported for Android 4.1+. An example of using the StateListDrawable is provided in detail here.
iOS
iOS is somewhat more simple. Simply create your own SwitchRenderer, override the OnElementChanged event and set the OnTintColor and ThumbTintColor.
I hope this helps.

A: You need to make custom renderer for your control in this case switch like that and set color when it changes:
class CustomSwitchRenderer : SwitchRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)
    {
        base.OnElementChanged(e);

        this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
        this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);

        this.Control.CheckedChange += this.OnCheckedChange;
    }

    private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
    {
        this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop);
        this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop);
    }
}