text:
Q: MySQL matching row values sets I am relatively new with mysql and php. I have developed a hockey stat db. Until now, I have been doing pretty basic queries and reporting of the stats.
I want to do a little more advanced query now.
I have a table that records which players were on the ice (shows as a "fk_pp1_id" - "fk_pp5_id") when a goal is scored.  here is the table:

pt_id  | fk_gf_id  | fk_pp1_id  | fk_pp2_id  | fk_pp3_id  | fk_pp4_id  |  fk_pp5_id
1      |     1     |     19     |     20     |     68     |     90     |     97
2      |     2     |     1      |     19     |     20     |     56     |     91
3      |     3     |     1      |     56     |     88     |     91     |     93
4      |     4     |     1      |     19     |     64     |     88     |     NULL
5      |     5     |     19     |     62     |     68     |     88     |     97
6      |     6     |     55     |     19     |     20     |     45     |     62
7      |     7     |     1      |     19     |     20     |     56     |     61
8      |     8     |     65     |     68     |     90     |     93     |     97
9      |     9     |     19     |     20     |     45     |     55     |     62
10     |     10    |     1      |     19     |     20     |     56     |     61
11     |     11    |     1      |     19     |     20     |     56     |     61
12     |     12    |     19     |     20     |     68     |     90     |     97
13     |     13    |     19     |     20     |     68     |     90     |     97
14     |     14    |     19     |     20     |     55     |     62     |     91
15     |     15    |     1      |     56     |     61     |     64     |     88
16     |     16    |     1      |     56     |     61     |     64     |     88
17     |     17    |     1      |     19     |     20     |     56     |     61
18     |     18    |     1      |     19     |     20     |     56     |     61
19     |     19    |     1      |     65     |     68     |     93     |     97

I want to do several queries:

*

*Show which of the five players were together on the ice most often
when a goal was scored.

*Select say 2 players and show which other players were on the ice most often with them when a goal was scored.

I was able to write a query which partially accomplishes query #1 above.

SELECT
fk_pp1_id,
fk_pp2_id,
fk_pp3_id,
fk_pp4_id,
fk_pp5_id,
count(*)
FROM TABLE1
group by
fk_pp1_id,
fk_pp2_id,
fk_pp3_id,
fk_pp4_id,
fk_pp5_id

Here are the results:

fk_pp1_id    fk_pp2_id     fk_pp3_id       fk_pp4_id       fk_pp5_id       count(*)
1               19            20              56              61              4
1               19            20              56              91              1
1               19            64              88            (null)            1
1               56            61              64              88              2
1               56            88              91              93              1
1               65            68              93              97              1
19               1            20              56              61              1
19              20            45              55              62              1
19              20            55              62              91              1
19              20            68              90              97              3
19              62            68              88              97              1
55              19            20              45              62              1
65              68            90              93              97              1             4

See this sqlfiddle:
http://sqlfiddle.com/#!9/e3f5f/1
This seems to work at first, but I realized this query, as written, is sensitive to the order in which the players are listed.  That is to say a row with:
1, 19, 20, 68, 90
will not match
19, 1, 20, 68, 90
So to fix this problem, I feel like I have a couple options:

*

*Ensure the data is input into the table in numerical order

*Re-write the query so the order of the data in the table doesn't matter

*Make the resulting query a sub-query to another query that first
orders the column (left to right) in numerical order.

*Change the schema to record/store the data in a better way
1, I can do, but would prefer to have the query be fool-proof.
2 or 3 I prefer, but don't know how to do either.
4, I don't know how to do and is least desirable as I already have some complex queries against this table that would need to be totally re-written.
Am i going about this in the wrong way or is there a solution??
Thanks for your help
UPDATE -
OK I (hopefully) better normalized the data in the table.  Thanks @strawberry.  Now my table has a column for the goal_id (foreign key) and a column for the player_id (another foreign key) that was on the ice at the time the goal was scored.
Here is the new fiddle:
http://sqlfiddle.com/#!9/39e5a
I can easily get the one player who was on the ice most when goals are scored, but I can't get my mind around how to find the occurrences of a group of players who were on the ice together.  For example, how many times were a group of 5 players on the ice together.  Then from there, how often a group of 2 players were on the ice together with the 3 other players.
Any other clues???

A: I find a similar problem here and based on that i come up with this solution.
For the first part of your problem to select how many time same five player were on the ice when the goal is scored your query could look like this:
SELECT GROUP_CONCAT(t1.fk_gf_id) AS MinOfGoal,
       t1.players AS playersNumber,
       COUNT(t1.fk_gf_id) AS numOfTimes
FROM (SELECT fk_gf_id, GROUP_CONCAT(fk_plyr_id ORDER BY fk_plyr_id) AS players
      FROM Table1
      GROUP BY fk_gf_id) AS t1
GROUP BY t1.players
ORDER BY numOfTimes DESC;

And for your second part of the question where you want to select two players and find three more player which were on the ice when goal were scored you should extend previous query whit WERE clause like this
SELECT GROUP_CONCAT(t1.fk_gf_id) AS MinOfGoal,
       t1.players AS playersNumber,
       COUNT(t1.fk_gf_id) AS numOfTimes
FROM (SELECT fk_gf_id, GROUP_CONCAT(fk_plyr_id ORDER BY fk_plyr_id) AS players
      FROM Table1
      WHERE fk_gf_id IN (SELECT fk_gf_id
                        FROM Table1
                        WHERE fk_plyr_id = 19)
      AND fk_gf_id IN (SELECT fk_gf_id
                       FROM Table1
                       WHERE fk_plyr_id = 56)
      GROUP BY fk_gf_id) AS t1
GROUP BY t1.players
ORDER BY numOfTimes DESC;

