问:
PHP Curl GET request doesn't return data
This really has me perplexed and other examples on Stackoverflow have not helped.

If I type into the browser :

https://api.bitfinex.com/v2/book/tXMRUSD/P0

I will get an long array of data which is correct.

With the following simple code :

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://api.bitfinex.com/v2/book/tXMRUSD/P0");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HTTPGET, 1);

$result = curl_exec($ch);
curl_close($ch);

var_dump($result);
</code>```

I get :

bool(false)

The only difference is my browser fetches the data directly, while the PHP code is on a local website hosted using IIS on windows 10.
I've tried everything and just can't see where I'm going wrong. Any help will be most appreciated. (Ironically, all the authenticated and encrypted POST code works fine and I'm stuck on the easy stuff!)

答:
Try This code it will work!!!!

```<code><?php
$url= "https://api.bitfinex.com/v2/book/tXMRUSD/P0";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$result = curl_exec($ch);
curl_close($ch);

print_r($result);

?>
</code>```

Body:
This really has me perplexed and other examples on Stackoverflow have not helped.

If I type into the browser :

https://api.bitfinex.com/v2/book/tXMRUSD/P0

I will get an long array of data which is correct.

With the following simple code :

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://api.bitfinex.com/v2/book/tXMRUSD/P0");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HTTPGET, 1);

$result = curl_exec($ch);
curl_close($ch);

var_dump($result);

I get :

bool(false)

The only difference is my browser fetches the data directly, while the PHP code is on a local website hosted using IIS on windows 10.
I've tried everything and just can't see where I'm going wrong. Any help will be most appreciated. (Ironically, all the authenticated and encrypted POST code works fine and I'm stuck on the easy stuff!)

Body:
Try This code it will work!!!!

<?php
$url= "https://api.bitfinex.com/v2/book/tXMRUSD/P0";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

$result = curl_exec($ch);
curl_close($ch);

print_r($result);

?>


来源: stackexchange

问:
Truncate and Insert
I am connecting to oracle using an ETL tool.The operation what I am doing is truncating an existing table and inserting records into that table from a different table. This is working fine for 15 to 20 cycles of job run. After that my job got stuck in the portion where its inserting record.Is there anything wrong which I am doing here. Please find the query I am using below.Could some one help on this, from the previous experience.</p>

```<code>    truncate table TABLE1;
        insert into TABLE1  select * from TABLE_SRC where TYPE in('MP','DA')
and ID in(select ID from TABLE_SRC where TYPE in('MP','DA') and FLAG='Y');
        commit;
</code>```

答:
I believe the table is going in lock situation.
Check with dba’s .
Select * from dba_lock ;</p>

ContentLicense: CC BY-SA 3.0

Title: Truncate and Insert

Body:
I am connecting to oracle using an ETL tool.The operation what I am doing is truncating an existing table and inserting records into that table from a different table. This is working fine for 15 to 20 cycles of job run. After that my job got stuck in the portion where its inserting record.Is there anything wrong which I am doing here. Please find the query I am using below.Could some one help on this, from the previous experience.

    truncate table TABLE1;
        insert into TABLE1  select * from TABLE_SRC where TYPE in('MP','DA')
and ID in(select ID from TABLE_SRC where TYPE in('MP','DA') and FLAG='Y');
        commit;


问:
Method to compare VBA change in xlsm file in Visual Studio 12
Just like we can compare .NET, javascripts files in Visual Studio and point out the exact changes that have been made between two separate versions, similarly is there a way to compare VBA of an xlsm file between two versions in Visual Studio 12?

Thanks in advance...

答:
Unfortunately, we cannot achieve that.

We cannot compare the .xlsm files with hte VBA code directly. We can only compare the text files in VS.

So, you could export all your VBA code into text for source control. Thus you can compare the different versions same as .NET, javascripts files.

There is an excel addin : https://github.com/hilkoc/vbaDeveloper.

It can export all your vba code automatically, as soon as you save your workbook. You can also easily import it again when you open a workbook.

Another workaround is comparing with other tools:

Excel: Extract VBA code to text files (for diffing)

VbaDiff

DiffEngineX

Other threads for your reference:

Best way to do Version Control for MS Excel

Excel VBA and Version Control


问:
Visual Studio Async CTP must be installed on client machines ?
If i use Async/Await in my code, must i install the CTP on each client machine or just on machine where i develop ?</p>

答:
In my opinion its not a good idea to use this CTP in production code. But as well as I know this is compiler feature, so you need only .Net 4.0 installed on client PC.

Update:
There is some special .NET Framework 4.0 update called “.NET Framework Async CTP”. It could be required at client machine.

ContentLicense: CC BY-SA 2.5


问:
How to unlock jenkins on windows 10
I installed jenkins on my window 10 machine by using the msi I downloaded. It installed fine and has now launched the browser prompting me to unlock jenkins with the initialadminpassword. I can't find this file anywhere. I looked in the install directory C:\Program Files (x86)\Jenkins and I have checked the log files and no password was written to it. I even did a search on my whole C: for initialadminpassword and nothing came up. I do have a file called secret.key in my Jenkins install directory but the key in this file isn't working. Any ideas on how I can get around this would be very helpful

Thanks

答:
In the Jenkins Home directory there should be a secrets subfolder. In that directory there should be a file called initialAdminPassword (no extension).

This file contains the password it is referring to.

Title: How to unlock jenkins on windows 10


问:
why arguments of a function cannot be declared val or var
Why the arguments of a function cannot be defined as val or var?

```<code>scala> def add2(val x:Int) = x+2
<console>:1: error: identifier expected but 'val' found.
def add2(val x:Int) = x+2
         ^

scala> def add3(var x:Int) = x+3
<console>:1: error: identifier expected but 'var' found.
def add3(var x:Int) = x+3
         ^

scala> def add2(x:Int) = x+2
add2: (x: Int)Int
</code>```

答:
I am copy pasting a text from Programming in Scala 3rd edition

"Any parameters to a method can be used inside the method. One important characteristic of method parameters in Scala is that they are vals, not vars.The reason parameters are vals is that vals are easier to reason about. You needn't look further to determine if a val is reassigned, as you must do with a var."

Body:
Why the arguments of a function cannot be defined as val or var?

scala> def add2(val x:Int) = x+2
<console>:1: error: identifier expected but 'val' found.
def add2(val x:Int) = x+2
         ^

scala> def add3(var x:Int) = x+3
<console>:1: error: identifier expected but 'var' found.
def add3(var x:Int) = x+3
         ^

scala> def add2(x:Int) = x+2
add2: (x: Int)Int


问:
How to POST a input string value using thyemeleaf?

My project based on spring boot,Thymeleaf,mysql,html and Jquery.

i tried to post the input String data to @RestController page,but it received as EMPTY which means null.
Here is my Code Details

HTML

```<code><form id="addchargesformid" method="post" th:action="@{/addcharge}">
 <!-- input box add -->
 <div class="form-group">
    <label for="chargeName">Add New Charge*</label>
    <input th:id="chargeName" th:name="chargeName" th:value="${chargeName}" type="text" class="form-control" placeholder="Ex : Maintanence charge">
</div>
<br/>
<button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
</form>
</code>```

@RestController

```<code>/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@ModelAttribute String chargeName)
{
    ModelAndView respondResult = new ModelAndView();
    try {
        String result  = serAssignCharges.doAddCharges(chargeName);
        if(result.equals("success"))
        {
            doGetChargesList();
        }
        else {
            respondResult.addObject("warning","sorry! failed to add");
        }

    } catch (Exception e) {
        // TODO: handle exception
    }
    return respondResult;
}
</code>```

Please help me to resolve this...

答:
I made a code changes....In HTML adding

th:object="${chargeName}"

in form,adding in input tag

name="chargeName"

Full Code Here

```<code> <form id="addchargesformid" method="post" th:action="@{/addcharge}" th:object="${chargeName}">
     <!-- input box add -->
     <div class="form-group">
        <label for="chargeNameid">Add New Charge</label>
        <input id="chargeNameid" name="chargeName" type="text" class="form-control" placeholder="Ex : Maintanence charge">
    </div>
    <br/>
    <button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
    </form>
