text:
Q: Show that the function $z\to \int_{\sqrt{5}}^{z} \frac{2w}{w^{2}-4}dw$ is well-defined in $\mathbb{C}\setminus [-2,2]$ Problem: Show that the function $z\to \displaystyle\int_{\sqrt{5}}^{z} \frac{2w}{w^{2}-4}dw$ is well-defined in $\mathbb{C}\setminus [-2,2].$
My approach to this problem was to prove that $\displaystyle\int_{\gamma} \frac{2w}{w^{2}-4}dw=0$ for every closed curve in $\mathbb{C}\setminus [-2,2]$, but when I took
$\gamma(t)=\sqrt{5}e^{it}$ for $t\in [0,2\pi]$, the result of the integral gave me 4$\pi i$. So this means that the function is not well-defined.
Can someone tell me if the integral is $0$ or $4\pi i$? Is the function well-defined?
I assume that this function is intended to be $\log(z^2 -4)$.

A: Chilote suggested that I turn my old (and somewhat poorly-worded) comment into an answer, so that's what I'm going to do.

Showing that $$ z \mapsto \int_{\sqrt{5}}^{z} \frac{2w}{w^{2}-4} \,  \mathrm dw$$ is a well-defined function on $\mathbb{C} \setminus [-2,2]$ means showing that the integral is independent of the path of integration.
This is indeed equivalent to showing that the value of the integral is zero for all closed contours on $\mathbb{C} \setminus [-2,2] $.
The integrand is a meromorphic function with simple poles at $w=-2$ and $w=2$, and the residue at both points is $1$.
Due to the branch cut on $[-2,2]$, every closed contour will either enclose both poles or neither pole.
If the contour encloses neither pole, then the value of the integral is $0$.
But if the contour is positively oriented and encloses both poles, that the value of the integral is $2 \pi i \, (1+1) = 4 \pi i$ (or a multiple of $4 \pi i$ if the contour winds around the poles more than once).
Therefore $$ z \mapsto \int_{\sqrt{5}}^{z} \frac{2w}{w^{2}-4} \, \mathrm dw $$ is not a well-defined function on $\mathbb{C} \setminus [-2,2]$.
The function is, however, well-defined on $\mathbb{C} \setminus (-\infty,2]$.
You are correct that the function is actually $f(z) = \log(z^{2}-4)$ if $f \left(\sqrt{5}\right)$ is defined to be zero (as opposed to some other other multiple of $2 \pi i$).


text:
Q: How to obtain Sinnoh Stones? I read that it is possible to get it on the 7th day of field research.
Are there other known ways to acquire this crucial item?

A: it is possible to gain them from trainer battle rewards (I do not know if this requires you to win against another player).
If I am not mistaken, you can also get them from spinning a stop for seven days straight, but I am not certain.

A: As of January 2019, Sinnoh Stones can be received from 7 day field research rewards as well as trainer battles (one chance a day for Blanche/Candela/Spark, three chances a day against an actual person). Actually doing the battle is what is necessary - whether you win or lose doesn't matter.
Drops are not guaranteed and there may be new methods for obtaining Sinnoh Stones added at any given time - many of which may be temporary. Unfortunately, posting the actual drop rates here wouldn't be very helpful as the actual drop rates are changing without notice as drops are shifted around by Niantic.
You can expect the methods for obtaining the Sinnoh Stone to change over time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Script error while using deploy.ps1 to deploy virtocommerce project I'm using the official virtocommerce azure deploy script under folder "virtocommerce\src\Extensions\Setup\VirtoCommerce.PowerShell" to deploy virtocommerce(with azure tool v2.4), i encounted some problems while running "deploy.ps1" script in windows azure powershell

*

*In "azure-db.ps1", there's lot of syntax like "Get-Date –f" , the dash character is wrong ,"–" must be "-", otherwise you will get error.

*In "azure-deploy.ps1", there's a function "build-search" which use cspack.exe to create "ElasticSearch.cspkg",that's correct, but for other packages such as "CommerceSite.cspkg" and "AzureScheduler.cspkg", i did not found any functions to create those packages, this will lead to an error says "CommerceSite.cspkg" can not be found.
Does anybody has the same problems?

A: Turn out that there's some problem inside code:

*

*"deploy.ps1" script is using deploy-tfs.ps1 , and use parameter "$build".

*parameter "$build" has been reset to 'False' in "deploy-tfs.ps1"

*"azure-deploy.ps1" using "$build" to decide if it's need to build the azure package, and this parameter is always 'False', so the azure package will never be creat.

A: The script is designed to run on azure sdk 2.4, not 2.5. The script is used to deploy daily both demo and testing environments and were completed succesfully today. You can see the status here: https://virtocommerce.codeplex.com.
As for cspkg, it is generated during actual build, by msbuild. The elastic search ccspkg has to be created differently, as it has to include javaruntime in addition to elasticsearch runtime and packaged into a single setup.
The new, 1.13 version of Virto Commerce by default deploys azure website instead of azure cloud service for website and scheduler (deployed as a web job). Only elastic search is deployed as a cloud service. The setting can be changed in deploy.ps1.
Also make sure to check the complete instructions on how to deploy source code to azure at http://docs.virtocommerce.com/display/vc1devguide/Source+Code+Azure+Deployment.


text:
Q: Is pure pattern matching without PatternTest and Condition Turing-complete? Note that this question is not a duplicate of that one. It is specifically about the pattern-matching engine, and explicitly excluding those patterns which call back into the full evaluation (i.e. PatternTest and Condition; if there are others like those, consider them excluded as well).
To state the problem more specifically: Given a problem with a yes/no answer which can be decided in finite time by an appropriate Turing machine, does there always exist a Mathematica pattern involving neither PatternTest nor Condition together with an appropriate encoding for the input data which matches iff the Turing machine would give "yes" for the input data?
To make more clear what I mean, I give an example of a problem solvable both with a Turing machine and with the pattern matcher:
Given a natural number, determine whether that number is even or odd. It is obvious that a Turing machine can solve this problem in finite time. Here's how pattern matching can solve that problem: Encode the natural number into a list of as many 1, so that 0 is {}, 1 is {1}, 2 is {1,1} etc. Then the pattern implementing the test is simply {PatternSequence[1,1]...}.

A: I cannot offer a rigorous answer to this question, but I will offer some thoughts...
This question asks whether the set of functions computable using basic patterns and MatchQ is isomorphic to the subset of Turing-computable functions whose results can be expressed in a single bit.  The one-bit subset restriction is important since MatchQ is clearly not fully Turing-complete since it cannot handle functions outside of that subset.
Basic pattern-matching would seem to be a very close approximation of boolean circuits.  With suitable input encoding, we can implement the basic operations thus:

    a OR b    -->    a | b
    NOT a     -->    Except[a]
    a AND b   -->    Except[Except[a], b]

For bounded input sizes, boolean circuits are known to be able to compute any boolean function (see, for example, Theorem 1.8.1 on page 32 of Clote and Kranakis: Boolean Functions and Computation Models).  The emphasis here is on bounded.  Boolean circuits are known not to be Turing-equivalent due to non-uniformity.  That is, a fixed-size Turing program can handle any input size while a boolean circuit must grow (exponentially!) in size as input size increases.
What is not clear to me is whether the other pattern-matching features add capability that will let us will evade this conclusion.  Perhaps some creative use of BlankSequence, Repeated, Longest, Shortest, PatternSequence, etc. takes us outside of the realm of boolean circuits and toward (one bit) Turing-equivalence.


text:
Q: Google sign in no longer working? I've been seeing "Bad Request Error 400" for the last few weeks whenever using Google signin on my Play Framework website (https://www.cointouch.com/). SecureSocial Config as follows:
google {
    authorizationUrl="https://accounts.google.com/o/oauth2/auth"
    accessTokenUrl="https://accounts.google.com/o/oauth2/token"
    clientId="[redacted]"
    clientSecret=[redacted]
    scope="https://www.googleapis.com/auth/plus.login profile email"
}

In the securesocial log, the following is shown before I see the error message in my browser
redirecting to: [https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login+email&client_id=[redeacted]&redirect_uri=http%3A%2F%2Ftest.cointouch.com%2Fauthenticate%2Fgoogle&response_type=code&state=[redacted]]

My redirect URLs are configured correctly in the Google API console.
I read that Google has deprecated some of their former signin APIs:
https://developers.google.com/+/api/auth-migration
Is there a quick-fix I can apply to my SecureSocial setup?

A: Having tried many remedies, and with the kind assistance of Jorge I discovered this was something to do with cookies. Deleting cookies fixed it.


text:
Q: Better quality way to set a flag outside of a foreach that determines an action I often find myself needing to iterate through a collection of elements to determine whether one or more of the elements has a particular property at a point in time. In order to determine the behaviour that occurs if the property in question is present, I clear a flag using a boolean and iterate through the collection, setting the flag and then later acting on the flag's value.
Here's an example:
function disableButtonIfAnyFailuresVisible() {
        var failureRows = $(this).find(".validation-row-failure");

        anyVisible = false;
        failureRows.each(function() {
            if ($(this).is(":visible")) {
                anyVisible = true;
            }
        });

        if (anyVisible) {
            $("#continue-button").prop("disabled", true);
        }
    }

Within this method, I want to find all of the .validation-row-failure elements on the page, and I want to check if they are visible or not. If there are any visible on the page, I want to prevent the user from proceeding by disabling the continue button.
To do this, I first set the anyVisible boolean to false, and I then iterate through each element in my collection, if any of them are visible anyVisible is set to true and then the if(anyVisible) conditional will fire.
As I mentioned before I use this approach semi-frequently, however I can't help but think that this is a poor way of going about this particular scenario. I'd like to know if there's any other better quality ways I can go about this?

A: Array.some() might be what you are looking for: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Something along these lines should work:
let failureRows = $(this).find(".validation-row-failure").toArray();
let anyVisible = failureRows.some(row => row.is(":visible"));
$("#continue-button").prop("disabled", anyVisible);