You can see how it's work here in SQL Fiddle...
Note: I added some data in Table1 (don't be confused with more date counted).
GL!


text:
Q: Matrices with elements that are a distinct set of prime numbers: always invertible? Inspired by a previous question, given a square non-symmetric matrix whose elements are all prime but distinct from each other, does this guarantee that the matrix is invertible? It's easy to see $N=2$ this holds, a counter-example would imply that there must be four distinct primes such that $p_1 p_2 = p_3 p_4$.

A: A $4 \times 4$ counterexample is
$$\pmatrix{43 & 17 & 53 & 19 \cr
11 & 71 & 3 & 89 \cr
79 & 47 & 29 & 37 \cr
31 & 7 & 61 & 13 \cr
}$$

A: No. To find a $3 \times 3$ counterexample it suffices to write down three $3$-term prime arithmetic progressions with the same common difference $d$. By inspection $\bmod 2,3$ the smallest possible such difference is $d = 6$, which gives
$$\left[ \begin{array}{ccc} 5 & 11 & 17 \\
 7 & 13 & 19 \\
 31 & 37 & 43 \end{array} \right].$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to ensure Django updates html to reflect changes? Expected Result:
I expect to see
B
 when I edit my home page from
A
  to
B
, save changes in the editor, and refresh the browser.
Actual Results:
I'm seeing
A
 when I edit my home page from
A
  to
B
, save changes in the editor, and refresh the browser.
A week ago I was getting the "Expected results" but I noticed a few days ago I'm getting the results explained in "Actual Results". Now Only when I restart the server by running docker-compose up restart I'm getting the expected results.
Why simple HTML changes not being updated when I refresh the browser? I'm using Django 3.1 and Python 3.7.
Edit:
Docker file:
# Pull base image
FROM python:3.7-slim

# Set environment varibles
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /projects

# Install dependencies
COPY Pipfile Pipfile.lock /projects/
RUN pip install pipenv && pipenv install --system

# Copy project
COPY . /projects/

docker-compose.yml
version: "3.7"
services:
  web:
    build: .
    command: python /projects/manage.py runserver 0.0.0.0:8000
    # command: gunicorn guyanaNPPM_project.wsgi -b 0.0.0.0:8000
    environment:

      - "DJANGO_SECRET_KEY=hidden for security reasons"
      - "DJANGO_DEBUG=True"
      - "DJANGO_SECURE_BROWSER_XSS_FILTER=True"
      - "DJANGO_SECURE_SSL_REDIRECT=False"
      - "DJANGO_SECURE_HSTS_SECONDS=0"
      - "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False"
      - "DJANGO_SECURE_HSTS_PRELOAD=False"
      - "DJANGO_SESSION_COOKIE_SECURE=False"
      - "DJANGO_CSRF_COOKIE_SECURE=False"

    volumes:
      - .:/projects
    ports:
      - 8000:8000
    depends_on:
      - db
  db:
    image: postgres:11
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - "POSTGRES_HOST_AUTH_METHOD=trust"

volumes:
  postgres_data:

A: Try docker-compose stop ; docker-compose rm -f ; docker-compose pull before you use docker-compose to launch your django project.
If this suggestion works, then you may forget to update your docker image when relaunching your django project, or your local source does not sync up with the code base in the running docker container instance.


text:
Q: Storing protocol/delegation results in the correct Object I've created a User class with a User object allocated in the first view controller.  While in the first view controller, a few of the objects properties are filled with some data.  I'm using a second view controller to obtain additional user information and then send it back to the first view controller to store in the remaining object properties.  I'm using a protocol and delegation to get this done.  I followed the instructions here:
Passing Data between View Controllers
Looks like I did everything correctly, except i don't know how to associate the results with the properties of my object.  It would be nice to be able to return to the original method in the first view controller that calls the second view controller.  Is this possible?  A lot of the answers I'm seeing are requiring global variables, but I'm not sure if thats necessary for my case.
/**Implementation of Main View Controller **/
-(IBAction)signUpButton
{

    User * firstUser = [[User alloc] init];

    firstUser.userName = userNameField.text;
    firstUser.password = passwordField.text;

    /**second view controller **/

    SetUp *setUpView = [[SetUp alloc] initWithNibName:Nil bundle:Nil];

    setUpView.delegate = self;

    [self presentViewController:setUpView animated:YES completion:^{ }];

    firstUser.zone = holdZoneInfo;
    firstUser.area= holdAreaInfo;

    NSLog(@"first User %@, %@, %@, %@",firstUser.userName, firstUser.password, firstUser.zone, firstUser.area);

    /**username and password display fine, but zone and area are null since the delegation operation hasn't been completed as this point **/

}

/**Protocol Method Declared in Main View Controller**/
-(void) sendUserInfoBack: (SetUp *) SetUpController didFinishWithZone:(NSString*)item1 didFinishWithArea:(NSString*) item2
{

    holdZoneInfo = item1;
    holdAreaInfo = item2;

    NSLog(@"Delegation result: %@ %@", holdZoneInfo, holdAreaInfo);
    /**This displays correctly**/

}

/**Second view controller implementation file**/

-(IBAction)goToMainView:(id)sender
{
    NSString * neededZoneStore = zoneField.text;
    NSString * neededAreaStore = areaField.text;

    User * user = [[User alloc] init];

    user.zone = neededZoneStore;
    user.area = neededAreaStore;

    [self.delegate sendUserInfoBack:self didFinishWithZone: neededZoneStore didFinishWithArea: neededAreaStore];

    [self dismissViewControllerAnimated:YES completion:NULL];
}

So I need firstUser.zone = holdZoneInfo but I'm unable to make this happen

A: In your SetUp view controller class, declare a user property of the type User. When you alloc/init a SetUp view controller set the user property to the firstUser. When the SetUp view controller calls the delegate method, return the firstUser object.
And let the SetUp view controller fill the User object with data from the user.
// in signUpButton
setUpView.user = firstUser;

Refactor the name of the delegate method:
- (void)setUpViewController:(SetUp *)controller exitedWithUser:(User *)user;


text:
Q: How to limit the amount of characters entered So, I'm working on a simple password program. I've got this code so far
/* simple  password prog */
#include<stdio.h>
#include<string.h>
int main(){
        char usrIn[9];
        char password[]={"AXcd8002"};
        do {

        fprintf(stdout,"\n Password:");
        fgets(usrIn,9, stdin);
        if  ( strcmp(usrIn,password)<0 || strcmp(usrIn,password )>0 ) {
        fprintf(stdout,"\n Password incorrect"); };

        }while( (strcmp(password,usrIn))!=0 );

fprintf(stdout, "\n The password is correct \n");
return 0;
}

This code works correctly, if the password is incorrect, the loop will keep going, if it's correct - loop will break. But what doesn't work is this: If the user enters a password with at least one character longer, the program will still say it is correct.
For instance, if user enters AXcd8002AAA, fgets will read only AXcd8002 , and ignore AAA. How can I prevent this from happening?

A: usrIn has only 9 characters, of course the extra characters are ignored. Just give usrIn enough space:
char usrIn[100];

And as a best practice:
fgets(usrIn, sizeof(usrIn), stdin);

There's another problem that you didn't consider: the new line character '\n' is considered a valid character by fgets, so it's also in usrIn, you need to remove it manually before comparing passwords.

A: Without giving the size of the usrIn giving it dynamic size & performing dynamic input will insert the full password into the array usrIn.


text:
Q: How do you find the number of occurrence within a list of dictionaries I'm trying to find how many times per case_id does email_response occurs in the example below:
json_obj = [{
    'case_id': 1000,
    'type': 'email',
    'customer_id': 42571,
    'date': '2015-01-20',
},
    {
    'case_id': 1000,
    'type': 'email_response',
    'customer_id': 42571,
    'date': '2015-01-21',
},
    {
    'case_id': 1021,
    'type': 'email',
    'customer_id': 88686,
    'date': '2015-01-24',
}]

So in this case, the answer would be 1 for case_id = 1000 and 0 for case_id = 1021.

A: You can create another dictionary and keep on updating the count like this
>>> result = {}
>>> for obj in json_obj:
...     if obj['type'] == 'email_response':
...         result[obj['case_id']] = result.get(obj['case_id'], 0) + 1
...
>>> result
{1000: 1, 1021: 0}

Since we pass 0 as the second parameter, the dict.get method will return 0 if it cannot find the key being retrieved, otherwise the actual value corresponding to the key. You can do the same like this
>>> result = {}
>>> for obj in json_obj:
...     result[obj['case_id']] = result.get(obj['case_id'], 0) + (obj['type'] == 'email_response')
...
>>> result
{1000: 1, 1021: 0}

Since Python's booleans are subclasses of int, True will be 1 and False will be 0. So, the result of (obj['type'] == 'email_response') will be added with the current value of case_id in the result dictionary.


text:
Q: Accessing to target values in vba simultaneously I have a code what it basically do is: i want to access two triggers or target values and based on their respective values, it perform on action. Ex:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Column = 19 And Target.row = 17 Then
        If Target.Value = "Yes" Then
'do something
End if
End Sub
If Target.Column = 20 And Target.row = 18 Then
        If Target.Value = "Yes" Then
'do something
End if
End Sub

What this does is, it only checks one trigger value at a time. When trigger1.value changes, it doesn't check trigger2.value
However what i really wanted to do is:
if triger1.value = "Yes" and triger2.value = "yes" then
'' do something
elseif triger1.value = "No" and triger2.value = "yes"
'' do another thing
end if
and so on

my question now is: how can i access the two triggers simultaneously and if the value one trigger is updated, it will check the second trigger value and decide what to do. Any help or suggestion is highly appreciated!

A: I think you want something like this:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)

    Dim trigger1 As Range, trigger2 As Range
    Set trigger1 = Me.Range("S17")
    Set trigger2 = Me.Range("T18")

    If Not Intersect(Target, Union(trigger1, trigger2)) Is Nothing Then
        If trigger1.Value = "Yes" And trigger2.Value = "Yes" Then
            'do something
        End If
    End If

End Sub

Any time either of the triggers is changed, this will check to see if both triggers are set to "Yes". If they are then the code will run (if you change the "do something" to the necessary functions)

A: Please remove the first end sub in your macro: it makes your macro stop at that moment and the other lines are not even read anymore.

A: For complicated checks, you can use a Boolean to store the True/False value, and check that later.
Dim bContinue AS Boolean
bContinue = False