</code>```

@RestController

changed @ModelAttribute to @RequestParam

```<code>/*To Add Individual charges into list*/
    @PostMapping(value="/addcharge")
    public ModelAndView doAddCharge(@RequestParam String chargeName)
    {
        ModelAndView respondResult = new ModelAndView();
        try {
            String result  = serAssignCharges.doAddCharges(chargeName);
            if(result.equals("success"))
            {
                respondResult = new ModelAndView("redirect:" + "/getchargeslist"); /*it is redirecting from
                                                                                "/addcharge" to "/getchargeslist" */
            }
            else {
                respondResult.addObject("warning","sorry! failed to add");
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        return respondResult;
    }
</code>```

Body:
My project based on spring boot,Thymeleaf,mysql,html and Jquery.

i tried to post the input String data to @RestController page,but it received as EMPTY which means null.
Here is my Code Details

HTML

<form id="addchargesformid" method="post" th:action="@{/addcharge}">

    Add New Charge*
    <input th:id="chargeName" th:name="chargeName" th:value="${chargeName}" type="text" class="form-control" placeholder="Ex : Maintanence charge">

<button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
</form>

@RestController

/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@ModelAttribute String chargeName)
{
    ModelAndView respondResult = new ModelAndView();
    try {
        String result  = serAssignCharges.doAddCharges(chargeName);
        if(result.equals("success"))
        {
            doGetChargesList();
        }
        else {
            respondResult.addObject("warning","sorry! failed to add");
        }

    } catch (Exception e) {
        // TODO: handle exception
    }
    return respondResult;
}

Please help me to resolve this...

Body:
I made a code changes....In HTML adding

th:object="${chargeName}"

in form,adding in input tag

name="chargeName"

Full Code Here

 <form id="addchargesformid" method="post" th:action="@{/addcharge}" th:object="${chargeName}">
     <!-- input box add -->
     <div class="form-group">
        <label for="chargeNameid">Add New Charge</label>
        <input id="chargeNameid" name="chargeName" type="text" class="form-control" placeholder="Ex : Maintanence charge">
    </div>
    <br/>
    <button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
    </form>

@RestController

changed @ModelAttribute to @RequestParam

/*To Add Individual charges into list*/
    @PostMapping(value="/addcharge")
    public ModelAndView doAddCharge(@RequestParam String chargeName)
    {
        ModelAndView respondResult = new ModelAndView();
        try {
            String result  = serAssignCharges.doAddCharges(chargeName);
            if(result.equals("success"))
            {
                respondResult = new ModelAndView("redirect:" + "/getchargeslist"); /*it is redirecting from
                                                                                "/addcharge" to "/getchargeslist" */
            }
            else {
                respondResult.addObject("warning","sorry! failed to add");
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        return respondResult;
    }


问:
Generating swagger definition for legacy java applications without using annotations
Is it possible to generate swagger definition for legacy Java applications which do not follow REST based services?
Note: I am able to generate swagger for applications with REST JAXRS and some other frameworks like spring. So the expectation is it possible to generate for an application which are not using any annotations. For example a web application which was developed using only html, jsp, servlets etc. In some places I have seen that swagger is specifically for REST services but just want to make sure is there a way to do for legacy applications. </p>

答:
You can't do it without providing swagger a way to generate its JSON.
There are 2 options for you:

Use swagger annotations. (JAX-RS native ones are supported to reduce duplication, but you can do everything just with Swagger ones)

Generate swagger.json manually or write you own logic that will produce compatible JSON.

Swagger UI is just about visualizing JSON of expected format describing REST services.


问:
Installing an SQL Server Sample Database in SQL Server 2017 using SSMS
I am brand new to SQL. I have not written SQL and do not have any prior experience. I am following an SQL tutorial on Udemy and to follow along I need to restore a database and retrieve both the mdf and ldf files.

I tried using the Northwind sample database which I downloaded from this website: http://northwinddatabase.codeplex.com/

I then click on create new Query in SSMS

and ran the following query which executed successfully:

I then ran this query which resulted in an error:

I naviagted to the my D drive on my file system and there is no folder there named MSSQLDataFiles. My C drive has only 45 GB left of space and I'm wondering if that may be an issue although I don't think that should be an issue at all, at least for what I am trying to achieve.

All I'm interested in is restoring the database file so that I can follow along with the Udemy tutorial.

Any suggestions would be greatly appreciated.

Thank you for your help

答:
there is no folder there named MSSQLDataFiles. My C drive has only 45 GB left of space and I'm wondering if that may be an issue although I don't think that should be an issue at all, at least for what I am trying to achieve

You need to create folder mssqldatafiles and all the subfolders for the restore to work


问:
CSS Flex spacing issue
I'm having trouble figuring out how to have two columns (which get shrunk into one big column when the screen size shrinks) display their whole content without overlapping. Here's the images of what is happening The first is when the app is on a larger screen, where the flex-direction is set to row. When the screen size is smaller, I have it switch flex-direction to column, which works well except I cannot figure out how to make the 2nd row (Trending Down) start where the Trending Up stops, where ever that may be. Instead it's starting the 2nd column right in the middle of it like you see in the image.

Here's the code full size:

```<code>.playersColumns {
display: flex;
flex-direction: row;
justify-content: center;
padding-top: 28px;
align-items: center;
}

.playersBody {
flex-wrap: wrap;
min-width: 255px;
}
</code>```

Here is the code when width < 600px (where the issue is occurring)

```<code>.playersColumns {
display: flex;
flex-direction: column;
justify-content: space-between;
padding-left: 52px;
}
</code>```

As you can see, players are being entered into the database, being displayed, and voted on. I need to have it line up one section on top of the other if there are only 2 players, or 20 players listed in Trending Up.

Here's the React:

```<code><div className="playersColumns">
      <div className="playersBody">
        <span className="trendHeaderUp">TRENDING UP</span>
        {
          orderedPlayersUp.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }
      </div>
      <div className="playersBody">
        <span className="trendHeaderDown">TRENDING DOWN</span>
        {
          orderedPlayersDown.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }
      </div>
    </div>
</code>```

答:
The following code for screen size < 600 should work:

```<code>.playersColumns {
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding-top: 28px;
  align-items: center;
  flex-wrap: wrap;
}
</code>```

It adds wrapping when the element doesn't fit next to another element and will move it to the next line.
It would be wise to make the elements itself have a width of 100% when using a smaller screen size.

Title: CSS Flex spacing issue

Body:
I'm having trouble figuring out how to have two columns (which get shrunk into one big column when the screen size shrinks) display their whole content without overlapping. Here's the images of what is happening The first is when the app is on a larger screen, where the flex-direction is set to row. When the screen size is smaller, I have it switch flex-direction to column, which works well except I cannot figure out how to make the 2nd row (Trending Down) start where the Trending Up stops, where ever that may be. Instead it's starting the 2nd column right in the middle of it like you see in the image.

Here's the code full size:

.playersColumns {
display: flex;
flex-direction: row;
justify-content: center;
padding-top: 28px;
align-items: center;
}

.playersBody {
flex-wrap: wrap;
min-width: 255px;
}

Here is the code when width < 600px (where the issue is occurring)

.playersColumns {
display: flex;
flex-direction: column;
justify-content: space-between;
padding-left: 52px;
}

As you can see, players are being entered into the database, being displayed, and voted on. I need to have it line up one section on top of the other if there are only 2 players, or 20 players listed in Trending Up.

Here's the React:

        TRENDING UP
        {
          orderedPlayersUp.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }

        TRENDING DOWN
        {
          orderedPlayersDown.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }

Body:
The following code for screen size < 600 should work:

.playersColumns {
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding-top: 28px;
  align-items: center;
  flex-wrap: wrap;
}

It adds wrapping when the element doesn't fit next to another element and will move it to the next line.
It would be wise to make the elements itself have a width of 100% when using a smaller screen size.


问:
Python: navigate to directory, and insert command line on cmd window inside Python
I've read the documentations that other stackoverflow posts provided, but I couldn't understand what they are saying.

Here is what I want to achieve: I want to navigate to a specific directory that contains a specific executable file, and insert a command line.

So,

```<code>.\> cd C:\Program Files\MongoDB\Server\3.4\bin
C:\Program Files\MongoDB\Server\3.4\bin> mongoimport -h <IP_ADDRESS> -d <DB> -c <COLLECTION> -u <USER> -p <PASSWORD> --drop --file C:\data.txt
</code>```

I need a code will perform  the two lines of code above inside Python.
In .\3.4\bin directory, there is an executable file called 'mongoimport.exe'. And on the SAME LINE, I need to insert additional sentences to specify the external server I want to access.

How can this be done?

答:
You can use subprocess like:

```<code>from subprocess import run

run(["C:\\Program Files\\MongoDB\\Server\\3.4\\bin\\mongoimport.exe",  "-h", "<IP_ADDRESS>", "-d", "<DB>", "-c", "<COLLECTION>", "-u", "<USER>", "-p", "<PASSWORD>", "--drop", "--file", "C:\data.txt" ])
</code>```

It will execute only exe file, if for example you need execute a python file add the executable:

```<code>run(["python.exe", "your_python_file"])
</code>```

More information

Body:
I've read the documentations that other stackoverflow posts provided, but I couldn't understand what they are saying.

Here is what I want to achieve: I want to navigate to a specific directory that contains a specific executable file, and insert a command line.

So,

.\> cd C:\Program Files\MongoDB\Server\3.4\bin
C:\Program Files\MongoDB\Server\3.4\bin> mongoimport -h <IP_ADDRESS> -d <DB> -c <COLLECTION> -u <USER> -p <PASSWORD> --drop --file C:\data.txt

I need a code will perform  the two lines of code above inside Python.
In .\3.4\bin directory, there is an executable file called 'mongoimport.exe'. And on the SAME LINE, I need to insert additional sentences to specify the external server I want to access.

How can this be done?

Body:
You can use subprocess like:

from subprocess import run

run(["C:\\Program Files\\MongoDB\\Server\\3.4\\bin\\mongoimport.exe",  "-h", "<IP_ADDRESS>", "-d", "<DB>", "-c", "<COLLECTION>", "-u", "<USER>", "-p", "<PASSWORD>", "--drop", "--file", "C:\data.txt" ])

It will execute only exe file, if for example you need execute a python file add the executable:

run(["python.exe", "your_python_file"])

More information


问:
variable with "true" value does not meet [variable] == "true" javascript
I have a variable declared as true

```<code>var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false
</code>```

but in my function

```<code>function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}
</code>```

console return "true" but it still does not meet the condition of the if statement

答:
var g1 = sessionStorage.getItem("g1");

here the output type is string so you can not check like this

```<code>if (g1 == true) {
</code>```

chage your code to

```<code>if (g1 == "true") {
</code>```

or if you feel you are getting boolean value then do this

```<code>if (g1) {
 or
if (!g1) {
</code>```

Body:
I have a variable declared as true

var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false

but in my function

function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}

console return "true" but it still does not meet the condition of the if statement

Body:
var g1 = sessionStorage.getItem("g1");

here the output type is string so you can not check like this

if (g1 == true) {

chage your code to

if (g1 == "true") {

or if you feel you are getting boolean value then do this

if (g1) {
 or
if (!g1) {


问:
Content React.js won't load if i disable javascript in browser
I'm new to react. I want to ask why my React content lost if I disable javascript in browser. and one more thing, when I curl my localhost:3000 it is showing html with just script and styling and no content there. Any package or trick to fix this?

答:
React is powered by JavaScript.

If your browser does not support it (or you have disabled it) it can not evaluate your React JavaScript code and therefore display nothing.

What you can do is to write a fallback with a message to let your users know they have to enable JavaScript in order to view the page.

```<code><noscript>Please enable JavaScript to view this page</noscript>
</code>```

Place this line of code above your root element for attaching React, in most cases it will be

Body:
React is powered by JavaScript.

If your browser does not support it (or you have disabled it) it can not evaluate your React JavaScript code and therefore display nothing.

What you can do is to write a fallback with a message to let your users know they have to enable JavaScript in order to view the page.

<noscript>Please enable JavaScript to view this page</noscript>

Place this line of code above your root element for attaching React, in most cases it will be <div id="root"></div>


问:
Cloud Firestore in Firebase - Get all root level collections
How do I get all the collections from root level?

As I know that Cloud Firestore Console allow to add more than one collection on root level.

I found some solution to get documents of particular collection but I didn't get to know same thing for collections.

Is there any way to get all collection name of root level?

答:
There is no API in the Firebase SDKs for iterating collections.  Similarly, there is no API for iterating subcollections of a document.  You must know the name of a collection ahead of time to use it on the client.

If you're using the Admin SDK for Node, which wraps the Google Cloud Firestore SDK, there is an API Firestore.getCollections() that will do what you want.


问:
Notify user when a date is near
I'm currently working on an Android app that uses several Firebase functions. In the Realtime Database I have a date (the date a book is due) and I need to notify the user when that date is near (say, 1 day before the date in the database). Firebase cloud functions doesn't seem to have a specific trigger to do this, as nothing in the database is changing.

I have seen this thread, which can set an alarm/notification for a future date, but I don't know how to stop it once it's been set; I need to be able to cancel the notification if they return the book. This does trigger a change in the database, so I would have an event to use to cancel it, if there was a way to do so.

Is this the best way to do this, or is there a way to implement it using Firebase? And if this is the way to go, how would I cancel a scheduled notification?

答:
Coming from the Reddit post you made, use a Job Scheduling tool like JobScheduler (API 21+), Firebase JobDispatcher (API 9+) or Evernote's Android Job (API 14+ but no Google Play Services required).

Since your Firebase Realtime DB is available locally, you have the date (and possibly the time) of when you want to show the notification. One of the job schedulers can simply run a Job which shows a notification, no internet or no server required.

Also, Job scheduling is recommended because, with Android Oreo & above (26+), background tasks have more restrictions on execution.

Title: Notify user when a date is near


问:
firebase realtime schema design
i have two set of entities in my firebase realtime schema. Called Orders and customers.

so far i was not actually relating them in my app but was just showing them related. the current schema looked like:

```<code>{
"orders" : [
             {"id" : 1, "name": "abc", "price": 200, "customer": "vik"}
           ],
"customers" : [
                 {"cust_id" : "10", "name" : "vik", "type": "existing"}
               ]
}
</code>```

so i have a orders list page showing all the orders in a table  which i get firing /orders.json

But practically, instead of having the customer name directly in the orders i should have cust_id attribute as that is the key.

That naturally makes it a standard relational schema where i will be free to change customer attributes without worrying about mismatch in orders.

However, the downside i see right away is that if i have say 20 orders to show in the order list table then instead of 1 i will end up firing 21 rest calls (1 to get order list and 20 to fetch customer name for each of the order)

What are the recommendations or standards around this ?

答:
Firebase is a NoSQL database. So the rules of normalization that you know from relational databases don't necessarily apply.

For example: having the customer name in each order is actually quite normal. It saves having to do a client-side join for each customer record, significantly simplifying the code and improving the speed of the operation. But of course it comes at the cost of having to store data multiple times (quite normal in NoSQL databases), and having to consider if/how you update the duplicated data in case of updates of the customer record.

I recommend reading NoSQL data modeling, watching Firebase for SQL developers, and reading my answer on keeping denormalized data up to date.

Title: firebase realtime schema design

Body:
i have two set of entities in my firebase realtime schema. Called Orders and customers.

so far i was not actually relating them in my app but was just showing them related. the current schema looked like:

{
"orders" : [
             {"id" : 1, "name": "abc", "price": 200, "customer": "vik"}
           ],
"customers" : [
                 {"cust_id" : "10", "name" : "vik", "type": "existing"}
               ]
}

so i have a orders list page showing all the orders in a table  which i get firing /orders.json

But practically, instead of having the customer name directly in the orders i should have cust_id attribute as that is the key.

That naturally makes it a standard relational schema where i will be free to change customer attributes without worrying about mismatch in orders.

However, the downside i see right away is that if i have say 20 orders to show in the order list table then instead of 1 i will end up firing 21 rest calls (1 to get order list and 20 to fetch customer name for each of the order)

What are the recommendations or standards around this ?


问:
How to Disable UWP App Suspension?
I am using C# to develop a UWP app for Windows 10 running only on desktop computers, targeting platform version 10.0.14393.0. Due to business requirements, the app lifecycle must behave like a traditional Win32 application.

Therefore, I followed the recommendation from this article to request an ExtendedExecutionSession  with ExtendedExecutionReason.Unspecified. I also configured Windows to never sleep and never hibernate.

Still, on rare occasions, Windows will revoke the extended execution session with reason SystemPolicy and then proceed to suspend the UWP app.

Two questions:

How can I get more information (system logs? event logs?) regarding what led to Windows revoking the extended execution session?

How can I get rid of these rare cases of suspensions so that the UWP app lifecycle behaves exactly like Win32 applications (that is, stay running until user explicitly stops it from running)?

Thanks!

答:
ExtendedExecutionSession with ExtendedExecutionReason.Unspecified is a subject to multiple restrictions regarding resource consumption. Since your test device doesn't have a battery, then the most likely reason for your app getting suspended is its high memory use. You can try to optimize the app in terms of memory consumption and make use of Memory Management APIs as documentation suggests, but still this doesn't guarantee that your app will never get suspended.

If your app is aimed at business sector then you might consider using more powerful ExtendedExecutionForegroundSession instead of ExtendedExecutionSession. This would probably be the perfect solution for your problem. But it's a restricted capability, which means an app that utilizes it is not allowed to Windows Store - only to Windows Store for Business. You'd also need to manually declare the extendedExecutionUnconstrained capability in the manifest (see the Special and restricted capabilities section of documentation) to take advantage of the API.

Alternatively you can use hacks that prevent app from getting suspended for long periods of time:

Use of App services for communicating with Win32 apps as pnp0a03 suggested.

Use Background Media Playback for playing silent audio sample in the background infinitely in a loop (even if the user stops it manually or another app pauses it to play its own background audio, your app can trace it and automatically restart the playback).

Title: How to Disable UWP App Suspension?


问:
Angular 2 unit test case using Function not provider
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

```<code>import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

Code for isSameDay function

```<code>export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};
</code>```

答:
If you need to test isSameDay function, you could convert it into a service and treat it the same as any other service. Just like LoggerService in your case.

The benefit with this approach is that you can test your function/service in isolation.

When writing component tests, you can always mock this new service call. Again,this helps you test your component in isolation.

Body:
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});

Code for isSameDay function

export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};


问:
How to add a ContextMenu in the WPF DataGridColumn in MVVM?
I've got a tricky issue regarding ContextMenu in a WPF DataGridColumn. I don't know if someone have already face this issue but I will really appreciate if someone can help me!

Let's start by my classes

```<code>public class Person
{
    public string Type { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

public class Menu
{
    public string Name { get; set; }
    public int Code { get; set; }
    public ObservableCollection<Menu> listMenu { get; set; }
}
</code>```

Now my ViewModel

```<code> public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Person> DataPersons = new ObservableCollection<Person>();
    private ObservableCollection<Menu> DataMenu = new ObservableCollection<Menu>();

    public ObservableCollection<Person> listDataPersons { get; set; }
    public ObservableCollection<Menu> listDataMenu { get; set; }

    public MyViewModel()
    {
        //initialization
        InitData();
    }

    private void InitData()
    {
        listDataPersons = new ObservableCollection<Person>();
        listDataMenu = new ObservableCollection<Menu>();

        DataPersons.Add(new Person() { Type = "Friend", Name = "Doe", Surname = "John", Age = 42});
        DataPersons.Add(new Person() { Type = "Friend", Name = "Smith", Surname = "Jack", Age = 42});

        DataMenu.Add(new Menu() { Name = "Principal", Code = 1});
        DataMenu.Add(new Menu() { Name = "Secondary", Code = 2});
        DataMenu.Add(new Menu() { Name = "Associated", Code = 3});

        DataMenu[2].listMenu = new ObservableCollection<Menu>();
        DataMenu[2].listMenu.Add(new Menu() { Name = "Associated 1", Code = 31 });

        listDataPersons = DataPersons;
        listDataMenu = DataMenu;
    }}
</code>```

Here are my View and it's code behind

```<code><DataGrid ItemsSource="{Binding listDataPersons}" AutoGenerateColumns="False">
    <DataGrid.ContextMenu>
        <ContextMenu ItemsSource="{Binding listDataMenu}"/>
    </DataGrid.ContextMenu>
    <DataGrid.Columns>
        <DataGridTemplateColumn IsReadOnly="True" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" Width="80" >
                    <TextBlock.ContextMenu>
                        <ContextMenu ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}, Path=DataContext.listDataMenu}"/>
                    </TextBlock.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

code behind

```<code>public partial class MyView : UserControl
{
    public MyView()
    {
        InitializeComponent();

        this.DataContext = new MyViewModel();
    }
}
</code>```

What I wanted in this example is to have a dynamic ContextMenu in DataGridColumn. First I put a ContextMenu in the entire DataGrid and it works fine. But in my case I need a ContextMenu only on a right click in Cells not in the entire DataGrid. So I tried to edit DataGridColumn's DataTemplate with a TextBox which has a ContextMenu. Unfortunately when I right click in the TextBox it's ContextMenu's ItemsSource seem to be empty. However when I right click outside the TextBox in the DataGrid, the DataGrid's ContextMenu is correctly binded.

I was thinking that it might be a problem of DataContext because ContextMenu and DataGrid do not have the same Visual Tree so I added RelativeSource in the ContextMenu's ItemsSource binding but no result!!!

Any idea?

答:
Even though I need the same contextMenu for each row in Datagrid, I tried you suggestion and can't make it works:( May be I forgot somthing

Hear we are I modify my classes like this :

```<code>    public class Person
{
    public string Type { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public Column Column { get; set; }
}

public class Menu
{
    public string Name { get; set; }
    public int Code { get; set; }
    public ObservableCollection<Menu> listMenu { get; set; }
}
public class Column
{
    public ObservableCollection<Menu> listDatatMenu { get; set; }
}
</code>```

Then I change InitData function in my ViewModel like:

```<code>private void InitData()
    {
        listDataPersons = new List<Person>();
        listDataMenu = new ObservableCollection<Menu>();

        DataPersons.Add(new Person() { Type = "Friend", Name = "Doe", Surname = "John", Age = 42});
        DataPersons.Add(new Person() { Type = "Friend", Name = "Smith", Surname = "Jack", Age = 42});

        DataMenu.Add(new Menu() { Name = "Principal", Code = 1});
        DataMenu.Add(new Menu() { Name = "Secondary", Code = 2});
        DataMenu.Add(new Menu() { Name = "Associated", Code = 3});

        DataMenu[2].listMenu = new ObservableCollection<Menu>();
        DataMenu[2].listMenu.Add(new Menu() { Name = "Associated 1", Code = 31 });

        DataPersons[0].Column = new Column();
        DataPersons[0].Column.listDatatMenu = DataMenu;

        DataPersons[1].Column = new Column();
        DataPersons[1].Column.listDatatMenu = DataMenu;

        listDataPersons = DataPersons;
        listDataMenu = DataMenu;
    }
</code>```

And finally the ContextMenu in my View

```<code><ContextMenu ItemsSource="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext.Column.listDataMenu}"/>
</code>```

Feel sorry if I made a rookie mistake but it does work

Body:
I've got a tricky issue regarding ContextMenu in a WPF DataGridColumn. I don't know if someone have already face this issue but I will really appreciate if someone can help me!

Let's start by my classes

public class Person
{
    public string Type { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

public class Menu
{
    public string Name { get; set; }
    public int Code { get; set; }
    public ObservableCollection<Menu> listMenu { get; set; }
}

Now my ViewModel

 public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Person> DataPersons = new ObservableCollection<Person>();
    private ObservableCollection<Menu> DataMenu = new ObservableCollection<Menu>();

    public ObservableCollection<Person> listDataPersons { get; set; }
    public ObservableCollection<Menu> listDataMenu { get; set; }

    public MyViewModel()
    {
        //initialization
        InitData();
    }

    private void InitData()
    {
        listDataPersons = new ObservableCollection<Person>();
        listDataMenu = new ObservableCollection<Menu>();

        DataPersons.Add(new Person() { Type = "Friend", Name = "Doe", Surname = "John", Age = 42});
        DataPersons.Add(new Person() { Type = "Friend", Name = "Smith", Surname = "Jack", Age = 42});

        DataMenu.Add(new Menu() { Name = "Principal", Code = 1});
        DataMenu.Add(new Menu() { Name = "Secondary", Code = 2});
        DataMenu.Add(new Menu() { Name = "Associated", Code = 3});

        DataMenu[2].listMenu = new ObservableCollection<Menu>();
        DataMenu[2].listMenu.Add(new Menu() { Name = "Associated 1", Code = 31 });

        listDataPersons = DataPersons;
        listDataMenu = DataMenu;
    }}

Here are my View and it's code behind

<DataGrid ItemsSource="{Binding listDataPersons}" AutoGenerateColumns="False">
    <DataGrid.ContextMenu>
        <ContextMenu ItemsSource="{Binding listDataMenu}"/>
    </DataGrid.ContextMenu>
    <DataGrid.Columns>
        <DataGridTemplateColumn IsReadOnly="True" Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" Width="80" >
                    <TextBlock.ContextMenu>
                        <ContextMenu ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridCell}}, Path=DataContext.listDataMenu}"/>
                    </TextBlock.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

code behind

public partial class MyView : UserControl
{
    public MyView()
    {
        InitializeComponent();

        this.DataContext = new MyViewModel();
    }
}

What I wanted in this example is to have a dynamic ContextMenu in DataGridColumn. First I put a ContextMenu in the entire DataGrid and it works fine. But in my case I need a ContextMenu only on a right click in Cells not in the entire DataGrid. So I tried to edit DataGridColumn's DataTemplate with a TextBox which has a ContextMenu. Unfortunately when I right click in the TextBox it's ContextMenu's ItemsSource seem to be empty. However when I right click outside the TextBox in the DataGrid, the DataGrid's ContextMenu is correctly binded.

I was thinking that it might be a problem of DataContext because ContextMenu and DataGrid do not have the same Visual Tree so I added RelativeSource in the ContextMenu's ItemsSource binding but no result!!!

Any idea?

Body:
Even though I need the same contextMenu for each row in Datagrid, I tried you suggestion and can't make it works:( May be I forgot somthing

Hear we are I modify my classes like this :

    public class Person
{
    public string Type { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public Column Column { get; set; }
}

public class Menu
{
    public string Name { get; set; }
    public int Code { get; set; }
    public ObservableCollection<Menu> listMenu { get; set; }
}
public class Column
{
    public ObservableCollection<Menu> listDatatMenu { get; set; }
}

Then I change InitData function in my ViewModel like:

private void InitData()
    {
        listDataPersons = new List<Person>();
        listDataMenu = new ObservableCollection<Menu>();

        DataPersons.Add(new Person() { Type = "Friend", Name = "Doe", Surname = "John", Age = 42});
        DataPersons.Add(new Person() { Type = "Friend", Name = "Smith", Surname = "Jack", Age = 42});

        DataMenu.Add(new Menu() { Name = "Principal", Code = 1});
        DataMenu.Add(new Menu() { Name = "Secondary", Code = 2});
        DataMenu.Add(new Menu() { Name = "Associated", Code = 3});

        DataMenu[2].listMenu = new ObservableCollection<Menu>();
        DataMenu[2].listMenu.Add(new Menu() { Name = "Associated 1", Code = 31 });

        DataPersons[0].Column = new Column();
        DataPersons[0].Column.listDatatMenu = DataMenu;

        DataPersons[1].Column = new Column();
        DataPersons[1].Column.listDatatMenu = DataMenu;

        listDataPersons = DataPersons;
        listDataMenu = DataMenu;
    }

And finally the ContextMenu in my View

<ContextMenu ItemsSource="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext.Column.listDataMenu}"/>

Feel sorry if I made a rookie mistake but it does work


问:
How to vertically center differently-sized hintText in TextField?
I have a TextField like this, where the input text and the hint text are sized differently.

```<code>TextField(
    style: Theme.of(context).textTheme.subhead.copyWith(
      fontSize: 70.0,
    ),
    decoration: InputDecoration(
      hintText: 'Enter a number',
      hideDivider: true,
      hintStyle: TextStyle(
        color: Colors.grey[500],
        fontSize: 25.0,
      ),
    ),
);
</code>```

While the user input text is centered in my parent container, the hintText is not (top has more space than the bottom). Is there a way to vertically center the hint text as well?

The reason the hint text is not the same size as the input text is that it takes up more space than the green Container has, so it looks like Enter a nu..., which isn't very user friendly. (So alternatively, is there a way to have a newline in the hintText?)

答:
```<code>new TextField(
  decoration: new InputDecoration(
    hintText: 'your hint',
  ),
  textAlign: TextAlign.center,
)
</code>```

textAlign: TextAlign.center will make your hint appear in the center.

ContentLicense: CC BY-SA 4.0

Body:
I have a TextField like this, where the input text and the hint text are sized differently.

TextField(
    style: Theme.of(context).textTheme.subhead.copyWith(
      fontSize: 70.0,
    ),
    decoration: InputDecoration(
      hintText: 'Enter a number',
      hideDivider: true,
      hintStyle: TextStyle(
        color: Colors.grey[500],
        fontSize: 25.0,
      ),
    ),
);

While the user input text is centered in my parent container, the hintText is not (top has more space than the bottom). Is there a way to vertically center the hint text as well?

The reason the hint text is not the same size as the input text is that it takes up more space than the green Container has, so it looks like Enter a nu..., which isn't very user friendly. (So alternatively, is there a way to have a newline in the hintText?)

Body:
new TextField(
  decoration: new InputDecoration(
    hintText: 'your hint',
  ),
  textAlign: TextAlign.center,
)

textAlign: TextAlign.center will make your hint appear in the center.


问:
Flask, Google Kubernete Cluster + Docker
I have an issue right now where I'm really not sure what's going on. On Google Cloud I have a cluster that contains two instances. Using Kubernetes I have 2 pods running, one on each machine. When I go to log into the application (using the ExternalIP of the LoadBalancer service) with a persisted user sometimes it just straight up fails to do so and redirects to my homepage. Other times it will log me in.

If however, I scale my application down to a single VM and one pod it works okay and will sign me in every time. Because of this I don't think it's an issue with Flask i.e my application, but something else. It's like when I try to sign in I'm on one machine and when I execute the request the load-balancer picks the other machine and it fails to sign me in, then sometimes it lucks out and gets the same one twice in a row. I don't really even know if that's something that's really even possible, it just what it seems like to me, but then again I'm quite new to all this.

https://github.com/tnolan8/CA674-Cloud-Architecture -> this is the repo which contains my application + my deployment scripts.

This is my actual deployment script: deployment.yml

I'm at a loss as to what might actually be causing this. Any thoughts?

答:
TL;DR
It seems like you're using sqlalchemy to store your 'database' state on
disk.

You should create a database deployment and change your config to use that database instead.

Details:

When you're using containers that you want to scale up and down you shouldn't use the disk because different containers will have different state (container1 thinks you're logged in, container2 thinks you're not because it's disk does not have that data)

Containers should be resilient to frequent restarts. This means that you should not store anything on disk that you'll need after you restart. If you really need to, you should look at persistent volumes for your containers. However, PVs need to be used carefully when you need to change the number replicas that your containers are using frequently.


问:
How to run or debug php on Visual Studio Code (VSCode)
I can't find a way to run or debug php on Visual studio code, Does anyone know how?</p>

答:
There is a much easier way to run PHP, no configuration needed:

Install the Code Runner Extension

Open the PHP code file in Text Editor

use shortcut Ctrl+Alt+N

or press F1 and then select/type Run Code,

or right click the Text Editor and then click Run Code in editor context menu

or click Run Code button in editor title menu

or click Run Code button in context menu of file explorer

Besides, you could select part of the PHP code and run the code snippet. Very convenient!


问:
Push plugin notification for apache cordova android app using phonegap-plugin-push
I have an android app built on apache cordova. I want push notifications for this application. I have used Visual studio 2015 IDE to built this application.
I have already installed some plugins for this application like cordova-plugin-device-orientation, statusbar etc. To enable push notifications for this app I have installed phonegap-plugin-push (version 2.1.0) and provided the sender Id for my application which I created using Firebase. By creating new project, added android app, downloaded google-services.json file and placed it in my project.

```

I found this code here.

答:
What is your cordova CLI and cordova platform android version?
I am using 6.2.3 android version and it run normally.

Please try to install the plugin first, after all the plugin install success than install the android platform for project.

Body:
I have an android app built on apache cordova. I want push notifications for this application. I have used Visual studio 2015 IDE to built this application.
I have already installed some plugins for this application like cordova-plugin-device-orientation, statusbar etc. To enable push notifications for this app I have installed phonegap-plugin-push (version 2.1.0) and provided the sender Id for my application which I created using Firebase. By creating new project, added android app, downloaded google-services.json file and placed it in my project.

I found this code here.


问:
An issue of C in 64 bit architecture: pthread_kill()
The question is quite simple: my application runs perfectly on a 32 bit architecture, but on a 64 bit arch. I got segmentation fault. I guess that the cause is the execution of a pthread_kill() call. Is it possible or my supposition is just wrong?

答:
What operating system and what glibc are you using?

If you're using a mainstream implementation of pthread (say a recent GNU glibc on Linux) I'm quite sure they're not broken.

I think that your crash is likely due to some problem in your code or maybe to an incorrect mixing of 32bit and 64bit binary code.

Could you try to reproduce your crash with as little code lines as possible and paste it here?


问:
How to get an ActorRef from "this"
Lets say you have an actor class:

```<code>class MyActor extends Actor { }
</code>```

And somewhere within MyActor, you'd like to pass it to another actor.  But, you need "this" as an ActorRef.  Since "this" is of type Actor, it can not be passed where ActorRef is required.

So the question is, how can an Actor ("this") get a reference to itself as an ActorRef?  Is this even possible, or am I totally misunderstanding something...

答:
If you know the path of an actor and you want to know its ActorRef then you can obtain it. You just have to create an actor using the actor selection and then send an Identity(none) message to that actor. It will send its ActorRefas a reply.

You find a more detailed explanation here: https://doc.akka.io/docs/akka/snapshot/actors.html

Title: How to get an ActorRef from "this"

Body:
Lets say you have an actor class:

class MyActor extends Actor { }

And somewhere within MyActor, you'd like to pass it to another actor.  But, you need "this" as an ActorRef.  Since "this" is of type Actor, it can not be passed where ActorRef is required.

So the question is, how can an Actor ("this") get a reference to itself as an ActorRef?  Is this even possible, or am I totally misunderstanding something...


问:
How to change part of HTML 'form action: link' elements using Java script or html ID
I have a link to a database in the server and I'm using an HTML form where the action points to the link and GET the information from the server.

I need to change the 'username' part of the link so that it takes in the username i enter and uses it in the link.
What's the best way to achieve something like this?

```<code><body>

        <form id = "me" action= "http://10.10.10.10/foods/<username>/" target="_blank"  method="GET">
            <h2>Enter Username</h2>
                <input type="text" name="user" placeholder="username" id = "user" >
                <br>
            <button class="button" type="submit" value="Submit" >get</button>
        </form>
        <script>
          var username = //need to get input username;
           document.getElementById('me').action = "http://10.10.10.10/foods/" + username + "/";
</script>
</BODY>
</code>```

this is all i have so far and i am stuck

答:
Do this simple submit event</p>

```<code> $('#me').submit(function(e){
  e.preventDefault();//prevent the submit
  var username = $(this).find('#user').val();//take the username
  window.location = "http://10.10.10.10/foods/" + username + "/";//redirect to the page
})
</code>```

Body:
I have a link to a database in the server and I'm using an HTML form where the action points to the link and GET the information from the server.

I need to change the 'username' part of the link so that it takes in the username i enter and uses it in the link.
What's the best way to achieve something like this?

        <form id = "me" action= "http://10.10.10.10/foods/<username>/" target="_blank"  method="GET">

Enter Username

                <input type="text" name="user" placeholder="username" id = "user" >

            <button class="button" type="submit" value="Submit" >get</button>
        </form>

this is all i have so far and i am stuck

Body:
Do this simple submit event

 $('#me').submit(function(e){
  e.preventDefault();//prevent the submit
  var username = $(this).find('#user').val();//take the username
  window.location = "http://10.10.10.10/foods/" + username + "/";//redirect to the page
})


问:
Fixed size div which sits to the right of a main div that fills up remainder of screen
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

```<code>+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+
</code>```

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

```<code>#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}
</code>```

答:
You need to put the right panel before the main content if you float it:

```<code><div id="rightpanel">blah blah blah</div>
<div id="mainbody">blah blah blah
    blah blah blah
    blah blah blah
</div>

<style type="text/css">
    #rightpanel {
        width:210px;
        float:right;
        background-color:red;
    }
    #mainbody {
       margin-right:210px;
       background-color:blue;
    }
</style>
</code>```

This will keep the right-hand panel aligned properly even if the page is resized.

Body:
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}

Body:
You need to put the right panel before the main content if you float it:

<div id="rightpanel">blah blah blah</div>
<div id="mainbody">blah blah blah
    blah blah blah
    blah blah blah
</div>

<style type="text/css">
    #rightpanel {
        width:210px;
        float:right;
        background-color:red;
    }
    #mainbody {
       margin-right:210px;
       background-color:blue;
    }