A: As Markus Dresch mentioned, the Array.some() is a very neat solution, specially designed to check if an element, corresponding to a certain patter, exists in the array.
Just an improvement of your solution - you can break the array loop once you have found a matching element:
anyVisible = false;
for(const row of failureRows) {    // change from `.each()` to `for of`
    if ($(this).is(":visible")) {
        anyVisible = true;
        break; // break once match is found
    }
}

A: Your approach is fine here's a tighter refactored version. If you want to break out of an .each() loop just add return false at the end of your if statement.

$(".fail").each(function() {
  if ($(this).is(":visible")) {
    $("#cont").prop("disabled", true);
    return false;
  }
});

    FAIL

    FAIL

    FAIL

    FAIL

    FAIL

    FAIL

    FAIL

    FAIL

    FAIL

  <button id='cont'>Continue</button>


text:
Q: Django beginner define an index url and load the view I am learning django and I am trying to add a new url to '/'
here is my urls.py:
from django.contrib import admin
from django.urls import path
from blog import views as blog_views

urlpatterns = [
    path(r'^$', blog_views.index),
    path('admin/', admin.site.urls),
]

and here is the index method from blog/views:
def index(request):
    return HttpResponse("Hey There")

But when I go to '/' route, I get a 404 response. It seems that it fails at import from blog import views as blog_views in urls.py.
What is going wrong?
Here is my project structure:

Here is the error I get:

A: In Django 2.x there is a path function instead of django's 1.x url function
the path function doesn't accept Regular Expressions it only accepts normal text
So to make a url for the home page with path function you only need to write your url path like this :
urlpatterns = [
    path('', blog_views.index), # http://localhost/
    path('admin/', admin.site.urls),
]

read more about Django 2.x urls here:
https://docs.djangoproject.com/en/dev/ref/urls/


text:
Q: Unable to upload high dimension images in php I have developed a small image upload system with lot of customization like (renaming, thumbnail generating, validation).
All features are working perfectly except Images with high dimension (2000x2000 upwards).
I can't recognize the issue.
Following is my upload.php
if (isset($_POST['upload'])) {
    $i_image = $_POST['image'];
    $fund_id = $_POST['fid'];
    $image = $_POST['image'];
    // check the existence
    $ex = mysql_query("SELECT pid, fid, image FROM imgs WHERE fid = '$fund_id' AND image = '$image'");
    if(mysql_num_rows($ex)> 0){
        echo 'Image already exists!!';
    }else{
        $newpath = $_POST['path'];
        $cfn = $_POST['cfn'];
        if (!file_exists($newpath)) {
            mkdir($newpath, 0777, true);
        }
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);

        if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/pjpeg")
            || ($_FILES["file"]["type"] == "image/x-png")
            || ($_FILES["file"]["type"] == "image/png"))
            && ($_FILES["file"]["size"] < 20000000)
            && in_array($extension, $allowedExts)) {
              if ($_FILES["file"]["error"] > 0) {
                echo "Return Code: " . $_FILES["file"]["error"] . "
";
              } else {
                echo "Upload: " . $_FILES["file"]["name"] . "
";
                echo "Type: " . $_FILES["file"]["type"] . "
";
                echo "Size: " . ($_FILES["file"]["size"] / 5000) . " kB
";
                echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";
                if (file_exists($newpath. $_FILES["file"]["name"])) {
                  echo $_FILES["file"]["name"]. " already exists. ";
                } else {
                    //rename
                    $temp2 = explode(".", $_FILES["file"]["name"]);

                    $dir_name = substr($cfn, 0, 15);
                    $rn_fn = $dir_name. '_'.$image.'.'.end($temp2);
                    $full_path = $newpath.$rn_fn;
                    $p2db = 'funds/deeds/'.$cfn.$rn_fn;
                    move_uploaded_file($_FILES["file"]["tmp_name"], $full_path);
                    $img_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $rn_fn);
                    $img_name_we = $rn_fn;
                    $user = $_SESSION['MM_Username'];
                    $insert = mysql_query("INSERT INTO imgs(fid, image, img_name, img_name_we, path, i_user) VALUES('$fund_id','$i_image','$img_name','$img_name_we','$p2db', '$user')") or die(mysql_error());
                    echo "
"."File Uploaded!". "
";
                    echo ''.'Go back';
                    $photoid= mysql_insert_id();
                    echo "

";
                    die();
                }
            }
        } else {
            echo "Invalid file";
        }
    }
}

Whenever a user uploading a large image (like 3000x4000 & File size 4.3MB) script give 'Invalid File' error.
I already set upload_max_filesize & post_max_size to 12M, max_input_time & max_execution_time to 300
What do you think?


text:
Q: Sorting and Grouping UITableView in alphabetical order I have an array filled with items from MPMediaQuery and I am trying to figure out how to get each song sorted in alphabetical order in the tableview. How do I set up the table to show each section for each letter and fill each section with the songs. not sure what code would be relevant to post, but if you need, I will provide my code i have so far.

A: You have to sort your array using a sort of NSSortDescriptor. Then you can create a different section for each letter. You also have to configure the tableviewcell properly.
Surely this will be helpful for you: https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/index.html and https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UITableViewDataSource_Protocol/index.html


text:
Q: "The report you requested requires further information" error Can anyone help me out with this issue on crystal report:
CR version 13.0.20.2399
Visual Studio Ultimate

When i try to move from the first page onto the second page, am getting this prompt,

The report you requested requires further information

Below is my code:
    myRrpt.Load(Server.MapPath("~\Reporting\CrystalReport15.rpt"))

    connect_EWS.ConnectionString = Constr_EWS
    Dim con As New SqlCommand
    Dim query As String = "SELECT * from Report_BT where Number=@num"
    con.CommandText = query
    con.Connection = connect_EWS
    con.Parameters.AddWithValue("@num", txtNumber.Text.Trim)
    connect_EWS.Open()
    '  Dim dsCustomers As New ISAE_BankTransfer
    Dim da As New SqlDataAdapter(con)

    Dim dsCustomers As DataSet4 = New DataSet4

    da.Fill(dsCustomers, "Report_BT")
    connect_EWS.Close()

    myRrpt.SetDataSource(dsCustomers.Tables(0))
    CrystalReportViewer1.DisplayPage = True

    CrystalReportViewer1.ReportSource = myRrpt

The website is published internally on Windows Server 2012 DataCenter

A: Add database connection's credential in your code.  So it will get the information in second page too. The logic is while paging in crystal report, it also hit the db to get second set of data.
var connectionInfo = new ConnectionInfo();
    connectionInfo.ServerName = "192.168.x.xxx";
    connectionInfo.DatabaseName = "xxxx";
    connectionInfo.Password = "xxxx";
    connectionInfo.UserID = "xxxx";
    connectionInfo.Type = ConnectionInfoType.SQL;
    connectionInfo.IntegratedSecurity = false;

for (int i = 0; i < Viewer.LogOnInfo.Count; i++)
{
    Viewer.LogOnInfo[i].ConnectionInfo = connectionInfo;
}

Crystal Reports - "The report you requested requires further information"


text:
Q: Using variables of one file in another file I have two python files:

*

*Term

*Today

In  the term.py file, the user is to enter some data
For instance, in the term.py  file, the user is to enter the age,sum_assuared, and the duration.
How can I make today.py file have access to the data variables(age,sum_assuared and duration) which have been input by the user in the term.py file instead of asking them to input the variables again in the today.py file
In the term.py file, I have this code
 import today
 def Term_advance():
     print('advance')
     n = int(input('enter duration (n) :'))
     age = int(input("enter life's age :"))
     Sum_assuared = int(input('enter sum assuared :'))
     basis = input('what is the calculation basis::\n'
               '1.\t AM 92\n'
               '2.\t ELT 15 MALES\n'
               '3.\t ELT 12 FELAMES\n'
              '4.\t PEN\n'
              '5.\t A1967-70\n')
     If basis==1:
          today.tables_advance_perpetuity()

Then in the today.py file, I have this code that reads the values from an excel document. The variables here, however, are to already input by the user in the Term.py file(age,n, and sum_assuared)
 import xlrd
 loc = "C:PycharmProjects/Life annuities/tables.xlsx"
 wb = xlrd.open_workbook(loc)

 def tables_advance_perpetuity():
     sheet = wb.sheet_by_index(0)
     sheet.cell_value(0, 0)
     num = int(input('enter the age of the life:'))
     for i in range(sheet.nrows):
         x = sheet.cell_value(i, 0)
         if x == num:
             dx = sheet.cell_value(num - 1, 2)
             nx = sheet.cell_value(num - 1, 6)
             print(dx)
             print(nx)
             ann = nx / dx
             print(f'Annuity value is {ann}')

So like for this case how can the today file read, for instance, the age,sum_assuared and n of the life entered by the user in the term.py file( instead of asking the user to enter the values again in the today.py file)
Like I seek to be able to read the variables(age,sum_assuared, and n) which are in the term.py file.So I wish to access them using the today.py file. instead of having a second prompt asking for the values in the today.py file

A: The easiest way might be to save the input of the first script to an external txt file, and then read it in the second script.
Or you could try to create a third script that import both modules and run them in the same session.
There seems to be some ideas here: How to share variables across scripts in python?

A: Well it depends if they are different processes or not, you could simply make a "main" function that calls the two files one after another and stores the information.
Otherwise if you want them to be two separate processes/programs you could use the module pickle to save the information in a .pickle file and then open the file in the other program.
Have a look at pickle if you are using objects with multiple attributes or such: https://docs.python.org/3/library/pickle.html. If you simply want to save a single value a text file should do the trick.

A: You can import term.py as a module and make it return values. Modify term.py as follows (add to the end of Term_advance()):

    return age, n, sum_assuared