If Target.Column = 19 And Target.row = 17 Then bContinue = True
If Target.Column = 20 And Target.row = 18 Then bContinue = True

If bContinue = True Then
    'If Trigger1...
End If

However, your current code is simple enough that an OR should work:
If (Target.Column = 19 And Target.row = 17) OR (Target.Column = 20 And Target.row = 18) Then

After that, Row 18, Column 20 of the sheet will be Me.Cells(18, 20).  Similarly, Row 17, Column 19 will be Me.Cells(17, 19)
This allows you to do this:
If Me.Cells(17, 19).Value = "Yes" And Me.Cells(18,20).Value = "Yes" Then
    'Do Something
'' do something
elseif Me.Cells(17, 19).value = "No" and Me.Cells(18,20).value = "yes"
'' do another thing
end if

However, if the only possible values are "Yes" and "No" (i.e. no "Maybe" or blank) then you can combine things into a Switch Statement with a bit of Binary:
Select Case (IIF(Me.Cells(17, 19).Value = "Yes", 1, 0) + IIF(Me.Cells(18, 20).Value = "Yes", 2, 0))
    Case 0: '0b00
        'Both are "No"
    Case 1: '0b01
        '"Yes" and "No"
    Case 2: '0b10
        '"No" and "Yes"
    Case 3: '0b11
        'Both are "Yes"
    Case Else:
        'Something has gone wrong
End Select

(The Worksheet_Change function is attached to the Worksheet, so you can use the special keyword Me to refer to the Worksheet.  If this was code in a Module, then that would not work)

A: A Worksheet Change (Multiple Cells)
Standard Module, e.g. Module1
Option Explicit

Sub TriggerS17T18( _
        ByVal Target As Range)
' Needs the 'ConcatRange' function.
    Const ProcName As String = "TriggerS17T18"
    On Error GoTo ClearError

    Const rgAddress As String = "S17,T18"

    Dim sws As Worksheet: Set sws = Target.Worksheet
    Dim rg As Range: Set rg = sws.Range(rgAddress)
    If Intersect(Target, rg) Is Nothing Then Exit Sub

    Application.ScreenUpdating = False
    ' The following line is crucial if you're going to process the same
    ' worksheet, because it will prevent retriggering the event while it
    ' is still running.
    Application.EnableEvents = False

    Dim cString As String: cString = UCase(ConcatRange(rg))

    ' Possibly Needed References
    ' Create a reference to the workbook.
    'Dim wb As Workbook: Set wb = sws.Parent ' Set wb = Target.Worksheet.Parent
    ' Create a reference to worksheet "Sheet2".
    'Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet2")

    ' When done testing, replace the `MsgBox cString` lines with your code.
    Select Case cString
    Case "YESYES"
        MsgBox cString

    Case "YESNO"
        MsgBox cString

    Case "NOYES"
        MsgBox cString

    Case "NONO"
        MsgBox cString

    Case Else
        MsgBox cString

    End Select

SafeExit:
    If Not Application.EnableEvents Then Application.EnableEvents = True
    If Not Application.ScreenUpdating Then Application.ScreenUpdating = True

    Exit Sub
ClearError:
    Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
              & "    " & "Run-time error '" & Err.Number & "':" & vbLf _
              & "    " & Err.Description
    Resume SafeExit
End Sub

Function ConcatRange( _
    ByVal mrg As Range, _
    Optional ByVal Delimiter As String) _
As String
    Const ProcName As String = "ConcatRange"
    On Error GoTo ClearError

    Dim mCell As Range
    For Each mCell In mrg.Cells
        ConcatRange = ConcatRange & CStr(mCell.Value) & Delimiter
    Next
    ConcatRange = Left(ConcatRange, Len(ConcatRange) - Len(Delimiter))

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
              & "    " & "Run-time error '" & Err.Number & "':" & vbLf _
              & "    " & Err.Description
    Resume ProcExit
End Function

Sheet Module, e.g. Sheet1
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    TriggerS17T18 Target
End Sub


text:
Q: How to discard older build while Fabric distribution? I have a problem with automated build distribution thru Fabric Beta with concurrent uploading.
For example I starting upload of first build and 5 seconds after it I starting upload second one. But because Internet is a magic-unstable-box the second build have uploads before the first build. And it's treated as first build is newer then second. But it's not true.
So I want to discard older (first) build when I uploading newer one.
Or I want some other workaround for my situation.

A: Mike from Fabric here. There is not an automated way within Fabric to stop the upload once it's started. You can manually remove versions via the app's settings page. From the documentation:
To remove, a specific version of your app, head to your app's settings. Select the app whose name you want to change and click on the "Versions" button. After that, select the toggle on any build or version you want to disable. Disabling a version prevents new crash reports from flowing in, hides it from the version filter, and prevents beta testers from installing that version.


text:
Q: How to write a query in SQL server CE to check data before updating? I'm trying to write a query that can compare each row of a DGV with SQL Server CE and if there were any row that its first and third column is equal to one of SQL rows, do nothing and if there were no duplicate value, then add that complete row to the SQL SERVER CE file.
I tried the following code but it throws runtime error:
SqlCeConnection connection2 = new SqlCeConnection();
connection2.ConnectionString = @"DataSource = WO_No.sdf; password= rss900";
SqlCeCommand mycommand = new SqlCeCommand();
mycommand.Connection = connection2;

for (int i = 0; i < DataGridView3.Rows.Count; i++)
{
connection2.Open();
mycommand.CommandText = $"IF EXISTS (SELECT * FROM [MyData] WHERE Wo={DataGridView3.Rows[i].Cells[0].Value} AND Code={DataGridView3.Rows[i].Cells[2].Value}" +
$"BEGIN" +
$"" +
$"END" +
$"ELSE" +
$"BEGIN" +
$"INSERT INTO [MyData] Wo={DataGridView3.Rows[i].Cells[0].Value}, EqN={DataGridView3.Rows[i].Cells[1].Value}, Code={DataGridView3.Rows[i].Cells[2].Value}, Work={DataGridView3.Rows[i].Cells[3].Value}, Cost={DataGridView3.Rows[i].Cells[4].Value}" +
$"END";
mycommand.ExecuteNonQuery();
connection2.Close();
}


text:
Q: Storing user data upon login I'm new to C# and ASP.NET, so please bear with me.
I'm making a site that consumes 2 different Web Services, that will hopefully use the user's individual accounts/api keys for each system. I take this information when the user creates an account on my system. I would like to retrieve this information from the database as soon as the user logs in, and store it in the Session so that I can use it every time my site calls one of the APIs.
I have tried:
public ActionResult Login(LoginModel model, string returnUrl)
{
  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
  {
     SiteEntities SiteDB = new SiteEntities();
     Session["user"] = SiteDB.T_USER.Find(WebSecurity.CurrentUserId);
     return RedirectToLocal(returnUrl);
  }

  // If we got this far, something failed, redisplay form
  //ModelState.AddModelError("", "The user name or password provided is incorrect.");
  ViewBag.WarningMessage = "The user name or password provided is incorrect.";
  return View(model);
}

but, apparently this won't work because WebSecurity.CurrentUserId has not been set yet at this point.
My question is that if I wanted to grab the user's data as early as possible, so that it is available for the user's entire visit, where should I go about retrieving it?

A: I recommend to use the username in finding the details instead of the UserId so your code should look like the following
public ActionResult Login(LoginModel model, string returnUrl)
{
  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
  {
     SiteEntities SiteDB = new SiteEntities();
     // ------- updated the below line to use username -------------------------------
     Session["user"] = SiteDB.T_USER.Find(model.UserName);
     return RedirectToLocal(returnUrl);
  }

  // If we got this far, something failed, redisplay form
  //ModelState.AddModelError("", "The user name or password provided is incorrect.");
  ViewBag.WarningMessage = "The user name or password provided is incorrect.";
  return View(model);
}


text:
Q: Highcharts: zooming doesn't show full visible series When I zoom in on a series in highcharts, I've noticed that the first visible point of the series is where it starts to draw. This means that if the only point in the visible zoomed area is in the middle, then the line for that series only starts to draw in the middle of the window. Is there a way to make Highcharts render the previous value so that it does not "cut off" the previous values of the graph?
Before, zoomed out:

After, zoomed in (problem):

Desired:

I have tried setting cropThreshold and connectNulls (just in case) among other tweaks with no luck. Any suggestions?


text:
Q: Prove that $\sum_{i=2^n+1}^{2^{n+1}} \frac{1}{i} \ge 0.5$ Where $n$ is any positive integer.
I'm honestly completely at a loss at how to prove this.
Tested by brute forcing it up to large numbers, and it keeps increasing, although very slowly.
This is actually part of a bigger problem containing harmonic numbers, but I've solved the rest, so that's why I don't really have much of an idea on how to approach this.
I've tried integrals to find something that would be smaller than the sum, yet clearly bigger than $0.5$, but, again, I can't really prove it.

A: Since $i\leq 2^{n+1}$ it follows that $\frac{1}{i}\geq \frac{1}{2^{n+1}}$. There are $2^n$ terms in the sum, hence
$$ \sum_{i=2^n+1}^{2^{n+1}}\frac{1}{i}\geq \frac{2^n}{2^{n+1}}=\frac{1}{2}$$

A: $$\sum_{i=2^n+1}^{2^{n+1}} \frac1i \geq \sum_{i=2^n+1}^{2^{n+1}} \frac{1}{2^{n+1}} = \frac12.$$


text:
Q: Do I need different certificates for MTLS and Signing data? I'm building an identity service using PKI and MTLS for authentication.
I use AWS ACM PCA for private certificate authority and AWS KMS for key pairs.
I use the private key created by KMS to sign the Certificate Signing Request that's sent to PCA for creating a client certificate.
The client certificate is then bundled together with the CA certificate chain and the private key in PKCS#12 format and returned to the user which is used to authenticate the user.
We also want the user to be able to sign data, e.g. a json string a PDF file e.t.c.
According to KMS documentation they recommend different types of keys for signing and encryption.
So, do I need different certificates for signing data and if so, what's the point of the signing certificate if the data is signed with the private key and the authentication is made with the client certificate?
We want to be able to authenticate the user using one certificate which is not protected by a password and require password for signing, so I guess we need different PKCS#12 stores?


text:
Q: (Python, Kivy) How do I define by button functions properly? I keep getting AttributeError: 'Dice' object has no attribute 'DisplayBox' I am working on a random dice roller project, Im new to python (I started learning it on my own about 2 months ago) and thought that it would be a good beginner project to work on. But I keep having trouble binding my functions to my buttons. I keep getting an AttributeError: 'Dice' object has no attribute 'displaybox'. Which I dont really understand because my Dice class clearly has a displaybox object inside of it. Thanks for any help!
Here is my Python code:
from random import randint

from kivy.app import App

from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.label import Label

class Dice(GridLayout):
    def __init__(self, **kwargs):
        super(Dice, self).__init__(**kwargs)

# Define Buttons and labels
        d4btn = Button(text='D4',
                       bold = True,
                       on_press = self.rolld4)
        d6btn = Button(text='D6',
                       bold = True)
        d8btn = Button(text='D8',
                       bold = True)
        d10btn = Button(text='D10',
                        bold = True)
        d12btn = Button(text='D12',
                        bold = True)
        d20btn = Button(text='D20',
                    bold = True)
        displaybox = (Label(text=('You have not rolled, \n please select a number to roll.')))
        infobox = (Label(text='Random Dice Project \nJoshua \n10/17/2017'))
# Create Buttons and Labels
        self.add_widget(d4btn)
        self.add_widget(d6btn)
        self.add_widget(d8btn)
        self.add_widget(d10btn)
        self.add_widget(d12btn)
        self.add_widget(d20btn)
        self.add_widget(displaybox)
        self.add_widget(infobox)
# Button Behavior
    def rolld4(self, obj):
        self.displaybox.text = print(str(randint(1,4)))

class DiceRollerApp(App):

    def build(self):
        return Dice()

if __name__ == '__main__':
    DiceRollerApp().run()

And here is my Kivy code:
#:kivy 1.10.0

<Dice>:

    cols: 2
    rows: 4

Edit: I got a working version completed. Thanks for your help!

A: My recommendation is to define all your widgets in your kv file, and use ObjectProperty to hook up to your display box. Please refer to the example below for details.
Example
main.py
from random import randint

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty

class Dice(GridLayout):
    displaybox = ObjectProperty(None)

    # Button Behavior
    def rolld4(self):
        self.displaybox.text = str(randint(1, 4))

class DiceRollerApp(App):

    def build(self):
        return Dice()

if __name__ == '__main__':
    DiceRollerApp().run()

diceroller.kv
#:kivy 1.10.0

<MyButton@Button>:
    bold: True

<Dice>:
    displaybox: displaybox
    cols: 2
    rows: 4
    MyButton:
        text: "D4"
        on_press: root.rolld4()
    MyButton:
        text: "D6"
    MyButton:
        text: "D8"
    MyButton:
        text: "D10"
    MyButton:
        text: "D12"
    MyButton:
        text: "D20"
    Label:
        id: displaybox
        text: 'You have not rolled, \nplease select a number to roll.'
    Label:
        id: infobox
        text: 'Random Dice Project \nJoshua \n10/17/2017'

Output

A: in the init() of your dice you need to instanciate the displaybox as an attribute of the dice then you can manipulate it in the button behaviour, so your code is correct just add the self parameter and everything would work fine
here is the code:
-kv:
<Dice>:
   cols: 2
   rows: 4

-py:
from kivy.app import App
from random import randint
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label

class Dice(GridLayout):
   def __init__(self, **kwargs):
      super(Dice, self).__init__(**kwargs)

# Define Buttons and labels
      d4btn = Button(text='D4',
                   bold = True,
                   on_press = self.rolld4)
      d6btn = Button(text='D6',
                   bold = True)
      d8btn = Button(text='D8',
                   bold = True)
      d10btn = Button(text='D10',
                    bold = True)
      d12btn = Button(text='D12',
                    bold = True)
      d20btn = Button(text='D20',
                bold = True)
      #Here you instantiate it ass an attribute of the dice
      self.displaybox = (Label(text=('You have not rolled, \n please select a number to roll.')))
      infobox = (Label(text='Random Dice Project \nJoshua \n10/17/2017'))

# Create Buttons and Labels
      self.add_widget(d4btn)
      self.add_widget(d6btn)
      self.add_widget(d8btn)
      self.add_widget(d10btn)
      self.add_widget(d12btn)
      self.add_widget(d20btn)
      #Then you add it to the layout
      self.add_widget(self.displaybox)
      self.add_widget(infobox)

# Button Behavior
  def rolld4(self, obj):
     self.displaybox.text = str(randint(1,4))
     print(str(randint(1, 4)))

class DiceRollerApp(App):

   def build(self):
      return Dice()

if __name__ == '__main__':
   DiceRollerApp().run()

proof:

I hope I helped !


text:
Q: PHP Singleton Acting Funny I have the following code:
$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "<pre>";
print_r(self::$extensions);

Each getInstance() method looks like this:
public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}

Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:
stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

A: See http://socket7.net/article/php-5-static-and-inheritance.
The problem is there is only one static variable, defined within the scope of the parent class. To create two static variables, the easiest way is to just define $_instance variable and get_instance method in both subclasses.
Another possible workaround is listed in the comments of the above article: "pass an extra class name parameter into the static method calls telling the method which class it should 'act as.'"

A: Since self is resolving to MySQL_Extension, I'm assuming that each class has this method (rather than being defined in Extension_Abstract.  However, where is self::$_instance defined?  My instinct is that it's defined on Extension_Abstract.  Simply re-define it in each class (protected static $_instance = null;).
Also, instead of self, if you're using 5.3+ you should use static since it enables you to inherit and use late-static-binding to determine the class.
If that doesn't help, post more code (the class definitions would help)...

A: Is $_instance in the base class?
If so, then you've got a singleton for the entire hierarchy, not each specific subclass.