</style>

This will keep the right-hand panel aligned properly even if the page is resized.


问:
Find out the recently selected rows from a Oracle table and can I update a LAST_ACCESSED column whenever the table is accessed
I have a database table which have more than 1 million records uniquely identified by a GUID column. I want to find out which of these record or rows was selected or retrieved in the last 5 years. The select query can happen from multiple places. Sometimes the row will be returned as a single row. Sometimes it will be part of a set of rows. there is select query that does the fetching from a jdbc connection from a java code. Also a SQL procedure also fetches data from the table.

My intention is to clean up a database table.I want to delete all rows which was never used( retrieved via select query) in last 5 years.

Does oracle DB have any inbuild meta data which can give me this information.

My alternative solution was to add a column LAST_ACCESSED and update this column whenever I select a row from this table. But this operation is a costly operation for me based on time taken for the whole process. Atleast 1000 - 10000 records will be selected from the table for a single operation. Is there any efficient way to do this rather than updating table after reading it. Mine is a multi threaded application. so update such large data set may result in deadlocks or large waiting period for the next read query.

Any elegant solution to this problem?

答:
I couldn't use any inbuild solutions. i tried below solutions
1)DB audit feature for select statements.
2)adding a trigger to update a date column whenever a select query is executed on the table.

Both were discarded. Audit uses up a lot of space and have performance hit. Similary trigger also had performance hit.