Then in the other script import the module and run the function to get values for variables (here I'm assuming both scripts are in the same folder):
import term

age, n, sum_assuared = term.Term_advance()

This way the user will need to enter data only once, but it will run through both scripts.
Alternatively, if you just want to run term.py separately, you can simply write values into a file and then have the second script read from it.


text:
Q: Best way to handle suggested edits to accepted answers I recently was presented with this edit:
https://stackoverflow.com/review/suggested-edits/4003993
In general, what's the feeling on allowing an edit of an accepted answer, and one that has so many upvotes?  Should it have been a comment to the answer rather than an edit to the answer?  With that many upvotes, and with the code unproven, I don't know if I feel confident in accepting the edit.
The community's guidance is appreciated.

A:
In general

Screw "in general". Evaluate the edit on its merits, in the context of the post being edited. If you don't know enough about the subject to be able to tell whether it's good or bad, skip it. If it made sense to reject edits based on simple rules like this, we could just do that automatically and skip the whole "reviewer" bit. In fact, we already do that, so if you're even seeing an edit there's at least a slim chance there's some worth to it.
The only edits you should evaluate consistently regardless of content or context are the fake ones generated for audits - they're crap 100% of the time or your money back.
P.S. Comments are often hidden, deleted or unread. Posting any non-trivial amount of code in comments is just cruelty to the reader. Don't put anything of value in comments if you can avoid it, and don't encourage others to do so either.

A: The fact that the answer is accepted and highly upvoted is irrelevant.
In the words of the official guidance:

When should I edit posts?
(…)  Common reasons for edits include: (…)

*

*To correct minor mistakes or add updates as the post ages

This edit is a minor change to the post; it respects the core logic and leaves most of the details intact, and purportedly correctly handles a case that the original case did not handle correctly. It is intended to correct a minor mistake in the original code.
So it boils down to: does this edit indeed correct a minor mistake?

*

*If it is correct, accept the edit.

*If it is incorrect, reject the edit.

*If it is not quite right but on the right track, improve the edit.

*If you aren't sure, for example because you lack the requisite subject knowledge, skip the edit.

A comment would not be appropriate to correct a mistake in an answer. Comments are only for temporary notes. For example, "X is wrong but I don't know how to fix it" should be posted as a comment, and stay until someone comes along and makes the required fix. On the other hand, "this is wrong and here's the precise way to fix it" should not be posted as a comment, it should be an edit that implements the fix.

A: Edits are there to improve the presentation of the author's content, not to change it.  Their goal is to make the reader better comprehend whatever it was that the author was trying to say.
If you would like to add entirely new content then the appropriate medium to do so is either through a comment to the answer, or if you are providing enough content that you feel it is worthwhile, an entirely new answer to the question.  (Just be sure that if posting a new answer, it fully answers the question, and that it's not just a reply to another answer.)
The rejection of the edit was correct, and for the correct reason.
That the answer is accepted has no bearing on this decision.
If a post is marked as Community Wiki, though, that changes matters entirely.  The whole point of marking a post as CW is to say, "This post is no longer just mine.  Anyone and everyone is free to change the content of the post, not just its presentation."  If the post is marked as CW and there is a suggested edit that changes its content, then approve/reject the suggestion based on whether it is correct, and whether it improves the quality of the post.  It is under no obligation to maintain the authors intent.


text:
Q: What is the preferred way to access an Android database (from the phone) and SQLite database (from the PC) with the same API? We develop an application that is supposed to run on both PCs and Android mobile phones. Some of the code should be shared on both platforms. As both versions make heavy use of databases (native SQLite on the PC and the built-in SQLite DBs on Android), I was wondering whether there is a good way to write code that accesses both these databases through the same API.
My question is about the preferred way to develop such code. There are ways to use a native SQLite DB on the Android phone, then obviously the code would be identical. The second option would be to develop a small library that has an AndroidDatabaseAdapter and an SQLiteDatabaseAdapter which both implement a common interface and essentially just forward the respective calls. But since I guess that I'm not the first person to have such a problem, I was wondering whether there already exists such a library. Unfortunately, my Google and SO search did not reveal any such library that is slim and does not already come along with ORM and lots more features which I consider as overhead for our purpose.


text:
Q: Vue error compiler with function never used could you please help me with resolve problem, why compiler say, that function 'show' is defined but never used?
function show is use in html:
<b-card>
  <div id="draw-image-test">
    <canvas
      id="canvasId"
      ref="canRef"
      @mousemove="show"
    />
  </div>
</b-card>

And after <script>
function show(){
  const canvasMouseTrack = document.getElementById('canvasId')
  const rect = canvasMouseTrack.getBoundingClientRect()
  console.log(rect.offsetX)
}

And i have error:
'show' is defined but never used         no-unused-vars

A: the function show should be added to the methods option :
<script>
  export default{

   methods:{
    show:function(){
      const canvasMouseTrack = document.getElementById('canvasId')
      const rect = canvasMouseTrack.getBoundingClientRect()
      console.log(rect.offsetX)
    }
    }
}


text:
Q: Google one tap login with laravel 8 in one of my projects i want to add a google one tap login for that i followed instructions as mentioned.
The front end is working fine but there is issue with the backend.
Here is my code.
I have added this script to the header.
and this code after body open
<div id="g_id_onload"
data-client_id="#####################.googleusercontent.com"
data-login_uri="/login/google/oneTap"
data-_token="{{csrf_token()}}"
data-method="post"
data-ux_mode="redirect"
data-auto_prompt="true">
</div>

This is the route
Route::get('/login/google/oneTap', [App\Http\Controllers\SocialLoginController::class, 'oneTap']);

In an article regarding one, tap login author told that it requires a post method but there is clarification on how to add a post method.
This is the article.
https://www.teachnep.com/blog/how-to-add-one-tap-login-to-laravel-project#
My backend code.
public function oneTap(REQUEST $request)
    {
        $token = $request->credential;
        $tokenParts = explode('.', $token);
        $tokenHeader = base64_decode($tokenParts[0]);
        $tokenPayload = base64_decode($tokenParts[1]);
        $jwtHeader = json_decode($tokenHeader);
        $jwtPayload = json_decode($tokenPayload);
        $user = $jwtPayload;
        return $user;
    }

It returns null;
Any help would be appreciated.

A: You must define your route using the POST verb instead of GET.
For example:
Route::post('/login/google', [GoogleSignInController::class, 'login'])
    ->name('login.google');

Even though you can verify the "ID Token" (this is how Google refers to the credential param) by yourself, it is recommended to use the official Google API Client Library.
You can add it to your project using Composer:
composer require google/apiclient

In addition to validate the credential field, you should validate the CSRF token provided in the g_csrf_token field.
To summarize:
/**
 * Validate the "ID Token" using the Google API Client Library.
 * https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
 */
public function login(Request $request)
{
    if ($_COOKIE['g_csrf_token'] !== $request->input('g_csrf_token')) {
        // Invalid CSRF token
        return back();
    }

    $idToken = $request->input('credential');

    $client = new Google_Client([
        'client_id' => env('GOOGLE_CLIENT_ID')
    ]);

    $payload = $client->verifyIdToken($idToken);

    if (!$payload) {
        // Invalid ID token
        return back();
    }

    dd($payload);
}

Note that I printed the $payload at the end:

You may want to use the $payload['sub'] that represents the user id to register / authenticate this user in your application, as well as its name and picture.


text:
Q: Cannot succes do as in tutorial of flask-peewee I learning using flask-peewee. As in tutorial there, i apply this script (app.py):
import datetime
from flask import Flask
from flask_peewee.auth import Auth
from flask_peewee.db import Database
from peewee import *
from flask_peewee.admin import Admin

# configure our database
DATABASE = {
    'name': 'exampleappusi.db',
    'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = 'ssshhhh'

app = Flask(__name__)
app.config.from_object(__name__)

# instantiate the db wrapper
db = Database(app)

class Note(db.Model):
    message = TextField()
    created = DateTimeField(default=datetime.datetime.now)

# create an Auth object for use with our flask app and database wrapper
auth = Auth(app, db)

admin = Admin(app, auth)
admin.register(Note)

admin.setup()

if __name__ == '__main__':
    auth.User.create_table(fail_silently=True)
    Note.create_table(fail_silently=True)

    app.run(host='0.0.0.0')

And until this part:

We now have a functioning admin site! Of course, we'll need a user log in with, so open up an interactive python shell in the directory alongside the app and run the following:

As an in the tutorial, we do in python shell (I understand that we do this following to adding user and pass as manual way):
>> from auth import User
>> admin = User(username='admin', admin=True, active=True)
>> admin.set_password('admin')
>> admin.save()

The problem is i get error when execute ">> from auth import User", which mean No module named auth. Sure, in this case we need auth.py , but what the auth.py should be ?
Thanks.

A: Your module is named app so you should import auth there.
>> from app import auth
>> User = auth.User
>> admin = User(username='admin', admin=True, active=True)
>> admin.set_password('admin')
>> admin.save()

A: You can create a auth.py file:
auth.py (same directory as app.py)
from flask_peewee.auth import Auth
from app import app, db

auth = Auth(app, db)

You will also need a models.py to create a User:
https://github.com/coleifer/flask-peewee/blob/master/example/models.py


text:
Q: CSV data map needs to fix Can someone help me to fix this code.
this is data array for a CSV file
foreach($feedback as $value) {
        $csv_array[] = array(
            'title' => $value->title ?: get_the_title($value->post_id),
            'feedback_type' => $value->type,
            'reason' => $value->reason,
            'comments' => $value->comments,
            'allow_response' => $value->allow_response === null ? 'No' : 'Yes',
            'firstname' => $value->first_name,
            'lastname' => $value->last_name,
            'phone' => $value->phone,
            'email' => $value->email,
            'prefered_contact_method' => $value->prefered_contact_method,
            'date_submitted' => $value->created_at
        );
    }

Now I want to know if feedback_type is negative 'reason' => $value->reason this needs to be empty.
I write this, but looks like something is wrong.
'feedback_type' => $value->type === 'negative' ? 'reason' => $value->reason : ''

A: if type is negative then empty , else use $value->reason
'reason' => $value->type === 'negative' ? '' : $value->reason


text:
Q: using method-declared variable in mutators? Confused on the logic of getting a variable out of a method in a  class and using it in a mutator.
Edit: here is my code dump
My Code:
package tests;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class LoadingBox extends JPanel {
String[] inFiles = new String[0];

    public void loadIt(){
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(getParent());
                if(returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getCurrentDirectory();
                    String path = file.getPath();
                    String filename = chooser.getSelectedFile().getName();
                    String fullpath = path + "/" + filename;
                    }
                }

    public String[] getFiles() {
        return inFiles;
    }

    public void setFiles(String[] inFiles) {
        this.inFiles = inFiles;
    }
}

Heres where it's going
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

 public class FileScan {

ArrayList<String> stringArray = new ArrayList<String>();
ArrayList<Integer> numArray = new ArrayList<Integer>();
LoadingBox LoadFile = new LoadingBox();
String[] files = {LoadFile.getFiles()[0]};

//ITS GOING RIGHT HERE^^^^^^^^^^^^^^^

public void scan(String[] args) throws IOException {
    Scanner input = null;
    new FileScan();
    try {
          input = new Scanner(new File(files[0]));
         //add strings and integers from file to different arrays
         while (input.hasNext()) {
         String token = input.nextLine();
                try{
                    int o = Integer.parseInt(token);
                    numArray.add(o);
                }
                catch(NumberFormatException nfe){
                    stringArray.add(token);
                }
          }
    }
    finally {
             if (input != null) {
                 input.close();
             }

        }
    }

//Some more getters and setters down here

Stack overflow is making me type more so I'm going to ramble out some words down here so that I can post.

A: I don't know what the error you're getting is, so I'm just going to rewrite your code and hope it solves your problem.
package tests;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class LoadingBox extends JPanel {
    private String inFiles;

    public void loadIt(){
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getCurrentDirectory();
                String path = file.getPath();
                String filename = chooser.getSelectedFile().getName();
                String fullpath = path + "/" + filename;
                this.setFiles(fullpath);
            }
    }

    public String getFiles() {
        return inFiles;
    }

    public void setFiles(String inFiles) {
        this.inFiles = inFiles;
    }

}
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class FileScan {
    private ArrayList<String> stringArray;
    private ArrayList<Integer> numArray;
    private LoadingBox loadFile;
    private String files;

    public FileScan(){
        stringArray = new ArrayList<String>();
        numArray = new ArrayList<Integer>();
        loadFile = new LoadingBox();
        loadFile.loadIt();
        files = LoadFile.getFiles();
    }

    public void scan(String[] args) throws IOException {
        Scanner input = null;
        new FileScan();
        try {
            input = new Scanner(new File(files));
            //add strings and integers from file to different arrays
            while (input.hasNext()) {
                String token = input.nextLine();
                try{
                    int o = Integer.parseInt(token);
                    numArray.add(o);
                 }
                 catch(NumberFormatException nfe){
                     stringArray.add(token);
                 }
            }
        }
        finally {
            if (input != null) {
                 input.close();
            }

    }
}


text:
Q: PHP Stripe get balance I am using stripe payment gateway with PHP. I need to retrieve the balance amount available in my account to initiate a transfer. Please describe pending and available amount given below in the API response. Under what condition the available amount turns negative. I am using in test mode.
Stripe_Balance::retrieve();

{
  "pending": [
    {
      "amount": 37353,
      "currency": "usd"
    }
  ],
  "available": [
    {
      "amount": -13725,
      "currency": "usd"
    }
  ],
  "livemode": false,
  "object": "balance"
}


text:
Q: App_Code compilation does not clean old assemblies We are developing an ASP.NET Website with a whole lot of code in the App_Code folder due to a special customer requirement (I know, we don't like that either).
The project is using .NET 4.7.1 and we have the following compiler section in our web.config

<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />

After recompilation we often have the issue, that not all code seems to be cleanly recompiled, which breaks our login among other things. I was able to track the problem down in the following line:
    bool isAuthenticated = System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated // User is logged in
                            && System.Threading.Thread.CurrentPrincipal.Identity is JWTAuthenticationIdentity;

The second part of the check returns false in this case, even though both are of the same type, however, the type of the Identity is defined in "Assembly1" while the type of the JWTAuthenticationIdentity is defined in "Assembly2". Therefore casting between the two types is impossible.
The error can be fixed, by applying a random change in the web.config or so, to force the server to recompile. Afterwards, the old assemblies are usually deleted, both types are therefore defined in the same assembly again and everything works as expected again.

A: It seems like my issue can be fixed, by disallowing the overlapping rotation of App_Pools in IIS.
This can be set via the IIS Manager GUI under "App Pools" --> "Advanced Settings" --> "Disable overlapping Recycle"


text:
Q: Appending render with decorator in Django I'm using render with the following:
@countunreadmail
def listall(request, *args, **kwargs):

    return render(request, 'static/list.html', {'loggedin': True})

but I want to append the render line to include some additional kwp's that are computed in a decorator that is used before the function. So the dectorator function is for example:
def countunreadmail(view):
    def wrapper(request, *args, **kwargs):
        exists, myid = myexists(request)
        unreadcount = messagescount(myid)[0]
        r.context_data = {'unreadcount': unreadcount}
        context = {'unreadcount': unreadcount}
        kwargs = dict(kwargs.items() + context.items())
        return view(request, *args, **kwargs)
    return wrapper

so how can I add get the following in the render line:
return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': unreadcount})

A: You could do one of the following. First, you could change the definition of your listall view function to
def listall(request, unreadcount=None):

That way unreadcount will be in the context of the listall function and you can call render as you have written above. Alternatively, you could change your render line to
return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': kwargs['unreadcount']})

Either way, it looks like your decorator could use some simplification. All it needs to do is ensure that unreadcount is in the kwargs for the view that it's decorating, and to set it's value. The following should work with either of the above corrections.
def countreademail(view):
    def wrapper(request, *args, **kwargs):
        exists, myid = myexists(request)
        kwargs['unreadcount'] = messagescount(myid)[0]
    return view(request, *args, **kwargs)
return wrapper

That being said, it's possible that you should consider using a non-decorator solution, since all you're using it for is adding single variable to the context of the view function and calculating a value for it. You could use the following, simpler solution instead.
def countunreademail(request):
    exists, myid = myexists(request)
    return messagescount(myid)[0]

def listall(request, *args, **kwargs):
    unreadcount = countunreademail(request)
    return render(request, 'static/list.html', {'loggedin': True, 'unreadcount': unreadcount })


text:
Q: Fast algorithm to detect the inclination of the lines in the image My requirement is to find the inclination of the lines (all 8 lines) surrounding the data matrix, as shown in the edge detected image:

The two main restrictions:

*

*The inclination detected should have precision of at least 0.1 deg (the best achievable in this image)

*Time taken should be less than 30 ms

I am implementing the algo on a Blackfin DSP, and have used Blackfin image processing toolbox.
I tried using Hough transform and Contour detection to find out the lines and thus their inclinations however the time limit exceeds. Any suggestions to use a different algorithm or optimize this one would help.
[for my use case the higher the angle precision the better, I am targeting at least 0.02 - 0.05 with a higher resolution image]

A: *

*find bounding box
scan all points and found xmin,ymin,xmax,ymax of set pixels

*find the gaps
cast scan lines through half of bounding box remembering/measure the gap sizes. To avoid line miss (due to holes) you can cast more scan lines or scan with wider ray.
If you need some examples for ray cast/scanning see:

*

*How to find horizon line efficiently in a high-altitude photo?

*segmentate the image into regions
just shrink bounding box by some fraction (50%) of a gap ... something like this:

forming 8 rectangular regions each one with single line without noise from the edges.

*regress/fit lines
The idea is to make a list of all set pixels for each region separately and fit a line that has smallest distance to all of them.
I would try to use this:

*

*Given n points on a 2D plane, find the maximum number of points that lie on the same straight line
Or use approximation search and fit something like

*

*Curve fitting with y points on repeated x positions
just ignore the curvature and fit line equation parameters directly instead cubics.
After the lines are fitted you can compute their slope directly by atan2(dy,dx)

A: A fast and easy approch would be to scan every line and column for the first and second white pixel starting from left, right, top and bottom. Then simply use some robust line fit algorithm to get the lines.
Unless you did not already try to do that you can reduce the data for Hough transform or other algorithms by cropping the image down to DMC size.
The required angle accuracy cannot be achieved as you don't have enough resultion. And even if you had your results would suffer from any noise and outliers.


text:
Q: Two Images on one Object in OpenGL I have two textures. One is jpg and the other is png. I have rendered a cube and I want to use the jpg image as a background in every face of the cube and then have the png on this background. I tried mix() but i can see the background through png and I don't want that. Is there any function that can do this for me?
Fragment Shader:
#version 330 core

struct Light {
    vec3 direction;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct Material {
    float shininess;
};

out vec4 FragColor;

in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoords;

uniform vec3 viewPos;
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform Light light;
uniform Material material;

void main() {

    // ambient
    vec3 ambient = light.ambient * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;

    // diffuse
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(-light.direction);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = light.diffuse * diff * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;

    // specular
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * spec * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;

    vec3 result = ambient + diffuse + specular;
    FragColor = vec4(result, 1.0);

}

texture1 is the png and texture2 is the jpg.

A: You need to mix the color depending on the alpha channel of the PNG texture. Assuming texture1 is the JPG and texture2 is the PNG, mix texture1 and texture2 depending on texture2's alpha channel:
vec4 color_jpg = texture(texture1, TexCoords);
vec4 color_png = texture(texture2, TexCoords);
vec3 color = mix(color_jpg.rgb, color_png.rgb, color_png.a);

Fragment shader:
void main()
{
    vec4 color_jpg = texture(texture1, TexCoords);
    vec4 color_png = texture(texture2, TexCoords);
    vec3 color = mix(color_jpg.rgb, color_png.rgb, color_png.a);

    // ambient
    vec3 ambient = light.ambient * color;

    // diffuse
    vec3 norm = normalize(Normal);
    vec3 lightDir = normalize(-light.direction);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = light.diffuse * diff * color;

    // specular
    vec3 viewDir = normalize(viewPos - FragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * spec * color;

    vec3 result = ambient + diffuse + specular;
    FragColor = vec4(result, 1.0);
}


text:
Q: Is there a more efficient query I can use I want to know if theres a better way to script out this update statement:
update table A
set item = (select itemA + ' - ' + itemB from table B where id = 1),
temp = (select itemA from table B where id = 1)
where sid = (select sItemId from table B where id = 1)

A: Use JOINS to make it more efficient and Alias to make it more readable.
UPDATE A
SET A.item  = B.itemA + ' - ' + B.itemB
   ,A.temp  = B.itemA
FROM tableA A
INNER JOIN tableB B ON A.[sid] = B.sItemId
where B.id = 1

A: SQL Server specific syntax:
update a
set item = b.itemA + ' - ' + b.itemB,
    temp = b.itemA
from tableA a
     inner join tableB b on a.sid = b.sItemId
where b.id=1

Alternatively you can use MERGE:
merge into tableA as a
using tableB as b
on a.sid = b.sItemId and b.Id = 1
when matched then update set item = b.itemA + ' - ' + b.itemB, temp = b.itemA
;

The advantage of merge is that it is standard SQL syntax, and it will fail if an attempt is made to update the same record twice (the update with join will silently do only one of the updates). IIRC in later versions (with the respective compatibility level) update will fail as well. Also merge is more flexible.

A: It is of course better to use only one join instead of retrieving the same table (tableB) 3 times
UPDATE tableA
SET tableA.item =tableB. itemA + ' - ' + tableB.itemB,
tableA.temp = tableB.itemA ,
...
FROM tableA, tableB
WHERE tableA.sid= tableB.sItemId And tableB.id =1


text:
Q: loading content in a div from iframe with jquery I have a dropdown list menu in my "index.php" page that loads another page (depending of selection) in a iframe like this:

loading area

  <form>
    <select onchange="setPic(this);">
      <option value="/network/page_elements/lvl1.php" >lvl1</option>
      <option value="/network/page_elements/lvl2.php" >lvl2</option>
      <option value="/network/page_elements/lvl3.php" >lvl3</option>
      <option value="/network/page_elements/lvl4.php" >lvl4</option>
    </select>
</form>

So i am loading for example page "lvl1.php" in the iframe. This "lvl1.php" page contains a button like this:

<form method="post">
  <input type="button" value="1" id="A1" />
</form>

When this button is being pressed it executes a jquery code that should load some results in the div with id="header" on the "index.php" page...wich it doesn't.
The jquery looks like this:

$(document).ready(function() {

    $('#header').load('network/page_elements/header.php');

 $('input').click(function() {

  var page=$(this).attr('id');

  $('#header').load('network/buttons/' + page + '.php');
  });

  return false;
});

So in this example when button is pressed it should execute a script called "A1.php" and post its results in the div with id="header" on the index page.

If i place the button code on the "index.php" page it works fine...but it does nothing if it is being pressed on the loaded page inside the iframe.
Any ideea what am i doing wrong?

A: You must access the DOM of the parent window since the javascript is executing inside a frame
window.opener.$("#header")

how to access parent window object using jquery?

A: Got it in the end:
I changed the jquery like this to access the parent window:

$("#header",window.parent.document).load('/network/buttons/' + page + '.php');

Thanks for the idea Digitaldouble


text:
Q: Rails 3.2 ActiveAdmin 'Collection is not a paginated scope.' error I'm developing an application using Rails 3.2 and ActiveAdmin 0.4.4.
I have model named Teaser (/app/models/teaser.rb):
class Teaser < ActiveRecord::Base
  attr_accessible :img, :name, :url
  validates :img, :name, :presence => true
  mount_uploader :img, TeaserUploader
end

And I added ActiveAdmin to it  (/app/admin/teaser.rb):
# encoding: UTF-8
ActiveAdmin.register Teaser do
    form do |f|
        f.inputs "Teaser" do
            f.input :name, :label => 'Текст'
            f.input :url, :label => 'Ссылка'
            f.input :img, :as => :file, :label => 'Картинка'
        end
        f.buttons
    end
end

Now, when I go to 'http://localhost:3000/admin/teasers', I get the following error:
Showing C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activeadmin-0.4.4/app/views/active_admin/resource/index.html.arb where line #1 raised:
Collection is not a paginated scope. Set collection.page(params[:page]).per(10) before calling :paginated_collection.
I get the same error when I test my app on linux (Ubuntu 12.04).
I can solve this problem by this way (/app/admin/teaser.rb):
# encoding: UTF-8
ActiveAdmin.register Teaser, :as => 'Somename' do

But if I use this method, I cannot translate this model by using /app/config/locales/XX.yml
All other models work properly.

A: In some cases all you need to do is change the model's label in active admin
Example
BREAKS
ActiveAdmin.register Stage do

WORKS
ActiveAdmin.register Stage, as: "Opportunity Stage" do

The same case is for a model Page
Update: 30-May
I've run into this issue again, with a model like

ActiveAdmin.register PageRedirects do

and in the application_controller.rb I had this:
before_filter :abc

def abc
  @page_redirects = ...
end

This method overrides the @page_redirects from the active-admin controller I guess.

A: Here is the solution (/app/models/teaser.rb)
collection_action :index, :method => :get do
  scope = Teaser.scoped
  @collection = scope.page() if params[:q].blank?
  @search = scope.metasearch(clean_search_params(params[:q]))
end

A: You may have a variable with the same name as the controller that is conflicting. Maybe in your application_controller.rb?

A: Just improving the answer... I had problems when using the active admin filters, so I had to modify a little bit the code. Its working for me now.
collection_action :index, :method => :get do
  scope = Teaser.scoped
  @search = scope.metasearch(clean_search_params(params[:q]))
  @collection =  @search.page()
end

A: None of the answers worked for me in rails 4.1
In the discussion at the github issue it turns out that this is caused by the fact that active admin is inheriting from the application controller.
So to answer this question, I suppose the bug is caused by assigning some collection to @teasers in the application controller.

A: Can you please rename resource name on active admin page like
ActiveAdmin.register Teaser, as: "Some other name" do

This solved my issue.
I think this is due to conflict of resource name.

A: Adding a default scope in active admin solved the issue for me.
ActiveAdmin.register StaticPage, as: 'Static Page' do
  scope :all, default: true
  # ...
end


text:
Q: MySQL - insert into using unknown values I'm trying to insert values into a table, but this doesn't seem to work.
'BLL.vb
adpUser as new dalUserTableAdapters.tblUserTableAdapter
adpUser.insert(objUser.UserName, objUser,UserPass)
'View.xsd
Insert into User
(UserName, UserPass)
Values
(@UserName, @UserPass)

So I need a user to fill in a textbox and the content of the textbox are inserted into the table. All I can find is predefined data.
Thanks!

A: You need paranthesis:
Insert into User
(UserName, UserPass)
Values
( ? , ? )

Try to use ? instaed of @parameter. I think there is difference between trying to connect to SQL-Server and MySQL.

And I guess the comma in objUser,UserPass is a typo in the post here...


text:
Q: How to achieve this material effect? I have seen this in a lot of apps but I don't know what exactly this is called....
Can anyone tell me? I actually wanna show some text in my app with this raised background kind of thing....
Please tell me how to get this effect..
Here is the image:

A: You can try this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_margin="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:text="My Title Text"
            android:padding="20dp"
            android:textSize="18sp"
            android:textColor="#000"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#e6b121"
            android:id="@+id/your_id" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:text="Lorem ipsum dolor sit amet, mel esse eripuit patrioque id. Id inimicus scripserit delicatissimi est, id vide velit erant sed. Has an veri mutat accumsan, te iusto dolore similique nec. An laboramus delicatissimi nam, ea brute consul vis."
                android:id="@+id/textView17" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

which will give you as a result this:

and also try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_margin="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:text="My Title Text"
            android:padding="20dp"
            android:textSize="18sp"
            android:textColor="#000"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#e6b121"
            android:id="@+id/your_id" />

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="Screen On:"
                        android:id="@+id/textView17" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="19m 28s"
                        android:id="@+id/textView18" />
                </LinearLayout>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="Discharge while On/Off:"
                        android:id="@+id/textView19" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:padding="10dp"
                        android:text="7% / 3%"
                        android:id="@+id/textView20" />
                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

But of course you are going to need to implement a custom adapter to adapt them into a ListView or RecyclerView
Hope it helps!!!


text:
Q: Does $\overline{A}$ be dense-in-itselft implies A is dense-in-itselft? Let ($X, τ$) ve a topological space and $A\subseteq X$ we say that $A$ is dense-in-itselft if $A \subseteq A'$ where $A'$ denotes the set of acumulation points of A.
If $\overline{A}$ is dense-in-itselft then A is dense-in-itselft?
I think yes but I have no idea of how to proof it or any counterexample

A: The restiction to $T_1$ spaces is in general necessary.
Let $S=\{0,1\}$ with the topology $\{\varnothing,\{0\},S\}$, let $[0,1]$ have its usual topology, let $Y=[0,1]\times S$ have the product topology, and let $X=Y\setminus\{\langle0,1\rangle\}$. Let
$$A=\{\langle 0,0\rangle\}\cup\big((0,1]\times\{1\}\big)\,;$$
then $\langle 0,0\rangle$ is an isolated point of $A$, so $A$ is not dense-in-itself, but $\operatorname{cl}A=X$, which has no isolated points and is therefore dense-in-itself.

A: Partial answer: Yes, provided $(X,\tau)$ is $T_1$.
Fix $x\in A$ and $U\in\tau$ with $x\in U$. By assumption, $x\in \overline A\subset (\overline  A)'$, so there is some $y\in \overline A$ with $y\in U$ and $y\neq x$. By assumption, there is some $V\in \tau$ with $y\in V$ and $x\not \in  V$. Now $y\in \overline A$ and $y\in V\cap U$, so there is some $z\in A$ with $z\in V\cap U$. Since $x\not \in V$, we can infer that $z\neq x$.
But then every open neighbourhood of $x$ contains  a point of $A$ different from $x$. Therefore, $x\in A'$.

A: No, consider $X=\{1,2\}$ with $\tau=\{\emptyset,X\}$. Then, $\{1\}'=\{2\}$ and $\overline{\{1\}}=X=X'$.
Your claim is true for T1 spaces.
If $X$ is T1 and $\overline{A}'\subseteq\overline A$, let $a\in A$ and let $U\ni a$ be open. Since $a\in\overline A$, there is some $b\in \overline A\cap U$ such that $b\ne a$. Now, consider and open set $V$ suc that $b\in V$ and $a\notin V$. Since $b\in\overline A$ and $b\in U\cap V$, there is some $a'\in A\cap U\cap V$. Therefore $a'\in A\cap U\setminus\{a\}$.


text:
Q: PKCS#11 Test suite Can somebody give me a link to PKCS#11 test suite? This may be a simple utility or part of big project no matter.
I now only this one: Netscape PKCS #11 Test Suites

A: OpenSC package includes pkcs11-tool, a very rudimentary test-suite, pkcs11-tool --test --slot X --module module. This is just for reference, I'm sure you can find some quirks in pkcs11-tool test suite if you're using a strange or little bit exotic PKCS#11 module.

A: http://thewalter.net/git/cgit.cgi/p11-tests
also has a good test cases and it's source codes is available through git system


text:
Q: What is the meaning of "static" in pseudo-code This is a pseudo-code from "Artificial Intelligence: A modern approach"
function Table-Driven-Agent(percept) returns action
  static: percepts, a sequence, initially empty
          table, a table, indexed by the percept sequences, initially fully specified

  append percept to the end of percepts
  action <-- Lookup(percepts, table)
  return action

In this code and many other codes, there is the keyword static before some declarations. I want to use this keyword in my own algorithm pseudo-code, but I am not sure what is its usage.

A: It means persistent (the data persists between calls). The latest version of the pseudo-code has been modified, such that the word "static" was replaced with "persistent". A description of your algorithm from that source: "The TABLE-DRIVEN-AGENT program is invoked for each new percept and returns an action each time. It retains the complete percept sequence in memory."
The word "static" can have very different meanings in different languages, so it was a poor choice.
Here is the updated pseudo-code.


text:
Q: ООП: переопределение vs определение абстрактного метода Подскажите, какой подход более грамотный, и почему:
<?php
    class base{
      function show(){
        return 'one';
      }
    }

    class one extends base{}
    class two extends base{
      function show(){
        return 'two';
      }
    }

    $one = new one();
    $two = new two();

    echo $one->show();
    echo $two->show();

VS
<?php
    abstract class base{
      abstract function show();
    }

    class one extends base{
      function show(){
        return 'one';
      }
    }
    class two extends base{
      function show(){
        return 'two';
      }
    }

    $one = new one();
    $two = new two();

    echo $one->show();
    echo $two->show();

A: Ни первый вариант, ни второй. Вам нужен интерфейс.
interface Showable {
    function show();
}

class One implements Showable {
    public function show() {}
}

class Two implements Showable {
    public function show() {}
}

Абстрактный класс нужен в том случае, если у вас есть общая реализация для нескольких потомков.
При использовании интерфейсов, вы можете, например, написать класс, реализующий несколько интерфейсов.
Почитайте про принципы проектирования SOLID. В особенности, про принцип подстановки и принцип разделения интерфейса.

A: Я из другого языка, но попытаюсь ответить так: если вам не нужно создавать экземпляр класса, но требуется описать класс с общей функциональностью, при этом реализовав некоторые методы, то абстрактный класс. В наследниках вы можете переопределить нужные методы и т.д. Скорее всего это удобно для больших проектов, где есть некоторая функциональность, которую желательно не реализовывать каждый раз самому, а просто определить наследника. С другой стороны, если вам нужно создавать экземпляр вашего базового класса и этим вы не нарушите никакую логику приложения, никто не запретит вам реализовать второй вариант) При этом в абстрактных классах не нужно указывать, что их возможно переопределить,а вот в базовых надо(virtual методы c# к примеру). Все зависит от удобства и привычки=)


text:
Q: Do I need a new table for a new language? Do I need to create a different table for each new language?
Here's a sample table:
field
id
field
lang
filter
count

Say someone inputs data in English, then they input data in Japanese, then they input data in Russian....  Is that going to be acceptable?  Or rather, is there a good way to make it possible because I get the following error, making me believe that I should re-design:
Warning: #1366 Incorrect string value: '\xE8\x8B\xB1\xE8\xAA\x9E' for column 'field' at row 1

A: You can use Unicode to allow all languages within your database. Clients should also process and transfer captured data in Unicode.


text:
Q: Error messages in Ruby on Rails I did a validates_presence_of fields to the comments in the guide. How to display validation errors on the posts page. I know about render, but with render i need to send all variables that i'm using on posts page. Am i right?

A: I don't believe a plugin is required. The scaffold generator in Rails 3.x does it this way:
<%= form_for(@model) do |f| %>
  <% if @model.errors.any? %>

<%= pluralize(@model.errors.count, "error") %> prohibited this model from being saved:

      <% @model.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>
<%# Rest of form... %>

A: If you are looking to show the messages in your view, like so:

This is what you want.. More info http://www.monochrome.co.uk/blog/2010/04/14/rails-3-error_messages-and-error_messages_for
`rails plugin install git://github.com/rails/dynamic_form.git`

<%= form_for @supermoon do |f| %>
  <%= f.error_messages %>

Plugin not required in rails 2.3 (is required in 3.x)

A: You can access these validation errors(and their messages) in the @variable.errors.full_messages as seen here.

A: validates_presence_of has a :message argument to custom an error message.
class Person < ActiveRecord::Base
    validates_presence_of :user_name, :message => 'My custom error message'
end


text:
Q: How to combine columns from join table results? I have a mysql table that looks like this:
Table PaymentType
ID   PaymentCode   PaymentName
1      P1        CASH
2      P2        TRANSFER
3      P3        CREDIT CARD

Table PERSONS
ID   ID_PERSON   PersonName
1      123        GEORGE
2      124        HENRY
3      125        MICHAEL
4      126        ANNA

Table INVOICE_IN
ID   ID_INVOICE_IN   Person_ID  Amount PaymentType_ID
1      II-001            1       100      1
2      II-002            2       200      1
3      II-003            4       300      2

Table INVOICE_OUT
ID   ID_INVOICE_OUT   Person_ID  Amount     PaymentType_ID
1      IO-001                 1       500      2
1      IO-002                 3       600      3

I want the result like this:
ID_INVOICE_IN PaymentCode  PersonName  Amount ID_INVOICE_OUT PaymentCode  PersonName  Amount
II-001            P1         George     100        IO-001     P2          George      500
II-002            P1         Henry      200        IO-002     P3       Michael       600
II-003            P2         Anna       300         NULL      NULL       NULL      NULL

I have a query like this:
SELECT INVOICE_IN.ID_INVOICE_IN, PaymentType.PaymentCode, PERSONS.PersonName, INVOICE_IN.Amount FROM INVOICE_IN LEFT JOIN PaymentType ON PaymentType.id = INVOICE_IN.PaymentType_ID LEFT JOIN PERSONS ON PERSONS.id = INVOICE_IN.Person_ID

The query successfully shows 4 columns for invoice_in.
and I also have a query like this:
SELECT INVOICE_OUT.ID_INVOICE_OUT, PaymentType.PaymentCode, PERSONS.PersonName, INVOICE_OUT.Amount FROM INVOICE_OUT LEFT JOIN PaymentType ON PaymentType.id = INVOICE_OUT.PaymentType_ID LEFT JOIN PERSONS ON PERSONS.id = INVOICE_OUT.Person_ID

The query successfully shows 4 columns for invoice_out
I need to combine between result1 (invoice_in) and result2 (invoice_out), so the result of query has 8 columns.

A: If I understood you right it seems that what you want to do is to show to unrelated sets of data next to each other.
One way to do this is to number the rows in each set and do a left join with the larger set as the left side. (A better way would be to use a full outer join but MySQL does not support that although the same effect can be achieved using left/right joins w/ union). With MySQL you would use user variables to number the rows.
This query gives the result from your example, although I don't really see the point of showing unrelated data side by side. (If it really is unrelated... there's nothing in the question that suggests it is related).
select
  t1.id_invoice_in, t1.paymentcode, t1.personname, t1.amount,
  t2.id_invoice_out, t2.paymentcode, t2.personname, t2.amount
from (
  select
    id_invoice_in, paymentcode, personname, amount,
    (@r1 := @r1 + 1) as r1
  from invoice_in
  join paymenttype pt on pt.id = paymenttype_id
  join persons p on p.id = person_id
  ,(select @r1 := 0) r
) t1 left join (
  select
    id_invoice_out, paymentcode, personname, amount,
    (@r2 := @r2 + 1) as r2
  from invoice_out
  join paymenttype pt on pt.id = paymenttype_id
  join persons p on p.id = person_id
  ,(select @r2 := 0) r
) t2 on t1.r1 = t2.r2;

Sample SQL Fiddle

A: SELECT
    `In`.`ID_INVOICE_IN`,
    `PayI`.`PaymentCode`,
    `PersI`.`PersonName`,
    `In`.`Amount`,
    `Out`.`ID_INVOICE_OUT`,
    `PayO`.`PaymentCode`,
    `PersI`.`PersonName`,
    `Out`.`Amount`
FROM
    `INVOICE_IN`  AS `In`,
    `INVOICE_OUT` AS `Out`,
    `PERSONS`     AS `PersI`,
    `PERSONS`     AS `PersO`,
    `PaymentType` AS `PayI`,
    `PaymentType` AS `PayO`
WHERE
    `In`.`ID`              = `Out`.`ID`   AND
    `In`.`Person_ID`       = `PersI`.`ID` AND
    `Out`.`Person_ID`      = `PersO`.`ID` AND
    `In`.`PaymentCode_ID`  = `PayI`.`ID`  AND
    `Out`.`PaymentCode_ID` = `PayO`.`ID`
ORDER BY
    `In`.`ID_INVOICE_IN`


text:
Q: Redefine figure counter with scrbook I am using the scrbook (KOMA Script) class, as this MWE shows:
\documentclass[11pt,a5paper,twoside,BCOR=8mm,DIV=12,headings=normal,open=right]{scrbook}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\usepackage{chngcntr}

\begin{document}
\part{Introduction}
\chapter{Lorem ipsum}

\counterwithout{figure}{chapter}

\begin{figure}[h!]
    My figure here.
    \caption{My caption}
\end{figure}
\end{document}

It's working, by and large, with one exception: The caption reads

Abbildung 1.: My caption

Notice the superfluous dot before the colon? It's clearly due to using parts; if I stick to chapters and sections only it's formatted as intended.
Any bright ideas?

A: By default, the KOMA-Script classes will add a period at the end of sectioning numbers, float numbers etc. if a \part or \appendix command was issued. To counter this behaviour, add the class option numbers=noendperiod. See section 3.16 of the KOMA-Script manual for further details.
If you want to change the default behaviour only  for figure and table captions, add the following to your preamble:
\renewcommand*{\figureformat}{%
  \figurename~\thefigure%
%  \autodot% DELETED
}
\renewcommand*{\tableformat}{%
  \tablename~\thetable%
%  \autodot% DELETED
}


text:
Q: What is wrong with Map>? I'm trying to build a data structure in Java where I'll be inserting about 200,000 Keys of strings each with "an average" of 1000 Integers Map<String, Arraylist<Integer>>. The map will eventually have around 200 millions of values.
The problem is that While inserting, I have to first check if the key is existed in the map, if true, get all values stored in a temp collection then add the new integer to the collection and put them back to map, or instantiate a new collection with a new integer.
This is so slow when I get to the point where a collection contains around 50000 integers. I usually got a java out of heap space error.
Is there a way to get rid of the get process? where I only check for the key existence and then immediately add the value to the existed collection, something like posh to a stack, especially that the map is in the memory, or is it what makes the difference between Java and C++, where in C++ I can benefit from using pointers?
Keeping the fact that I dont prefer to increase the size of the map by using things like multimaps, as the structure seems almost straightforward.
Many thanks in advance.

A: If your code is actually doing what your question suggests, you are working too hard.  Once you've got your Key associated with the ArrayList.  Just get the ArrayList out of the map and add the new integer to that list.  You don't need to "put it back".  The reference to the List is all you need to change the List.
    Map<String, ArrayList<Integer>> m = new HashMap<String, ArrayList<Integer>>();
    for ( int i = 0; i < 5; i++ ) {
        String key = ( i % 2 == 0 ) ? "Bob" : "Robert";
        ArrayList<Integer> l = m.get( key );
        if ( l == null ) {
            l = new ArrayList<Integer>();
            m.put( key, l );
        }
        l.add( i );
    }
    System.out.println( "m is " + m );

In my opinion, though, Guava Multimap is a far better solution to this problem:  http://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html

A: *

*There is a huge performance overhead related to the HashMap resize. When you create new HashMap with no-arg constructor, its size is by default 16. You put more and more elements in it, so any time you exceed available space, it needs to resize. Resizing involves calculating hash codes for every key and moving keys between hashtables. It's very expensive.

If you know your HashMap will store a lot of keys, you can create it with size of, for instance, 200,000.

*ArrayList has default capacity of ten. If you put more elements, it needs to resize. This involves creating new array (in which ArrayList internally stores elements) and copy elements from the old array to the new one. This also can be very expensive on large ArrayLists.

I would suggest using LinkedList instead. Adding new elements to it is really cheap, as elements are stored as independent nodes. However, there are some drawback. Please see this question for details.

*You have to be able to reserve enough memory for 200,000,000 objects. As Tom Hawtin suggested, increasing maximum heap space used by JVM may be necessary. Java is not C++, you can't just use more and more memory.


text:
Q: POCO and MVC 4 Models I've just created my first MVC project.  My question is with MVC is it common practice to create POCO classes or just create the objects in the Models ?

A: Depends on complexity of your domain(business) logic.
Although it is not "by the book" you can use POCO classes as Models for Views.
I personally would split them, at least created lowest common dominator as an interface

A: Totaly agree with Dejan Dakić. I will try to give a little bit extended answer.
If you have the one-layer solution with little amount of bussines logic, then it definetly will be faster to combine POCO object and Models in mvc. This will help you to make the little application many time faster then dividing the POCO and Model classes.
But If you have huge solution with extended architecture then you should make POCO object and models separately. Because letting know your Presentation layer about the objects in your Data Access Layer is bad move. DAL and Presentation layer should be divided with the Business Layer. "By the book", Presentation Layer know about the Business layer, Business layer knows about Data access Layer. And everybody knows about the Common layer (if you have such a layer). POCO object should belong to Data Access Layer but mvc Models should belong to Presentation layer.
Hope it helps.


text:
Q: Array with type  not working, Error Cannot resolve Name to a Type I'm trying to write a program that let's me enter multiple Objects of the same Class, Drinks in my Case, into an Array.
When trying to create the Array, i can't set the Type to my Object. I feel like i'm missing something very obvious, i'd appreciate any help!
This is the code i have so far. The names are in german, hope that's not a problem.
import java.util.ArrayList;

public class KellnerGetraenkeliste {

// Erstellen der Attribute
private String kunde;
private int anzahl;
private String getraenk;

private KellnerGetraenkeliste(String kunde, int anzahl, String getraenk) {
    super();
    this.kunde = kunde;
    this.anzahl = anzahl;
    this.getraenk = getraenk;
}

ArrayList<getraenk> getraenkeListe = new ArrayList<getraenk>();

}

A: The generic specified between  square brackets  has to be a class, not a variable name.
In your case it should be a String such as :
ArrayList<String> getraenkeListe = new ArrayList<String>();

Note that it would be better to declare an interface as declared type and to use the diamond operator for the instantiation to not repeat the generic such as :
List<String> getraenkeListe = new ArrayList<>();


text:
Q: I need to save the User Name and email address separately. I am am having an issue with logging into the site after the user is registered I am creating a new ASP.NET Core (2.2) WebSite. By default, the UserName and Email Address is the same thing. I want to have them be different. The issue comes in when I try to log that user back into the web page.
I scaffolded the register Identity page and made some simple changes to the Code behind and also the Razor page itself (see below). I did also scaffold the login page, but I don't think that I need to make any changes there, because I am ok with folks logging in using their email address still.
Here are the edits to the Register.cshtml.cs page.
I added this to the InputModel class:
[Required]
[StringLength(256, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 5)]
[DataType(DataType.Text)]
[Display(Name = "User Name")]
public string UserName { get; set; }

I also changed the user in the OnPostAsync method
var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };

Everything else is as default.
On the page itself, I simply added it below the email:

    <input asp-for="Input.UserName" class="form-control"/>

I would expect for the user to be logged in as normal, alas. The error I get is simply "Invalid Log-in attempt". Annoyingly, The user I created before making any changes still is able to be logged in just fine. So my gut tells me that Something is funny in the register page, I am just not sure where.

A: You have to modify SignInManager.PasswordSignIn method. By default it uses FindByNameAsync to check if user with given name exists , you should change to FindByEmailAsync .

*

*Create new SignInManager :
public class MySignInManager : SignInManager<IdentityUser>
{
    public MySignInManager(Microsoft.AspNetCore.Identity.UserManager<Microsoft.AspNetCore.Identity.IdentityUser> userManager, Microsoft.AspNetCore.Http.IHttpContextAccessor contextAccessor, Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<Microsoft.AspNetCore.Identity.IdentityUser> claimsFactory, Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Identity.IdentityOptions> optionsAccessor, Microsoft.Extensions.Logging.ILogger<Microsoft.AspNetCore.Identity.SignInManager<Microsoft.AspNetCore.Identity.IdentityUser>> logger, Microsoft.AspNetCore.Authentication.IAuthenticationSchemeProvider schemes)
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
    {
    }

    public override async Task<SignInResult> PasswordSignInAsync(string userName, string password,
        bool isPersistent, bool lockoutOnFailure)
    {
        var user = await UserManager.FindByEmailAsync(userName);
        if (user == null)
        {
            return SignInResult.Failed;
        }

        return await PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);
    }
}

*Register the SignInManager:
services.AddDefaultIdentity<IdentityUser>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddSignInManager<MySignInManager>()   //register new SignInManager
    .AddEntityFrameworkStores<ApplicationDbContext>();


text:
Q: Phonegap working with Android but not with iOS, Error Code I am getting this error code when i open a phonegap html site in iOS:
gap:["Device","getDeviceInfo","Device341875241"]
gap:["NetworkStatus","getConnectionInfo","NetworkStatus341875242"]
gap:["App","show","App341875243"]

It is working with Android perfectly.. i am using cordova 2.7.0.
What´s that supposed to mean?
thanks!

A: You must add the correct cordova-2.7.0.js file that is specific to iOS. This error usually occurs when you add cordova JS file which is not specific to a particular platform. In other words, you should add the iOS specific cordova-2.7.0 JS file to your iOS PhoneGap project.
Possible scenario:
You might have wrongly included the Android specific cordova-2.7.0 JS file in your iOS project.
Fix:
Just remove the current cordova JS file and add the cordova-2.7.0.js file from iOS folder in the downloaded Phonegap-2.7.0 folder


text:
Q: CodeIgniter use different 404 page on front-end and back-end Hi I'd like to ask a question please. I'm building a project in which I'm having this folder structure:
application
- controllers
-- posts.php // this is on frontend
-- admin
--- posts.php // this is on backend obviously

So in both cases if I try to access from the url a post that doesn't exist I'll do something like this
$data['post'] = $this->post_model->get_by_id($id);
count($data['post']) || show_404(); // Return 404 if post not found

which shows the default 404 Codeigniter page.
Is it possible to set a different 404 page for front end and back end and if so how can I do this ?
The only options I have thought so far are these:

*

*Have the same custom 404 page for both front end and back end, in which case I only have to set a different 404 view to the default file, but I don't think its the best option.

2 (not tested). Create 2 different controllers and views, like this
applicatiom
- controllers
-- front404.php
-- admin
--- admin404.php

so when I check if the post exist, it would become like this
 count($data['post']) || redirect('admin/admin404'); // on back-end
count($data['post']) || redirect('admin/front404'); // on front-end

3 (not test). A similar to 2nd option, but setting the $route['404_override'] = ''; dynamically ??
However I was wondering if there's a more efficient way of doing this. Btw I'm using CodeIgniter v3.

A: When you have
application/controllers/Error404.php and application/controllers/admin/Error404.php,
setting $route['404_override'] to 'Error404' will cause admin/Error404.php to be loaded if you visit /admin/non-existing-uri.
I do have to say this though - you shouldn't 404 based on whether items exist in a list or not. The list itself still exists, even if empty.
application/controllers/admin/Error404.php

application/controllers/Error404.php

Your Router settings should be as below
$route['404_override'] = 'Error404';

Thats it.


text:
Q: Inject CSS styles inside of the shadow-root instead of the head tag | Vue.js & Webpack I'm making an embeddable widget for websites using Vue.js and vue-custom-element. Everything was going smoothly until I ran into a problem.
When I'm trying to use a component (with css) from a package. Like vue-number-input for example. The css gets injected in the head of the webpage even though it should be added inside the shadow root.
As you can see here you see that the css from the number input package is injected inside the head while the other stylings are in the shadow root like they should.
As far as I know I changed all of the settings needed to make the application work inside a shadow root.
This is my vue.config.js, my main.js (where I register the custom element) and my component (where I import the component from the package).
Does anyone know how I can do this or is this even possible?

A: If the library is itself embedding the styles to the head of the page, then there is nothing you can do other than to write some script to manually copy it into the shadow dom after initialization. I ran into the same issue for Font Awesome icons. Luckily, they provided a fix for this. (https://github.com/FortAwesome/vue-fontawesome#web-components-with-vue-web-component-wrapper)

A: After a lot of research for a solution which actually lazy-loaded our styles into the shadow-root, we didn't find one. We went with suboptimal solution which is loading all the styles on first load.
Note: This makes it work for QA and production environments. When developing, the styles will still be loaded inside of the head of the page. So you have to make sure no other styles conflict with that.
This was our way of accomplishing this:
// vue.config.js

const webpack = require('webpack');

module.exports = {
  configureWebpack: {
    // ...
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 1,
      }),
    ],
  },
  chainWebpack: (config) => {
    config.optimization.delete('splitChunks');
  },
};

// main.js

import createStyleLink from '@/helpers/createStyleLink';

// ...

const options = {};

// Enable shadow root for production build
if (process.env.NODE_ENV === 'production') {
  options.shadow = true;
  options.beforeCreateVueInstance = (root) => {
    const rootNode = root.el.getRootNode();
    if (rootNode instanceof ShadowRoot) {
      root.shadowRoot = rootNode;
    } else {
      root.shadowRoot = document.head;
    }
    // After deployment, this will create a style link and put it inside the shadow root.
    // Preferably, you would use a CDN for this.
    createStyleLink(rootNode, `${process.env.VUE_APP_URL}/css/app.css`);
    return root;
  };
}

// ...

Vue.customElement('widget', App, options);

// createStyleLink.js

export default function (node, url) {
  const link = document.createElement('link');
  link.href = url;
  link.type = 'text/css';
  link.rel = 'stylesheet';
  node.appendChild(link);
}

I'll not mark this as a solution as this is more like a suboptimal workaround.


text:
Q: What is the best approach to minifying CSS and JS files in Drupal 7? I'm currently in the process of improving the performance of a Drupal site that I'm working on. I am currently using the Grunt task runner to concatenate and minify my JS and CSS, and I'm wanting to do the same for the core Drupal files.
I have currently aggregated the CSS and JS in the CMS (configuration > development > performance), I was wondering whether there are any reliable modules / settings that can enhance this functionality further?

A: Minify is designed to improve the website performance.
This module provides the mechanism to render the page using minified version of HTML and JavaScript files.
Minified HTML is generated using regular expression, and JavaScript files are generated using GOOGLE Closure Compiler webservice. Minify also works perfectly with Boost module.
https://www.drupal.org/project/minify


text:
Q: Closing a threaded loop The code I am working on needs to use a serial port event (connecting pins 5 and 8 with a contact switch) to trigger a function (playing music), within a GUI application. I have created a loop to monitor the serial port and have this running within a separate thread from the pygtk GUI.
I an testing this from the command line. When the GUI is closed, the monitoring thread does not immediately close. It stays open until the event is triggered (the contact switch pressed) again then it will close.
I do not want users to need to press a switch to properly close a program!
A simplified version of the code is:
#!/usr/bin/python2

import sys
import subprocess
import pygtk
pygtk.require('2.0')
import gtk
import threading
import gobject
from serial import Serial
from fcntl import  ioctl
from termios import (
    TIOCMIWAIT,
    TIOCM_RNG,
    TIOCM_DSR,
    TIOCM_CD,
    TIOCM_CTS
)

ser = Serial('/dev/ttyS0')
wait_signals = (TIOCM_RNG |
                TIOCM_DSR |
                TIOCM_CD  |
                TIOCM_CTS)

def startplaying():
    #for testing
    print('Start playing the track!')

gobject.threads_init()

class SerialWatch(threading.Thread):

    def __init__(self):
        super(SerialWatch, self).__init__()
        self._stop = threading.Event()

    def run(self):
        if __name__ == '__main__':
            while not self._stop.isSet():
                ioctl(ser.fd, TIOCMIWAIT, wait_signals)
                startplaying()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

class MusicManager():

    def delete_event(self, widget, event, data=None):
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)
        self.window.show_all()

    def main(self):
        gtk.main()

sw = SerialWatch()
sw.start()

print __name__
if __name__ == "__main__":
    music_manager =  MusicManager()
    music_manager.main()

sw.stop()

I am not an experienced programmer and would appreciate any help with this.

A: For anybody who might find this post and is interested in how I got things to work the way I wanted:
I did not want to use polling as smichak suggested. However my attempts to use threads to run the TIOCMIWAIT loop failed as it interfered with the GUI loop.
What I have done is to write a separate python script to watch the serial port with the TIOCMIWAIT loop and to run this script as a subprocess from the main GUI program. This way the script is launched when the GUI is opened and it is killed when the GUI is closed. When a connection is made on the serial port, the script uses dbus to communicate to the GUI and run the required function.


text:
Q: Problem with compiz saving key bindings I use Blender on Ubuntu, and need to free a shortcut. The key combination is Ctrl+Alt+Numpad0. In CCSM this shortcut is listed under general settings > Keybindings. But when i edit this setting, nothing changes. And when i restart CCSM they old key combination is back. Any ideas how to fix this?

A: CCSM forces certain shortcuts after reboot.
If you uninstall CCSM you can permanently set shortcuts with System settings > Keyboard > Shortcuts.


text:
Q: How to create preconfigured fake debit card, for testing paying without paypal's account in sandbox? I dont want to put real visa card information for testing paying in sandbox.
Is any way to create preconfigured card for testing?

A: Any Visa card adhering to the Luhn algorithm will work.
However, there are a few things to consider.

*

*If 'Negative Review' is enabled on the Sandbox test account, using a certain amount, CVV code or expiry date can trigger a decline. 'Negative review' is intended to test error scenario's, and depends on you setting a certain CVV code or amount in order to trigger an error response. To avoid this, I would recommend always using a CVV code of '000', which will always succeed.

*Not all card types are supported in Sandbox. E.g. Amex may be troublesome. It's best to test with Visa.

*PayPal Sandbox doesn't connect to any processors, and as such there is no actual card validation taking place. Any expiry date in combination with any card number (providing the card type is acceptable) and any CVV code will work.

For example the following card numbers would be great to test with;
Card type: VISA
Expiry date (all cards): any date in the future. E.g. 05/2018
CVV code (all cards): 000
Any Visa card number from http://www.darkcoding.net/credit-card-numbers/

A: There are plenty of test credit card numbers to use. No need to use a real one.


text:
Q: Inverted search in Python I'm trying to implement an inverted search as part of map reduce, first part of which I was able to complete (mapper). The output of first part looks something like below
(headings are for reference, these are not in actual output of mapper)
word     frequency     document
------------------------------
tire        1           car
headlight   1           shop
tire        1           car
gas         1           gasstation
beer        1           gasstation
headlight   1           car
tire        1           shop

I'm trying to get to below solution:
The word is found in which file, along with its frequency. (for example tire is found twice in car file)
Until now I have tried using dictionary to get the files in which the word is found, but I am unable to link it to get count, below is the output I'm getting:
{'car':[tire,tire,headlight],'shop':[headlight],'gasstation':[gas,beer]}

Expected:
tire           {'car':2,'shop':1}
headlight      {'car':1, 'shop':1}

A: What you want is to reduce the dict you have to group the elements in your list.
Assuming the output of your mapping is a list of dicts like this:
mapped_data = [
    { 'word': 'tire', 'frequency': 1, 'document': 'car' },
    { 'word': 'headlight', 'frequency': 1, 'document': 'shop' }
]

Then you could do something like:
def reducer(accumulated, line):
    # We've never seen this word before, create the dict to store the documents
    if line['word'] not in accumulated:
        accumulated[line['word']] = {}

    # We've never seen this word in this document before, initialize the counter.
    if line['document'] not in accumulated[line['word']]:
        accumulated[line['word']][line['document']] = 0

    # Increment th counter
    accumulated[line['word']][line['document']] += line['frequency']

    return accumulated_data

reduce(reducer, mapped_data, {})

This would produce the expected result:
{
    'tire': {
        'car': 2,
        'shop': 1
    },
    'headlight': {
        ...
    },
    ...
}


text:
Q: How can I install large Apps from App Store on and external disk I can't download extremely large games, because App Store says there's "not enough space to install the product."
This is not unexpected, but I do have a USB-C 2TB SSD always connected and I'd like to install things there.
Is there a way to change where games get installed from App Store?

A: No. Move other files to the external drive to free up space. Then once you have installed the app, move it after it's done downloading and installing.
You need free space on the system drive for many reasons and one is App Store and installing apps.

A: The existing answer is correct. You can't install them to the external drive. And guess what? If you move them to the external drive, the App Store will lose track of them and offer to download them all over again! Always remember to max out the internal storage when buying a Mac. Can't afford that? Save up for longer!