A: Try not using self::, but MySQL_Extension:: and Error_Extension:: explicitly.
Also, the abstract parent class Extension_Abstract should not contain the implementation for the getInstance method.

A: late binding issue.
public static function getInstance()
{
    if (static::$_instance == null)
    {
        static::$_instance = new static();
    }

    return static::$_instance;
}


text:
Q: Team Foundation Server 2015 Custom Git Build Activities - Where do I get the required references I am attempting to get our custom activities compiling under TFS2015. The project has two activities, one for TFS source control another for TFSGit.
With the team foundation binaries no longer installed into the GAC and some namespaces changed things are no longer compiling since Visual Studio 2015 RC.
Installing the NuGet package "Microsoft.TeamFoundationServer.Client" results in
Microsoft.TeamFoundation.Build.Activities still missing. I haven't been able to locate the NuGet package for this or a valid reference which works with the NuGet package "Microsoft.TeamFoundationServer.Client".
I have attempted to follow the comments in Where can I find Microsoft.TeamFoundation.Build.Client in Visual Studio 2015?. However I still have this error.
The best answer I have found so far is to create a powershell script like:
https://github.com/ctaggart/SourceLink/blob/master/Tfs/lib/Copy-Libraries.ps1#L8
Yet I am still uncertain as to which files are correct to reference. The versions I get in the example above are lower than those in the NuGet package, which are again different to those on the TFS server.
A classic example of this is that the Lib2GitSharp reference seems to be strongly named by Microsoft. Making the Lib2GitSharp NuGet package incompatible.
So in summary; where is the definitive location for TFS Activity references?

A: You should reference the build activities from the folder in the matching version of VS for the build controller you are targeting.  For VS 2015 it would be this folder by default
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer


text:
Q: android cordova sharedpreference deleting during force close We are facing an issue with android SharedPreferences in our application. Our application is a cordova application. We are storing few data in the SharedPreferences. For example, storing userid, last visited page html contents, few json values.
Following are code samples for managing sharedpreferences (get/set/remove).
//get
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
Object obj = sharedPrefs.getAll().get(key);

//remove
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
if (sharedPrefs.contains(key)) {
    Editor editor = sharedPrefs.edit();
    editor.remove(key);
}

//store
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cordova.getActivity());
Editor editor = sharedPrefs.edit();
editor.putString(key, value);
editor.commit();

The storing retrieving deleting everything working fine. The problem we are facing is, the data is not persisting in a consistent manner.
For example, user opens the app and then he force close the app, again takes the app. All data in the sharedpreference is persists. But when he force close 2nd time and come back to the app once again, then the data from the sharedpreference is deleted. I could not find any log in the logcat also. Any help will be much appreciated.


text:
Q: Makefile g++ compile with -D variable from command line with default value I'm trying to setup a makefile which will take a command line argument and pass it on to the compiler with the -D flag. Also, set a default value for the variable.
e.g.
$: Make program FOO=12

and this will compile with -DFOO=12
Also, if FOO is not given at the command line how can I set a default value?  I am working with c++ so I can do
#ifndef FOO

#define FOO 12

#endif

But I would like a way to have a default value inside the makefile.

A: ifeq ($(FOO),)         # check if FOO is not defined
CFLAGS= -DFOO=999      # if not defined, set a default value
else
CFLAGS= -DFOO=$(FOO)   # or use the value from argument
endif

A: Redefined macro is a warning, so if you aren't care about warnings, just add the default value into the flags, and append the user input one next, it will cover the default value.
If you don't like warnings, use -U argument.
-D FOO=1 -U FOO -D FOO=2


text:
Q: Does web-fonts need to have BOLD / ITALICS files together? In Desktop software (like MS WORD) in order to use BOLD or ITALICS styles for an unicode font, we had to install separate files:
MyFont.ttf
MyFont-Bold.ttf
MyFont-Italics.ttf
.....

But in CSS, we only need to have only .ttf file, and browser can do BOLD/ITALICS itself. So, my question is - how do browsers "create" those styles without providing the files specifically for BOLD and ITALICS? Or what's the difference between Desktop apps and Browsers, with regard to this question? or why ...bold.ttf and ...italics.ttf files existed ever, and not integrated within the main ttf file at all?

A: Browsers have their own faux bold and italics algorithms for simulating bold and italics when a typeface doesn't come with its own bold and italics fonts. And they're not the only applications that come with faux bold and italics — some image editing applications like Photoshop have them too.
The reason typefaces come with their own bold and italics fonts is because the variant glyphs are often unique to each typeface and cannot be accurately simulated by a browser. For example, faux italics algorithms just skews the glyphs in an oblique style rather than actually italicizing them. Even CSS defines both italic and oblique as values of the font-style property for this reason, though in practice almost no typefaces actually provide both variants anyway.
The reason bold and italics variants of a typeface are stored in separate font files is because that's just how the file formats were designed in the beginning. TrueType does provide a .ttc file format, which stands for TrueType Collection, that combines multiple fonts into a single file. But since the @font-face rule was designed for use with one font at a time, .ttc files can't be used with it.


text:
Q: PGP not decrypting when using gpg4win I have set up the GPGTools on OS X 10.11 and they work perfectly fine in Apple Mail, as I have verified by testing with two of my email addresses. Even in Outlook 2016 with the gpg4win plugin on my Windows 10 machine the emails are decrypted automatically and signatures are verified correctly.
It doesn't work the other way round though: Emails encrypted in Outlook 2016 using the gpg4win plugin do NOT get decrypted (automatically) at the receiving email address. Not in Outlook, and not in Apple mail either. Instead, I'm shown the encrypted message between the PGP message lines.
BTW: After creating the key pair with the GPGTools in OS X, I exported the two pairs for my two email addresses and imported them in Kleopatra (gpg4win) on my Windows 10 machine.
Can anybody, please, tell me what's going wrong? Why is decryption working correctly when emails are sent from Apple Mail (GPGTools, OS X), but not when sent from Outlook 2016 (gpg4win, Windows 10)? Any help is appreciated!

A: From my experience gpg4win's Outlook integration is not very realiable.
To have a check if the key material on Windows is correct, you might try to install gpg4o. It also includes a decent keymanagement. Unfortunately it is not freeware, but it's trial mode should be sufficient to test the keys.


text:
Q: Hive table replace timestamp column NULL value with Custom default I understand how to keep default value as current timestamp, But I have requirement to replace NULL value in timestamp column with custom date/timestamp.

A: There is coalesce function that you can use, e.g.,
select coalesce(column_name, cast("2020-07-28 12:34:56" as timestamp))


text:
Q: Type an object with optional keys, but non-null value for keys that exist I'm on TypeScript 3.2.2 with strict: true.
I've been unable to type a plain object that has a set of dynamically defined keys, but all those keys have a guaranteed non-null value type.
[TypeScript playground example]
// Will assume any property access has type T
interface Object<T> {
    [key: string]: T;
}

// Will assume Object.values() could be undefined
interface Object<T> {
    [key: string]: T | undefined;
}

// Doesn't compile
interface Object<T> {
    [key: string]?: T;
}

A: As mentioned in the comments, TypeScript doesn't do a great job of distinguishing missing properties from undefined properties.  That's at least somewhat reasonable, since when you read a missing property from an object in JavaScript you will get undefined (and not an error).  And before the --strictNullChecks compiler option was introduced in TypeScript 2.0, TypeScript did a very bad job of distinguishing missing/undefined properties from present/defined properties.  This was mostly addressed by --strictNullChecks but a few issues linger.
One of the places that this issue still shows up is in types with index signatures.  Index signatures are just considered to be present.  There is no way to say some keys are present and some keys are absent with an index signature.  The optional index signature syntax you want is not part of the language. With --strictNullChecks turned on, the signature {[k: string]: SomeType} is saying that every single string-key property exists and is of type SomeType, but this is not actually enforced when you assign objects to it.  The only truly type safe way to use index signatures is to add | undefined to the value type, like {[k: string]: SomeType | undefined}, but this ends up becoming very annoying to use in many circumstances, leading to people overusing non-null assertions, which  doesn't help anyone.  So it is the way it is.