Finally i resolved the issue by maintaining a separate table were entries older than 5 years that are still used or selected in a query are inserted. While deleting I cross check this table and avoid deleting entries present in this table.


问:
Swift: How to get first string of array in plist?
I have a plist that is an array containing hundreds of arrays, each containing 22 strings. How do I get the first string of each array in the plist?

I'm using collections and in cellForItemAt I'm trying to get the first string of the arrays to show under each cell in a label.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")

    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = (??) // <--------------

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}
</code>```

I have 2 types of plists:

First plist has 1 array with multiple strings. Each string is a name that goes under the cells.

Second plist is an array of arrays, each array containing 22 strings. Here I need to get only the first string from each array to show under the cells.

答:
You need to parse your plist into Array of Array of Strings i.e. [[String]].

```<code>func arrayFromPlist(plist:String) -> [[String]]? {
    guard let fileUrl = Bundle.main.url(forResource: plist, withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) else {
        return nil
    }

    return try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String]]
}
</code>```

Use above function to get the array and use the array as a datasource to tableview.

```<code>var datasourceArray:[[String]] {
    didSet {
        self.tableView.reloadData()
    }
}
</code>```

In your cellForRow:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")
    let strings = datasourceArray[indexPath.row]!
    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = strings.first

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}
</code>```

Body:
I have a plist that is an array containing hundreds of arrays, each containing 22 strings. How do I get the first string of each array in the plist?

I'm using collections and in cellForItemAt I'm trying to get the first string of the arrays to show under each cell in a label.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")

    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = (??) // <--------------

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}

I have 2 types of plists:

First plist has 1 array with multiple strings. Each string is a name that goes under the cells.

Second plist is an array of arrays, each array containing 22 strings. Here I need to get only the first string from each array to show under the cells.

Body:
You need to parse your plist into Array of Array of Strings i.e. [[String]].

func arrayFromPlist(plist:String) -> [[String]]? {
    guard let fileUrl = Bundle.main.url(forResource: plist, withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) else {
        return nil
    }

    return try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String]]
}

Use above function to get the array and use the array as a datasource to tableview.

var datasourceArray:[[String]] {
    didSet {
        self.tableView.reloadData()
    }
}

In your cellForRow:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Collections

    // Set Image
    cell.imageCell.image = UIImage(named: "image_\(indexPath.row)")
    let strings = datasourceArray[indexPath.row]!
    // Check NameLabel Switch Status
    if savedSwitchStatus == true {

        cell.labelCell.isHidden = false
        cell.labelCell.text = strings.first

    } else {
        cell.labelCell.isHidden = true
    }

    return cell
}