UPDATE for TS4.1
TS4.1 will introduce a --noUncheckedIndexedAccess compiler option, also known as "pedantic index signatures" which behaves mostly like | undefined has been added to the index signature.  This is still annoying to use in the way mentioned above, especially for string index signatures (arrays are less bad since you can make a for..of loop that doesn't worry about undefined), so the rest of this answer mostly stands.

Right now your options are, as I see them:

*

*use an index signature without | undefined and deal with the fact that the compiler thinks all properties are present when some are not (do checks that the compiler doesn't think are necessary, like if (unknownKey in foo) {... foo[unknownKey] ...})

*use an index signature with | undefined (or use --noUncheckedIndexedAccess in TS4.1+) and deal with the fact that the compiler keeps warning you that a value might not be defined when you know it is (do extra checks you don't need, like const prop = foo[knownKey]; if (typeof prop !== 'undefined') { ... prop ... }; or non-null assertions like const prop = foo[knownKey]!)

*don't use an index signature.  You might be able to get away with using a mapped type where the set of keys is some union of literals that you don't know when you're defining your types but you will know when you are using it.  That is, use the predefined Record<K, T> type:
  type Record<K extends keyof any, T> = {[P in K]: T};

But that gets more complicated when trying to manipulate, so I'm not going to dive too deeply in here.
Not sure what else to say.  It's a language limitation that persists because the alternatives seem to be more annoying.  If you have a compelling use case you might be able to comment on some of the linked GitHub issues or open a new one, but I don't expect much will change here.
Oh well, hope that's of some help.  Good luck!

A: You can use the unknown type:
interface Object {
    [key: string]: unknown;
}

From the TypeScript docs:

[...] unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.


text:
Q: Copiar valor de um input com document.execCommand('copy') usando toLowerCase()? Preciso copiar o valor de um input para a área de transferência, até o momento fiz desta forma:
$("#valor").select();

try {
    document.execCommand('copy');
}
catch (e) {}

Porém, gostaria de que este valor copiado fosse todo em letras minúsculas, ou seja, aplicando um .toLowerCase(), porém não estou conseguindo e tentei pesquisar mas não obtive resultados... Alguém saberia me instruir de como fazer?

A: Após algumas pesquisas cheguei no Clipboard API, API projetada para substituir o acesso à área de transferência usando document.execCommand(), que foi deprecado.
Neste caso é possível copiar para a área de transferência o próprio texto de um elemento ou de uma variável.
A solução foi:
var valor = $("#valor").val().toLowerCase();

navigator.clipboard.writeText(nrRegistro).then(function() {
    console.log("success");
}, function(err) {
    console.log("error");
});

Deixo de referência para caso alguém tenha os mesmos problemas https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API


text:
Q: Query on multiple values in Firebase, similar to IN() SQL functionality I have an array that looks like this:
validZipCodes = [
  "84606",
  "84605",
  "84601"
]

I'm querying some data like this:
var Jobs = firebase.child('Jobs');

I tried this:
var Jobs = firebase.child('Jobs').orderByChild('ZipCode').equalTo($scope.validZipCodes);

But it returned an error that it was an invalid data-type, is there anyway to say something like:
var Jobs = firebase.child('Jobs').orderByChild('ZipCode').inArray($scope.validZipCodes);

Or something like that.
Note that this is an array comparison & not querying text in an object.

A: Here is how I eventually did it:
With the foreach command you can easily manipulate data and then push it into an array to re-create a collection of data however you need it.
$scope.validZipCodes = [];
$scope.validContractorJobs = [];

var Jobs = firebase.child('Jobs');

contractorJobs.on('value', function(snap) {
            snap.forEach(function(job) {
                angular.forEach($scope.validZipCodes, function(value, key) {
                    if(job.val().ZipCode == value) {
                        $scope.validContractorJobs.push(job.val());
                    }
                });
            });
        });

A: The Firebase .equalTo() documentation states that the value argument should be one of the following types: String, Number, Null, or Boolean.

*

*You are getting an invalid data-type error because you are not passing one of these types.

*There is no method like .inArray() (i.e. querying for equalTo multiple values).
You can review all of the Firebase Query Methods in the Query documentation, which also  suggests:

Read our documentation on ordering and querying data for more information and examples.


text:
Q: How can I smooth noisy time series data to explore possible relationships First CV post but prior S.O. user. Thanks for your patience as 'stats' is not my natural habitat.
I have data in the following form, in which I am trying to see if there is a relationship.

*

*Daily log returns for a series of companies.

*Daily data that may influence the performance of those companies on a lagged basis (for example, independent observer data on how many people enter a set of stores on a given day).

I expect that there is lot of noise in the data, such that the independent observer data on store visits on T-1 will not influence the returns on T, but that aggregated independent data from T-1 to T-30 might, for example, influence the returns from T to T+15.
I'm looking for feedback on how to aggregate these data in a meaningful way to see if there's a relationship, either in return space, or in volatility space. I could certainly draw arbitrary lines (like looking at mean or median visitors for a month and considering monthly returns), but that throws away a lot of data and doesn't seem "right". My intuition is also that I don't have enough data to consider any sort of high-dimensional regression or other analysis that incorporates, for example, 15 lagged observations.
So, what is a reasonable way to aggregate my noisy time series data? Or am I thinking about this wrong?


text:
Q: Haskell IO error handling during IO operation In the System.Directory library, getPermissions function could return IO errors.
The documentation says it could fail with isPermissionError or isDoesNotExistError.
How do I handle IO errors during calling getPermissions?
Attempt:
input <- try (do
        permissions <- getPermissions filepath
        print permissions)
case input of
        Left e  -> print "a"
        Right e -> print "b"

Error:
No instance for (Exception e0) arising from a use of 'try'
The type variable 'e0' is ambiguous
Note: there are several potential instances:
  instance Exception NestedAtomically
    -- Defined in 'Control.Exception.Base'
  instance Exception NoMethodError
    -- Defined in 'Control.Exception.Base'
  instance Exception NonTermination
    -- Defined in 'Control.Exception.Base'
  ...plus 7 others
In a stmt of a 'do' block:
  input <- try
             (do { permissions <- getPermissions filepath;
                   print permissions })
In the expression:
  do { input <- try
                  (do { permissions <- getPermissions filepath;
                        print permissions });
       case input of {
         Left e -> print "a"
         Right e -> print "b" } }
In an equation for 'checkwritefilepermissions':
    checkwritefilepermissions filepath
      = do { input <- try
                        (do { permissions <- getPermissions filepath;
                              print permissions });
             case input of {
               Left e -> print "a"
               Right e -> print "b" } }

A: The error message says it was impossible to figure out the type of exception (that is, the instance of Exception) you want to catch. One possible solution is providing a type annotation which specifies it, as in:
case (input :: Either IOError String) of
    Left e -> print "a"
    Right r -> print "b"

Alternatively, if you use isDoesNotExistError and friends in System.IO.Error to distinguish the error cases  the exception type will be inferred as IOError without requiring extra annotations.
A relevant discussion of basic exception catching practices can be found in the Control.Exception documentation.

A: There is an easy fix (not a best fix) to this problem, replace
Left e

by
Left (e :: SomeException)

By the way, your code could be simplified like this
input <- try $ getPermissions filepath
case input of
    Left (e :: SomeException) -> print "a"
    Right e -> print "b"

And you really should improve those names in your code.


text:
Q: post a  to sharepoint page I am doing following in one of my webpart .ascx file.
<FORM action="https://illustration.sagicorlifeusa.com/fse5/main/FormPost.aspx" id="frmLogin" method="post" target=blank>

    <%= CompleteRequest %>
<input type="submit" name="__exclude__Submit" value="Run Sagicor Life Illustration Software Online" />

Notice the method="post"; However, looks like when I add this web-part, The hosting page already has a <FORM/> . How can I do the above POST?

A: posting to a new window from inside an ASPX web form (which SharePoint is) is tricky, because the framework wraps everything in a <form> it keeps track of.  If you are required to post to the target page (i.e. get isn't good enough), you might have to:

*

*create a separate .aspx page entirely to produce the form

*open that form from within your Web Part with a JS call to window.open or an <a href="..." target="blank"

*auto-post that form, with JavaScript, as soon as it loads.

(I have no firsthand experience with sharepoint; take this answer with a grain of salt.)


text:
Q: How to turn off animation in three.js While testing code in three.js, animation is not needed.  I can see the first rendered frame.  This would use less power, and stop the fan on the laptop from kicking in as the graphics card heats up.
The examples in three.js have the following structure:
function init() {
  animate()
}

function animate() {
    requestAnimationFrame( animate );
    render();
    targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
}

function render() {
    group.rotation.y += ( targetRotation - group.rotation.y ) * 0.05;
    renderer.render( scene, camera );
}

I do not see how to turn off the repeated calls to animate.
Is there any easy way to turn off animation?

A: You do not have to have an animation loop in three.js -- say, if you have a static scene. Just call
renderer.render( scene, camera );

You will need to re-render whenever the camera moves or when loaders finish loading models or loading textures.
If you are using OrbitControls with a static scene, you can instantiate OrbitControls like so:
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render ); // use if there is no animation loop

where render() calls renderer.render( scene, camera ).
If you are loading models or textures, the three.js loaders have a callback function you can specify. For example,
var loader = new THREE.TextureLoader();
var texture = loader.load( 'myTexture.jpg', render );

Also
var manager = new THREE.LoadingManager();
var loader = new THREE.OBJLoader( manager );

loader.load( 'myModel.obj', function( object ) {
    // your code...
    render();
}

three.js r.75


text:
Q: pointer to functions? say I have
class B{   //base class

}

class A : public B{ //derived class
}

I also have a function that returns a pointer to class B
B* returnB(){
    B * object = new A; //pointer of base class allocate object of derived class
    return object;
}

now when i try to make a pointer to function B*, I get an error
B* (*randomFunction)();
randomFunction = returnB;

Visual Studios wont compile.
1   IntelliSense: a value of type "B*(MediaFactory::*)()" cannot be assigned to an entity of type "B*(*)()" c:\Users\...\mediafactory.cpp   35

A: You seem to be trying to assign a pointer to a member function of class MediaFactory into a variable that can hold a non-member function. These entities aren't compatible. Either use boost bind or change your function pointer variable to be of B* (MediaFactory::*)() type.

A: You are assigning a pointer-to-member function to a function pointer.
A method of your class, unless static, has a different signature and approach to calling. The simple function declaration does not account for class representations (e.g. implicit this).
See here: http://www.parashift.com/c++-faq/fnptr-vs-memfnptr-types.html


text:
Q: Orfeo toolbox and MacOs, installation fails I am trying to install orfeo toolbox in my MacAir with Maverics. I am using homebrew but the installation fails with the following error log:
==> Downloading //downloads.sourceforge.net/project/orfeo-toolbox/OTB/OTB-3.20/OTB-3.20
Already downloaded: /Library/Caches/Homebrew/orfeo-3.20.0.tgz
==> cmake .. -DCMAKE_C_FLAGS_RELEASE= -DCMAKE_CXX_FLAGS_RELEASE= -DCMAKE_INSTALL_PREFIX=/usr/
-- Configuring incomplete, errors occurred!
See also "/tmp/orfeo20150720-4244-1cjwrtd/OTB-3.20.0/build/CMakeFiles/CMakeOutput.log".
See also "/tmp/orfeo20150720-4244-1cjwrtd/OTB-3.20.0/build/CMakeFiles/CMakeError.log".
READ THIS: //git.io/brew-troubleshooting
These open issues may also help:
orfeo 5.0.0 (https://github.com/Homebrew/homebrew/pull/41363)
orfeo fails to build on 10.10.3 (https://github.com/Homebrew/homebrew/issues/41275)
I went to the github forum and the issue has been opened, but it was not 100%clear which is the solution

A: I've commented on the issue tracker on github. I don't get why the formula is trying to install version 3.20 which is pretty old. I was thinking that there is formula for OTB 4.X


text:
Q: Zend 2.0 query route Hello I am using ZendFramework 2.0 and I would like to set routing with query params. For example I would like something like that to get working.

I want route that will match .../foo?my_param=number but will not
  match .../foo or .../foo?not_allowed_param=value

'type' => 'Literal',
'options' => array(
    'route' => 'foo',
    'defaults' => ...// Route to some error handler
    'may_terminate' => true,
    'child_routes' => array(
        'query' => array(
             // there is some query so route to my action
            'type' => 'Query',
            'options' => array(
                'defaults' => array(
                    'controller' => 'index',
                    'action' => 'fooAction',
                ),
            ),
        ),
    ),
),

On the other side I want be able to use $this->url('.../foo', array('my_param' => 3))
Ofc that this does not work. I hope you get the idea what behaviour I expect.
Thanks for any help!

A: Your answer suggests use of GET parameters.  You could check in the controller if the variables have been passed.
If you want to do it through the router (as Sam notes) you can set up a segment style router.  This is explained at this link:
http://framework.zend.com/manual/2.0/en/modules/zend.mvc.routing.html
An example of how this could look is included below:
'YourName' => array(
            'type' => 'segment',
            'options' => array(
                'route' => '/property/search[/:action]',
                'constraints' => array(
                    'controller'=>'[a-zA-Z][a-zA-Z0-9_-]*',
                    'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                ),
                'defaults' => array(
                    'controller' => 'Module\Controller\Controller',
                    'action' => 'index',
                ),
            ),
        ),

Segments in square brackets are considered optional.


text:
Q: Is there a way to remotely shut down a Windows machine on my home network that doesn't support RDP? I have an older Dell Dimension desktop, originally running Windows XP, that I had recently upgraded to Windows 8.1. I plan on using it as a media server running Plex, and I can easily move files on to it over my home network and update the library through the Plex web admin. I would also like to be able to shut down the machine when I'm not using it.
I don't want to plug a monitor and a keyboard into it, so I'm not sure how I can do this, since remote desktop is apparently only available in Windows 8.1 Pro for some reason. The only thing I can think of is to set up a web server that runs some highly-trusted code that can invoke the shutdown command on the host, but I imagine there is a simpler way.

A: Find an old computer with a CD-ROM drive. Install linux. Name it HOMECOMPUTERSHUTDOWNROBOT. Find a plastic stick, about 2 inches long. Superglue it to the CD-ROM door so that it sticks straight out from the computer. Position the old computer so that the stick points at the power button for the computer you want to shut down. Use old books as necessary to prop the computer up to the needed height to do so.
When you want to turn off the computer, SSH into HOMECOMPUTERSHUTDOWNROBOT. In the terminal, use the eject command to eject the CD drive. The plastic stick will push the power button of the computer not supporting RDP and turn it off.

A: Such "highly trusted" code already exists.

*

*The shutdown tool can do remote shutdowns over RPC, as long as File Sharing is enabled:
shutdown -m \\plexbox -s -t 0 -f

Its Linux Samba equivalent:
net rpc -S plexbox -f -t 0

(Note that this needs SeRemoteShutdownPrivilege separate from the regular "local shutdown" privilege – even if you use it locally. This can be granted to non-admins via secpol.msc.)

*PowerShell Remoting can be used to run PowerShell commands.

*You can install a SSH server, such as Bitvise WinSSHd.

*psexec was the usual pre-Remoting tool for running programs remotely. (Although I can't get it working with Active Directory anymore...)

*Finally, as GeraldB also wrote, there are other graphical remote control tools besides RDP – such as VNC, TeamViewer, radmin, etc.

A: Another option for remote control, in addition to RDP and VNC, is services like LogMeIn, Team Viewer, WebEx or other similar alternatives to screensharing.
These options, like VNC, generally involve installing a client. You can then use their service to log into a computer remotely.

A: Start menu, control panel, and or remove software / windows components. Click add / remove windows components.
Find "telnet server" in the tree, and enable it. For now, you can get a remote command line with any telnet client (I would suggest either the telnet client in windows, can be enabled there, too), or putty (can work as a telnet client as well).
Logging there remotely you can halt / restart your machine with the common shutdown ... commands.
But beware: telnet is among the most cracked protocols of the internet, because it send everything (incl. passowords) unencrypted. Thus I highly suggest to combine this solution with an encrypting VPN.

A: VNC (TightVNC or many other flavors) is a freeware graphical remote control solution like Remote Desktop you wanted to use. It supports Windows 8.x.  VNC though a SSH tunnel is recommended for usage across the Internet.
Alternatively if you enjoy the command line, try running an SSH server on your media server. You can then run an ssh client (like PuTTY) which would allow the automation of file transfers and access to the command line with high security.  Inside of an ssh session or even directly from another Windows machine, you can use the shutdown command-line.  This allows you to shut down or restart a local or remote computer.
For a low-tech solution, try holding the power button down quickly for a second or less (not the 5 seconds for a hard power off). Windows should shutdown gracefully or go into standby, depending on configuration.
As Peterh mentioned, you can also use telnet a command-line interface built-in to windows.  See control panel, add-remove programs.  While telnet is insecure for a home network it is a possibility.  SSH is the recommended secure encrypted alternative that only takes a little longer to setup.

A: Alternatively you can write a Python script that listens on a port via sockets (must port forward if you'd like to access from anywhere) and you can issue it commands via a Python socket client or through a PHP socket_write() to execute an appropriate task aka shutdown

A: Native windows solution (even works on ɴᴛ4). Very Simple. No need to install anything.

*

*If the machines aren't member of the same active directory domain you'll need to run this command the first time as an administrator on the host machine (it will be added permanently) : cmdkey /add:Netbios name or ip target address /user:a local administrator account name existing on the target machine /pass:password of the account
ꭥ
 2. Then and for all the time you will need it, simply runshutdown /i. (Sorry but I can't change the language)

A: You can use this tool (an early version, but fully functional):
https://github.com/r4zv4n/PlexShutDown
It will allow you to remotely shutdown the PlexMediaServer computer, by playing a a custom title from your library.


text:
Q: Display workflows in LOB application I am working on a WPF LOB application. Basically users have to drive an entity(lets call it order) throuout the workflow. For example: The first one creates the order and it notifies his boss, then his supervisor confirms it,...
I would like to know if anyone knows any appropriate wpf user control for this kind of job. Most of the solutions on the internet are rehosting the WF designer. Unfortunately I do not have the time and resources to learn WF. I would prefer, to keep whole thing simple.


text:
Q: nodemailer - not sending email I am setting up firebase function to send emails.
I am using nodemailer for sending emails; referring docs here.

*

*function deployed without error.

*functions log shows status ok. No error logged.

*CC to sender email works fine.

*the recipient is not receiving any email. Tried many recipient email combinations.

My code index.js as below.
const functions = require("firebase-functions");
const nodemailer = require("nodemailer");
const fromEmail = "###"; // masked while sharing here
const pwd = "****"; // // masked while sharing here

const transporter = nodemailer.createTransport({
  host: "mail.my-domain.com",
  port: 465,
  secure: true,
  auth: {
    user: fromEmail,
    pass: pwd,
  },
});

exports.sendVerifyEmail = functions.firestore.document("profiles/{uid}")
    .onCreate((snap, context) => {
      const emailVerified = snap.data().emailVerified;
      const email = snap.data().userId;

      const mailOptions = {
        from: fromEmail,
        to: email,
        cc: fromEmail,
        subject: "Email Verification",
        html: `
Welcome to Connecting Dots...

Please verify your email using below code.

                    Your one time verification code is
                    ${emailVerified}

`,
      };

      return transporter.sendMail(mailOptions, (error, data) => {
        if (error) {
          functions.logger.log("error", error + "", fromEmail, pwd);
          return;
        }
        const messageId = data.messageId;
        const res = data.response;
        console.log(email + " : " + emailVerified);
        console.log(messageId);
        console.log(res);
        functions.logger.log("Email sent ->", mailOptions.html);
      });
    });


text:
Q: Transition with keepScrollPosition and navigateBack We are using Durandal for our SPA application and came to a, in my opinion, common use case. We have two pages: one page is a list of entities (with filters, sorting, virtual scroll) and another is detail preview of an entity. So, user is on list page and set a filter and a list of results comes out. After scrolling a little bit down user notice an entity which he/she would like to see details for. So clicking on a proper link user is navigated to details preview page.
After "work finished" on preview page user click back button (in app itself or browser) and he/she is back on the list page. However, default 'entrance' transition scroll the page to the top and not to the position on list where user pressed preview. So in order to 'read' list further user have to scroll down where he/she was before pressing preview.
So I started to create new transition which will for certain pages (like list-search pages) keep the scroll position and for other pages (like preview or edit pages) scroll to top on transition complete. And this was easy to do however, I was surprised when I noticed that there are strange behavior on preview pages when I hit navigateBack 'button'. My already long story short, after investigation I found out that windows.history.back is completing earlier then the transition is made and this cause that preview pages are scrolled automatically down to position of previous (list) page when back button is hit. This scrolling have a very unpleasant effect on UI not mentioning that it is 'total catastrophe' for my transition.
Any idea or suggestion what could I do in this case?
Here is the code of transition. It is just a working copy not finished yet as far as I have this problem.
define(['../system'], function (system) {
var fadeOutDuration = 100;

var scrollPositions = new Array();

var getScrollObjectFor = function (node) {
    var elemObjs = scrollPositions.filter(function (ele) {
        return ele.element === node;
    });
    if (elemObjs.length > 0)
        return elemObjs[0];
    else
        return null;
};

var addScrollPositionFor = function (node) {
    var elemObj = getScrollObjectFor(node);
    if (elemObj) {
        elemObj.scrollPosition = $(document).scrollTop();
    }
    else {
        scrollPositions.push({element: node, scrollPosition: $(document).scrollTop()});
    }
};

var scrollTransition = function (parent, newChild, settings) {
    return system.defer(function (dfd) {
        function endTransition() {
            dfd.resolve();
        }

        function scrollIfNeeded() {
            var elemObj = getScrollObjectFor(newChild);
            if (elemObj)
            {
                $(document).scrollTop(elemObj.scrollPosition);
            }
            else {
                $(document).scrollTop(0);
            }
        }

        if (!newChild) {

            if (settings.activeView) {
                addScrollPositionFor(settings.activeView);
                $(settings.activeView).fadeOut(fadeOutDuration, function () {
                    if (!settings.cacheViews) {
                        ko.virtualElements.emptyNode(parent);
                    }
                    endTransition();
                });
            } else {
                if (!settings.cacheViews) {
                    ko.virtualElements.emptyNode(parent);
                }
                endTransition();
            }
        } else {
            var $previousView = $(settings.activeView);
            var duration = settings.duration || 500;
            var fadeOnly = !!settings.fadeOnly;

            function startTransition() {

                if (settings.cacheViews) {
                    if (settings.composingNewView) {
                        ko.virtualElements.prepend(parent, newChild);
                    }
                } else {
                    ko.virtualElements.emptyNode(parent);
                    ko.virtualElements.prepend(parent, newChild);
                }

                var startValues = {
                    marginLeft: fadeOnly ? '0' : '20px',
                    marginRight: fadeOnly ? '0' : '-20px',
                    opacity: 0,
                    display: 'block'
                };

                var endValues = {
                    marginRight: 0,
                    marginLeft: 0,
                    opacity: 1
                };

                $(newChild).css(startValues);
                var animateOptions = {
                    duration: duration,
                    easing : 'swing',
                    complete: endTransition,
                    done: scrollIfNeeded
                };

                $(newChild).animate(endValues, animateOptions);
            }

            if ($previousView.length) {
                addScrollPositionFor(settings.activeView);
                $previousView.fadeOut(fadeOutDuration, startTransition);
            } else {
                startTransition();
            }
        }
    }).promise();
};

return scrollTransition;

});

A: A simpler approach could be to store the scroll position when the module deactivates and restore the scroll on viewAttached.
You could store the positions in some global app variable:
app.scrollPositions = app.scrollPositions || {};
 app.scrollPositions[system.getModuleId(this)] = theCurrentScrollPosition;