问:
google cloud function to firebase database with storage trigger
I want to create a cloud function triggered by a storage trigger which writes data into a firebase database. It seems that only during a database trigger can the cloud function talk to the firebase database.

So I want to know does anyone have an example for that or tell me if it is possible for a Google Cloud function to do it?

Thanks.

答: Cloud Functions can be triggered from uploads to Cloud Storage, or through writes to the Firebase Realtime Database. The samples repo on Github has examples for both.</p>


问:
How to debug a stackoverflowexception in .NET
Scenario:

I've just been on a roll and implemented a bunch of code, but when I execute it I get thrown a StackOverflowException? The StackOverflowException doesn't have a stacktrace so I'm stuck. I know why a stack overflow might occur, but to fix it I need to know where it's root is.

All I'm getting is: An unhandled exception of type 'System.StackOverflowException' occurred in tag-you're-it.dll

Options:

Scan through all the changes and try to pin point the problem. (could be slow)

Use a debugger and step through till you find the problem. (probably better than 1.)

Use a profile and look for the most called methods.

?

PS:

This is a hypothetical situation (although not too uncommon) and therefore no code is available.

答:
This is almost always due to recursion. Either a method calling itself, or a method calling a method that calls it back and so on.

To find it:

UPDATED: I didn't realise, but apparently you can't get the stack trace for a StackOverflowException (I guess something to do with not being able to catch one, either). However there are ways to get a dump as mentioned here.

ReSharper will show methods that call themselves (it puts a little green circle in the sidebar for recursive calls) though it won't catch recursion where two or more methods are involved.

Use a tool like ANTS Profiler to see which methods are called the most times.

Keep an eye out for events that fire that might call code that means the same event fires again, causing a loop.

Occasionally you'll get typos like this, too:

```<code>private string name;

public string Name
{
    get { return Name; } // Ooops! This is recursive, all because of a typo...
}
</code>```

Which is one reason why I personally now prefer to use automatic properties.

Body:
This is almost always due to recursion. Either a method calling itself, or a method calling a method that calls it back and so on.

To find it:

UPDATED: I didn't realise, but apparently you can't get the stack trace for a StackOverflowException (I guess something to do with not being able to catch one, either). However there are ways to get a dump as mentioned here.

ReSharper will show methods that call themselves (it puts a little green circle in the sidebar for recursive calls) though it won't catch recursion where two or more methods are involved.

Use a tool like ANTS Profiler to see which methods are called the most times.

Keep an eye out for events that fire that might call code that means the same event fires again, causing a loop.

Occasionally you'll get typos like this, too:

private string name;

public string Name
{
    get { return Name; } // Ooops! This is recursive, all because of a typo...
}

Which is one reason why I personally now prefer to use automatic properties.


答: I just used indexPath.row on the array of the plist and matched it.

Title: Swift: How to get first string of array in plist?


问:
How to write a sql show the quantity result based on filter and merge two different column if no filtering option?
Table

```<code>|---------------------|------------------|------------------|
|          ID         |   qty_ordered    |   qty_received   |
|---------------------|------------------|------------------|
|          10         |         30       |                  |
|---------------------|------------------|------------------|
|          10         |         30       |         20       |
|---------------------|------------------|------------------|
</code>```

I have a filter to let user choose whether to show qty_ordered or qty_received. When user select filter for qty_ordered then result will be 30 else if select qty_received then result will be 20 else will return 50.

SQL

```<code>select sum(qty_ordered) as order, sum(qty_received) as received from table...
</code>```

Currently i will select both, and using if-else statement in my html to show the result of quantity. If filtering by qty_ordered and qty_received will be fine, but problem occurred when need to display all quantity. Mean, i need to merge ordered quantity and received quantity with same id as one row.

```<code>|---------------------|------------------|
|          ID         |     quantity     |
|---------------------|------------------|
|          10         |         50       |
|---------------------|------------------|
</code>```

ps: Ordered quantity will only be sum up if there is no received quantity.

答:
You can try aggregating by the ID and using SUM to obtain single values for the quantity ordered and received:

```<code>SELECT
    ID,
    SUM(qty_ordered) AS qty_ordered,
    SUM(qty_received) AS qty_received,
    SUM(COALESCE(qty_received, qty_ordered)) AS qty_total
FROM yourTable
GROUP BY ID;

    ID  qty_ordered qty_received qty_total
1   10  60          20           50
</code>```

I use a COALESCE trick in the expression for the total sum.  The logic is that if the quantity received is present, we count it, even if the quantity ordered might also be present.  If the quantity received be absent, only then do we count the quantity ordered.

Demo

Body:
Table

|---------------------|------------------|------------------|
|          ID         |   qty_ordered    |   qty_received   |
|---------------------|------------------|------------------|
|          10         |         30       |                  |
|---------------------|------------------|------------------|
|          10         |         30       |         20       |
|---------------------|------------------|------------------|

I have a filter to let user choose whether to show qty_ordered or qty_received. When user select filter for qty_ordered then result will be 30 else if select qty_received then result will be 20 else will return 50.

SQL

select sum(qty_ordered) as order, sum(qty_received) as received from table...

Currently i will select both, and using if-else statement in my html to show the result of quantity. If filtering by qty_ordered and qty_received will be fine, but problem occurred when need to display all quantity. Mean, i need to merge ordered quantity and received quantity with same id as one row.

|---------------------|------------------|
|          ID         |     quantity     |
|---------------------|------------------|
|          10         |         50       |
|---------------------|------------------|

ps: Ordered quantity will only be sum up if there is no received quantity.

Body:
You can try aggregating by the ID and using SUM to obtain single values for the quantity ordered and received:

SELECT
    ID,
    SUM(qty_ordered) AS qty_ordered,
    SUM(qty_received) AS qty_received,
    SUM(COALESCE(qty_received, qty_ordered)) AS qty_total
FROM yourTable
GROUP BY ID;

    ID  qty_ordered qty_received qty_total
1   10  60          20           50

I use a COALESCE trick in the expression for the total sum.  The logic is that if the quantity received is present, we count it, even if the quantity ordered might also be present.  If the quantity received be absent, only then do we count the quantity ordered.

Demo


问:
Missing devise routes
```<code>Rails 5.1
Devise
</code>```

My routes.rb file:

```<code>Rails.application.routes.draw do

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  devise_for :users, controllers: {
      sessions: 'users/sessions',
      confirmations: 'users/confirmations',
      passwords: 'users/passwords',
      registrations: 'users/registrations',
      unlocks: 'users/unlocks',
      invitations: 'users/invitations'
  }

  root to: "landings#index"
  resources :users
  resources :followeds
  resources :followers
  resources :locations
  resources :fw_exports

  get 'import_spreadsheet', to: :upload_spreadsheet, controller: 'fw_exports'
  post 'parse_imported_spreadsheet_and_confirm', to: :process_imported_spreadsheet_and_confirm, controller: 'fw_exports'
  post 'process_parsed_spreadsheet', to: :process_parsed_spreadsheet, controller: 'fw_exports'

  scope module: :landings do
    get 'visitors'
  end

end
</code>```

When I generate routes, here's what I get:

```<code>                            Prefix Verb   URI Pattern                                       Controller#Action
                  new_user_session GET    /users/sign_in(.:format)                          users/sessions#new
                      user_session POST   /users/sign_in(.:format)                          users/sessions#create
              destroy_user_session DELETE /users/sign_out(.:format)                         users/sessions#destroy
                 new_user_password GET    /users/password/new(.:format)                     users/passwords#new
                edit_user_password GET    /users/password/edit(.:format)                    users/passwords#edit
                     user_password PATCH  /users/password(.:format)                         users/passwords#update
                                   PUT    /users/password(.:format)                         users/passwords#update
                                   POST   /users/password(.:format)                         users/passwords#create
          cancel_user_registration GET    /users/cancel(.:format)                           users/registrations#cancel
             new_user_registration GET    /users/sign_up(.:format)                          users/registrations#new
            edit_user_registration GET    /users/edit(.:format)                             users/registrations#edit
                 user_registration PATCH  /users(.:format)                                  users/registrations#update
                                   PUT    /users(.:format)                                  users/registrations#update
                                   DELETE /users(.:format)                                  users/registrations#destroy
                                   POST   /users(.:format)                                  users/registrations#create
            accept_user_invitation GET    /users/invitation/accept(.:format)                users/invitations#edit
            remove_user_invitation GET    /users/invitation/remove(.:format)                users/invitations#destroy
               new_user_invitation GET    /users/invitation/new(.:format)                   users/invitations#new
                   user_invitation PATCH  /users/invitation(.:format)                       users/invitations#update
                                   PUT    /users/invitation(.:format)                       users/invitations#update
                                   POST   /users/invitation(.:format)                       users/invitations#create
                              root GET    /                                                 landings#index
                             users GET    /users(.:format)                                  users#index
                                   POST   /users(.:format)                                  users#create
                          new_user GET    /users/new(.:format)                              users#new
                         edit_user GET    /users/:id/edit(.:format)                         users#edit
                              user GET    /users/:id(.:format)                              users#show
                                   PATCH  /users/:id(.:format)                              users#update
                                   PUT    /users/:id(.:format)                              users#update
                                   DELETE /users/:id(.:format)                              users#destroy
                         followeds GET    /followeds(.:format)                              followeds#index
                                   POST   /followeds(.:format)                              followeds#create
                      new_followed GET    /followeds/new(.:format)                          followeds#new
                     edit_followed GET    /followeds/:id/edit(.:format)                     followeds#edit
                          followed GET    /followeds/:id(.:format)                          followeds#show
                                   PATCH  /followeds/:id(.:format)                          followeds#update
                                   PUT    /followeds/:id(.:format)                          followeds#update
                                   DELETE /followeds/:id(.:format)                          followeds#destroy
                         followers GET    /followers(.:format)                              followers#index
                                   POST   /followers(.:format)                              followers#create
                      new_follower GET    /followers/new(.:format)                          followers#new
                     edit_follower GET    /followers/:id/edit(.:format)                     followers#edit
                          follower GET    /followers/:id(.:format)                          followers#show
                                   PATCH  /followers/:id(.:format)                          followers#update
                                   PUT    /followers/:id(.:format)                          followers#update
                                   DELETE /followers/:id(.:format)                          followers#destroy
                         locations GET    /locations(.:format)                              locations#index
                                   POST   /locations(.:format)                              locations#create
                      new_location GET    /locations/new(.:format)                          locations#new
                     edit_location GET    /locations/:id/edit(.:format)                     locations#edit
                          location GET    /locations/:id(.:format)                          locations#show
                                   PATCH  /locations/:id(.:format)                          locations#update
                                   PUT    /locations/:id(.:format)                          locations#update
                                   DELETE /locations/:id(.:format)                          locations#destroy
                        fw_exports GET    /fw_exports(.:format)                             fw_exports#index
                                   POST   /fw_exports(.:format)                             fw_exports#create
                     new_fw_export GET    /fw_exports/new(.:format)                         fw_exports#new
                    edit_fw_export GET    /fw_exports/:id/edit(.:format)                    fw_exports#edit
                         fw_export GET    /fw_exports/:id(.:format)                         fw_exports#show
                                   PATCH  /fw_exports/:id(.:format)                         fw_exports#update
                                   PUT    /fw_exports/:id(.:format)                         fw_exports#update
                                   DELETE /fw_exports/:id(.:format)                         fw_exports#destroy
                import_spreadsheet GET    /import_spreadsheet(.:format)                     fw_exports#import_spreadsheet
parse_imported_spreadsheet_and_confirm POST   /parse_imported_spreadsheet_and_confirm(.:format) fw_exports#parse_imported_spreadsheet_and_confirm
        process_parsed_spreadsheet POST   /process_parsed_spreadsheet(.:format)             fw_exports#process_parsed_spreadsheet
                          visitors GET    /visitors(.:format)                               landings#visitors
</code>```

Am I not supposed to also be getting routes for confirmatins and unlocks?

答:
The problem is you have commented the lockable & confirmable. You need to uncomment it inorder to make it work.

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  #   :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
end
</code>```

Title: Missing devise routes

Body:
Rails 5.1
Devise

My routes.rb file:

Rails.application.routes.draw do

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  devise_for :users, controllers: {
      sessions: 'users/sessions',
      confirmations: 'users/confirmations',
      passwords: 'users/passwords',
      registrations: 'users/registrations',
      unlocks: 'users/unlocks',
      invitations: 'users/invitations'
  }

  root to: "landings#index"
  resources :users
  resources :followeds
  resources :followers
  resources :locations
  resources :fw_exports

  get 'import_spreadsheet', to: :upload_spreadsheet, controller: 'fw_exports'
  post 'parse_imported_spreadsheet_and_confirm', to: :process_imported_spreadsheet_and_confirm, controller: 'fw_exports'
  post 'process_parsed_spreadsheet', to: :process_parsed_spreadsheet, controller: 'fw_exports'

  scope module: :landings do
    get 'visitors'
  end

end

When I generate routes, here's what I get:

                            Prefix Verb   URI Pattern                                       Controller#Action
                  new_user_session GET    /users/sign_in(.:format)                          users/sessions#new
                      user_session POST   /users/sign_in(.:format)                          users/sessions#create
              destroy_user_session DELETE /users/sign_out(.:format)                         users/sessions#destroy
                 new_user_password GET    /users/password/new(.:format)                     users/passwords#new
                edit_user_password GET    /users/password/edit(.:format)                    users/passwords#edit
                     user_password PATCH  /users/password(.:format)                         users/passwords#update
                                   PUT    /users/password(.:format)                         users/passwords#update
                                   POST   /users/password(.:format)                         users/passwords#create
          cancel_user_registration GET    /users/cancel(.:format)                           users/registrations#cancel
             new_user_registration GET    /users/sign_up(.:format)                          users/registrations#new
            edit_user_registration GET    /users/edit(.:format)                             users/registrations#edit
                 user_registration PATCH  /users(.:format)                                  users/registrations#update
                                   PUT    /users(.:format)                                  users/registrations#update
                                   DELETE /users(.:format)                                  users/registrations#destroy
                                   POST   /users(.:format)                                  users/registrations#create
            accept_user_invitation GET    /users/invitation/accept(.:format)                users/invitations#edit
            remove_user_invitation GET    /users/invitation/remove(.:format)                users/invitations#destroy
               new_user_invitation GET    /users/invitation/new(.:format)                   users/invitations#new
                   user_invitation PATCH  /users/invitation(.:format)                       users/invitations#update
                                   PUT    /users/invitation(.:format)                       users/invitations#update
                                   POST   /users/invitation(.:format)                       users/invitations#create
                              root GET    /                                                 landings#index
                             users GET    /users(.:format)                                  users#index
                                   POST   /users(.:format)                                  users#create
                          new_user GET    /users/new(.:format)                              users#new
                         edit_user GET    /users/:id/edit(.:format)                         users#edit
                              user GET    /users/:id(.:format)                              users#show
                                   PATCH  /users/:id(.:format)                              users#update
                                   PUT    /users/:id(.:format)                              users#update
                                   DELETE /users/:id(.:format)                              users#destroy
                         followeds GET    /followeds(.:format)                              followeds#index
                                   POST   /followeds(.:format)                              followeds#create
                      new_followed GET    /followeds/new(.:format)                          followeds#new
                     edit_followed GET    /followeds/:id/edit(.:format)                     followeds#edit
                          followed GET    /followeds/:id(.:format)                          followeds#show
                                   PATCH  /followeds/:id(.:format)                          followeds#update
                                   PUT    /followeds/:id(.:format)                          followeds#update
                                   DELETE /followeds/:id(.:format)                          followeds#destroy
                         followers GET    /followers(.:format)                              followers#index
                                   POST   /followers(.:format)                              followers#create
                      new_follower GET    /followers/new(.:format)                          followers#new
                     edit_follower GET    /followers/:id/edit(.:format)                     followers#edit
                          follower GET    /followers/:id(.:format)                          followers#show
                                   PATCH  /followers/:id(.:format)                          followers#update
                                   PUT    /followers/:id(.:format)                          followers#update
                                   DELETE /followers/:id(.:format)                          followers#destroy
                         locations GET    /locations(.:format)                              locations#index
                                   POST   /locations(.:format)                              locations#create
                      new_location GET    /locations/new(.:format)                          locations#new
                     edit_location GET    /locations/:id/edit(.:format)                     locations#edit
                          location GET    /locations/:id(.:format)                          locations#show
                                   PATCH  /locations/:id(.:format)                          locations#update
                                   PUT    /locations/:id(.:format)                          locations#update
                                   DELETE /locations/:id(.:format)                          locations#destroy
                        fw_exports GET    /fw_exports(.:format)                             fw_exports#index
                                   POST   /fw_exports(.:format)                             fw_exports#create
                     new_fw_export GET    /fw_exports/new(.:format)                         fw_exports#new
                    edit_fw_export GET    /fw_exports/:id/edit(.:format)                    fw_exports#edit
                         fw_export GET    /fw_exports/:id(.:format)                         fw_exports#show
                                   PATCH  /fw_exports/:id(.:format)                         fw_exports#update
                                   PUT    /fw_exports/:id(.:format)                         fw_exports#update
                                   DELETE /fw_exports/:id(.:format)                         fw_exports#destroy
                import_spreadsheet GET    /import_spreadsheet(.:format)                     fw_exports#import_spreadsheet
parse_imported_spreadsheet_and_confirm POST   /parse_imported_spreadsheet_and_confirm(.:format) fw_exports#parse_imported_spreadsheet_and_confirm
        process_parsed_spreadsheet POST   /process_parsed_spreadsheet(.:format)             fw_exports#process_parsed_spreadsheet
                          visitors GET    /visitors(.:format)                               landings#visitors

Am I not supposed to also be getting routes for confirmatins and unlocks?

Body:
The problem is you have commented the lockable & confirmable. You need to uncomment it inorder to make it work.

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  #   :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
end


问:
ember-pikaday does not create action when value is changed to null
I'm using ember-pikaday on my web application. I have faced a problem while I'm testing my date component. When the value is set to null, it does not create action, and the binding value remains the last setted value. This is my component:

```<code>{{pikaday-input onSelection=(action 'onSelection') }}
</code>```

This is my test.

```<code>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import moment from 'moment';

moduleForComponent('my-component', 'TODO: put something here', {
  integration: true
});

 function updateDateValue(_this, val){
   let datecomponent = _this.$('input');
   datecomponent.click();
   datecomponent.val(val);
   datecomponent[0].dispatchEvent(new Event('change'));
 }

  test('it renders', function(assert) {

  let actionListenerValue;
  this.on('myaction', function(val) { actionListenerValue=val; });

  this.render(hbs`{{my-component onSelection=(action 'myaction') }}`);

  updateDateValue(this, '01.04.2016');

  assert.equal(this.$('input').val(), '01.04.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '01.04.2016');

  updateDateValue(this, '05.02.2016');
  assert.equal(this.$('input').val(), '05.02.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '05.02.2016');

  updateDateValue(this, null);
  assert.notOk(this.$('input').val());
  assert.notOk(actionListenerValue); // this line throws error

});
</code>```

I have prepared a twiddle of my problem.

答:
I have found the answer on ember-pikaday's test codes.

The answer is to click anywhere in the context after setting value to null like this:

```<code>updateDateValue(this, null);
this.$().click();
</code>```

Body:
I'm using ember-pikaday on my web application. I have faced a problem while I'm testing my date component. When the value is set to null, it does not create action, and the binding value remains the last setted value. This is my component:

{{pikaday-input onSelection=(action 'onSelection') }}

This is my test.

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import moment from 'moment';

moduleForComponent('my-component', 'TODO: put something here', {
  integration: true
});

 function updateDateValue(_this, val){
   let datecomponent = _this.$('input');
   datecomponent.click();
   datecomponent.val(val);
   datecomponent[0].dispatchEvent(new Event('change'));
 }

  test('it renders', function(assert) {

  let actionListenerValue;
  this.on('myaction', function(val) { actionListenerValue=val; });

  this.render(hbs`{{my-component onSelection=(action 'myaction') }}`);

  updateDateValue(this, '01.04.2016');

  assert.equal(this.$('input').val(), '01.04.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '01.04.2016');

  updateDateValue(this, '05.02.2016');
  assert.equal(this.$('input').val(), '05.02.2016');
  assert.equal(moment(actionListenerValue).format('DD.MM.YYYY'), '05.02.2016');

  updateDateValue(this, null);
  assert.notOk(this.$('input').val());
  assert.notOk(actionListenerValue); // this line throws error

});

I have prepared a twiddle of my problem.

Body:
I have found the answer on ember-pikaday's test codes.

The answer is to click anywhere in the context after setting value to null like this:

updateDateValue(this, null);
this.$().click();