text:
Q: How to calculate the area of a geospatial ZIP code polygon extracted from the US Census using tidycensus I would like to calculate the population density for ZIP codes in my state (North Carolina). I am able to extract the ZIP code populations and polygons from the US Census and plot the map of North Carolina using the following code:
library(tidycensus)
geo <- get_acs(geography = 'zcta',        # Get zip code-level data
               state = 'NC',              # for NC
               year = 2019,               # for 2019
               table = 'B01003',          # from this US Census table
               geometry = TRUE) %>%       # and return the geospatial polygons for mapping
       dplyr::rename('population' = estimate, 'zipcode' = NAME) %>%
       select(-moe) %>%
       arrange(zipcode)

p <- tm_shape(geo) +
  tm_polygons('population')
p

This maps population by ZIP code. In order to calculate and map the population density by ZIP code, I need the area (in miles or kilometers squared) of each ZIP code polygon. I am struggling to find a way of (a) getting this data from the US Census site, (b) finding it elsewhere, or (c) using the polygon geometry to calculate it.
Any suggestions will be appreciated.

A: Another approach is to set keep_geo_vars = TRUE in get_acs(). This will return the area (in square meters) of the land and water areas in each ZCTA polygon. For calculating population density, you may prefer to use just the land area rather than the total area of each ZCTA polygon.
The land area variables is ALAND10 and the water area is AWATER10
library(tidycensus)
get_acs(geography = 'zcta',
        state = 'NC',
        year = 2019,
        table = 'B01003',
        geometry = TRUE,
        keep_geo_vars = TRUE)

#> Getting data from the 2015-2019 5-year ACS
#> Simple feature collection with 808 features and 9 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32187 ymin: 33.84232 xmax: -75.46062 ymax: 36.58812
#> geographic CRS: NAD83
#> First 10 features:
#>    ZCTA5CE10     AFFGEOID10 GEOID   ALAND10 AWATER10        NAME   variable
#> 1      28906 8600000US28906 28906 864608629 28813485 ZCTA5 28906 B01003_001
#> 2      28721 8600000US28721 28721 285413675    41953 ZCTA5 28721 B01003_001
#> 3      28365 8600000US28365 28365 498948199  2852124 ZCTA5 28365 B01003_001
#> 4      27317 8600000US27317 27317 139042432  9345547 ZCTA5 27317 B01003_001
#> 5      27562 8600000US27562 27562 139182043 11466187 ZCTA5 27562 B01003_001
#> 6      28748 8600000US28748 28748 218992045        0 ZCTA5 28748 B01003_001
#> 7      28025 8600000US28025 28025 282005597   384667 ZCTA5 28025 B01003_001
#> 8      28441 8600000US28441 28441 331231481   282711 ZCTA5 28441 B01003_001
#> 9      27893 8600000US27893 27893 285314738  3173744 ZCTA5 27893 B01003_001
#> 10     28101 8600000US28101 28101   2319755   131290 ZCTA5 28101 B01003_001
#>    estimate  moe                       geometry
#> 1     19701  736 MULTIPOLYGON (((-84.31137 3...
#> 2     10401  668 MULTIPOLYGON (((-82.93706 3...
#> 3     15533 1054 MULTIPOLYGON (((-78.29569 3...
#> 4     16169  875 MULTIPOLYGON (((-79.87638 3...
#> 5      2149  431 MULTIPOLYGON (((-78.99166 3...
#> 6     12606 1020 MULTIPOLYGON (((-82.88801 3...
#> 7     54425 1778 MULTIPOLYGON (((-80.62793 3...
#> 8      3396  588 MULTIPOLYGON (((-78.6127 34...
#> 9     39531 1258 MULTIPOLYGON (((-78.06593 3...
#> 10      970  245 MULTIPOLYGON (((-81.09122 3...

A: I was able to find an answer to my question that is very simple. Note that the polygons describing each ZIP code are found in the variable geometry in the geo data frame.
First, we calculate the area, which by default is returned in m^2 units.
library(sf)
geo$area.m2 <- st_area(geo$geometry)

Second, we convert to miles^2 units.
library(units)
geo$area.miles2 <- set_units(geo$area.m2, miles^2)


text:
Q: Inner message in SQL Server TRY/CATCH I want handle error in my procedure when running
BACKUP DATABASE [MyDb] TO DISK = 'c:\Test.bak' WITH COMPRESSION;

command.
If I run this command without TRY/CATCH, I get two errors :

Msg 3201, Level 16, State 1, Line 24
Cannot open backup device 'c:\Test.bak'. Operating system error 5 (Access is denied.).
Msg 3013, Level 16, State 1, Line 24
BACKUP DATABASE is terminating abnormally.

but when I use TRY/CATCH in the statement shown here, I get only part two of this error:
BEGIN CATCH
        select ERROR_MESSAGE()
END CATCH

returned error is only :

BACKUP DATABASE is terminating abnormally.

How to I can get two part of errors?

A: Clearly I misunderstood the question so  scratch this.
SELECT
     ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_STATE() AS ErrorState
    ,ERROR_LINE () AS ErrorLine
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_MESSAGE() AS ErrorMessage;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove by definition $\epsilon-\delta$ the limit $\lim_{(x,y)\rightarrow(0,0)}\frac{1-\cos(xy)}{(xy)^2}=\frac{1}{2}$
Prove by definition $\epsilon-\delta$
  $$\lim_{(x,y)\rightarrow(0,0)}\frac{1-\cos(xy)}{(xy)^2}=\frac{1}{2}$$

My work:
Let $\epsilon >0$, and $\delta =...$
 If $\sqrt{x^2+y^2}<\delta$ then $|\frac{1-cos(xy)}{(xy)^2}-\frac{1}{2}|=|\frac{2-2cos(xy)-(xy)^2}{2(xy)^2}|=\frac{|2-2cos(xy)-(xy)^2|}{2(xy)^2}\leq\frac{|2-2-(xy)^2|}{2(xy)^2}=\frac{|-(xy)^2|}{2(xy)^2}=\frac{(xy)^2}{2(xy)^2}=\frac{1}{2}$
In this step i'm stuck. Can someone help me?

A: With $|\sin t|\leq|t|$ or $-t^2\leq-\sin^2t$ we write
$$2-2\cos t-t^2\leq2-2\cos t-\sin^2t=4\sin^2\dfrac12t-4\sin^2\dfrac12t\cos^2\dfrac12t=4\sin^4\dfrac12t$$
then
$$\Big|\dfrac{1-\cos t}{t^2}-\dfrac12\Big|=\Big|\dfrac{2-2\cos t-t^2}{2t^2}\Big|\leq\Big|\dfrac{4\sin^4\dfrac12t}{2t^2}\Big|\leq\Big|\dfrac{\dfrac14t^4}{2t^2}\Big|=\dfrac18t^2$$
also $|xy|\leq\dfrac12(x^2+y^2)$.


text:
Q: PowerShell.exe -ExecutionPolicy Bypass - Header in Script I am attempting to easily ByPass PowerShells ExecutionPolicy. I realize one easy fix was to create runme.ps1 and script.ps1 and in runme.ps1 I can Bypass the ExecutionPolicy and call script.ps1. Is there some way to put this in a "header" of a script and have it call itself while Bypassing the ExecutionPolicy?
runme.ps1:
PowerShell.exe -ExecutionPolicy Bypass -File "C:\tmp\script.ps1"

script.ps1:
Write-Host "Hello World"
PAUSE

I'm currently working on some sort if "flag" or "tmpfile" logic and having the script call itself, but I wondered if there was a known/better way or even a possible way to have this be a header in all my scripts so end users can just "run w/ powershell" without prompts.
Addendum's to answer's with elaborations on ExecutionPolicy are welcome, but let's focus on the question.
Discussions on ExecutionPolicy should be focused on the "Security Stack Exchange" and the relevant post is linked here:
https://security.stackexchange.com/questions/118553/whats-the-purpose-of-executionpolicy-settings-in-powershell-if-the-bypass
https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/:

However, it's important to understand that the setting was never meant
to be a security control. Instead, it was intended to prevent
administrators from shooting themselves in the foot.

A: You can create a some kind of trusted launcher (cmd file, or exe file), that will run powershell with --ExecutionPolicy ByPass flag. Or Even you can change behaviour of double-click action to run PowerShell with ByPass policy flag always.
However, settings on computer can be hardened by system administrator in MachinePolicy\ExecutionPolicy or UserPolicy\ExecutionPolicy and you will not be able to override it in normal way.
ExecutionPloicy is configured at 4+1 levels, with priority from High to Low:
> Get-ExecutionPolicy -List

MachinePolicy (Group Policy)
   UserPolicy (Group Policy)
      Process (Configured using powershell -ExecutionPolicy flag for new process only)
  CurrentUser (User settings)
 LocalMachine (Computer settings)

When you run PowerShell with ByPass flag, you actually set Process-level ExecutionPolicy that overrides CurrentUser and LocalMachine setings, but can be hardened at UserPolicy or MachinePolicy level managed by local or domain Group Policies.

Better way is to comfigure user policies using group policy to allow run only AllSigned or RemoteSigned scripts, generate a certificate New-SelfSignedCertificate -Type CodeSigning for 100 years, deploy it using GPO as Trusted Publisher per computer and sign using Set-AuthenticodeSignature every script you deploy to users.

A: TLDR;
PowerShell.exe -ExecutionPolicy Bypass -File "C:\circumvent\industry\standard.ps1" 2>&1>$null

I wanted to share scripts and be able to say "right click and run w/ powershell" which is already worse then batch scripts where I say "double click the file" (people always get that one!).
The solution came to me because I had a PAUSE in my main script to read console output and I noticed that after my main script called script.ps1 that I received an additional PAUSE prompt from the "main/parent" script. Which made me realize, that the parent script was able to continue after calling child script. Ergo, call nonexistent script and pipe output to null! & continue on merrily.
Example Scenario:
The following script wouldn't run via "right-click, Run w/ PowerShell" after a fresh reboot and I got the standard "Execution Policy Prompt":
script.ps1
Write-Host "Calling Scripts? No Problem!"
PAUSE

The following worked after a fresh reboot:
PowerShell.exe -ExecutionPolicy Bypass -File "C:\circumvent\industry\standard.ps1" 2>&1>$null
ECHO "This Script Won't Run Without Line 1"
ECHO "I had fun to try to circumvent an industry standard"
ECHO "I Learned a lot about PowerShell ExecutionPolicy"
C:\tmp\script.ps1
PAUSE

Result:
This Script Won't Run Without Line 1
I had fun to try to circumvent an industry standard
I Learned a lot about PowerShell ExecutionPolicy
Calling Scripts? No Problem!
Press Enter to continue...:

Update based on @BACON's comment, this is truly only possible with "run w/ powershell" via the "context menu". I tried setting "powershell" as the default app for .ps1 and not only did it not work, but the context menu removed the "run w/ powershell" option!
Thankfully, end users will have default settings and/or sysadmins will know how to resolve already.
Something I didn't test originally, but wanted to know how "circumventy" this solution really was is try using just PowerShell.exe -ExecutionPolicy Bypass in the header. This resulted in the script not running, therefor it must be assigned a -File but has no effect if File doesn't exist and allows script to continue executing.


text:
Q: How to translate a boolean formula into CNF for a SAT Solver? I'm trying to solve Minesweeper with a SAT Solver.
So far i understand the general logic of the game, how the SAT Solver works and how to implement it.
However i can't wrap my head around, how to translate my boolean formula into a CNF in order to solve it with a SAT Solver.
lets say i have the following 5x5 Board:
2 X X X X
X X X X X
X X X X X
X X X X X
X X X X X
In cell 1,1 there is value 2, which means the surrounding neighbor cells have 2 mines. Overall cell 1,1 has 3 neighbors (cell 1,2; cell 2,1; cell 2,2). I will call the neighbor cells: 1,2 and 3.
That means i have the following boolean possibilities:
cell 1 = Bomb
cell 2 = Bomb
cell 3 = No Bomb
or
cell 1 = Bomb
cell 2 = No Bomb
cell 3 = Bomb
or
cell 1 = No Bomb
cell 2 = Bomb
cell 3 = Bomb

If (a or b) and (c or not d) is a CNF than the syntax for a SAT Solver is: {{1,2},{3,-4}}
where the variables are integers and the boolean false values are negative integers and the true values are positive integers.
However, I don't know how to turn my boolean possibilities of the minesweeper field into a CNF.
My guess for cell 1,1 with 3 neighbors and 2 mines:
(Bomb 1,2 or Bomb 2,1 or no Bomb 2,2) and
(Bomb 1,2 or no Bomb 2,1 or Bomb 2,2) and
(no Bomb 1,2 or Bomb 2,1 or Bomb 2,2)

so my SAT Solver formula according to the syntax would be:
{{1,2,-3},{1,-2,3},{-1,2,3}}
Can someone please confirm or correct my SAT Solver formula?
Thank you.

Edit:

After some discussion, i came up with the following pseudo code idea/approach:
# pseudo code for cell_x_y_n of corner type (3 neighbors) with n = 2 bombs

for cell_x_y in minesweeper_board:

 if cell_x_y == corner_cell and cell_value_n == 2:

   check with SAT Solver if knowledge_base(cell_x_y_2) ∪ bomb_x_y is satisfiable:

      if satisfiable == True:
         mark cell_x_y as bomb and don't visit anymore
         continue

      if satisfiable == False:
         cell_x_y has no bomb and don't visit anymore
         continue

*

*Any remarks of any kind are highly appreciated and helpful.

*Also once i checked and looped through every cell will this approach solve the game?
Thank you.


text:
Q: configure the $ key as a "(" key We use x11vnc for our vnc servers, Remmina for our VNC viewers, and ssh to tunnel the connections. When workers connect they typically interact with a VBox guest.
When the remote machine is running a VBox guest, parenthesis are not passed through to the VM from the vnc server. Essentially all other keystrokes but parenthesis work. (This is an ancient, apparently unsolved, problem - based on searching the terms: vnc vbox parenthesis not working)
I need a work-around that keeps our our current x11vnc/remmina/vbox remote access model and does not use the built-in VBox VNC capability. In an attempt to allow parenthesis to be typed and passed to the VM, I would like try mapping a different key to send the "(" key code to the VM... for example pressing "$" key outputs a parenthesis.
How would I do this?


text:
Q: Flutter SfCalendar customize "dot" Is it possible to Customize the "dot" (Picture) inside the SfCalendar widget? I want a Icon there instead of a simple colored dot. Or is there a other package where this is possible?
Code:
 body: SfCalendar(
      view: CalendarView.month,
      initialSelectedDate: DateTime.now(),
      initialDisplayDate: DateTime.now(),
      dataSource: events,

      controller: _controller,
      onSelectionChanged: selectionChanged,
      monthViewSettings: const MonthViewSettings(
        showAgenda: true,
      ),
      onTap: (details) {
        if (details.targetElement == CalendarElement.appointment || details.targetElement == CalendarElement.agenda) {
          final Meeting appointmentDetails = details.appointments![0];
          databaseReference.collection('CalendarAppointmentCollection').doc(appointmentDetails.id).delete();
          getDataFromFireStore().then((results) {
            setState(() {});
          });
        }
      },
    ));

Here the picture.

A: You can achieve your requirement by customizing the calendar month cell with an appointment count by using the "monthCellBuilder" property of the calendar.
Refer to the KB document at the following link to learn how to customize the month cell with an appointment count in the Flutter calendar: https://www.syncfusion.com/kb/12306/how-to-customize-the-month-cell-with-appointment-count-in-the-flutter-calendar.
To know more details about "monthCellBuilder" support from the calendar, please refer to the UG document at the following link: https://help.syncfusion.com/flutter/calendar/builders#month-cell-builder


text:
Q: Android notification not able to access the received string I receive a notification in broadcast receiver like this in MainActivity.java. I need to access this string textMessage for my other classes  -
if (intent.getAction().equals("NOTIFY_TEXT_MESSAGE")){
                String textMessage = intent.getStringExtra("TextMessage");
                Intent noti_intent = new Intent(MainActivity.this, NotificationReceiver.class);
                noti_intent.setAction("NotificationReceived");
                noti_intent.putExtra("NotificationMessage",textMessage);

                PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, noti_intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder builder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.drawable.text_messages)
                                .setContentTitle(getResources().getString(R.string.Message_Title))
                                .setContentText(textMessage)
                                .setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
                                .setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
                                .addAction(0,
                                        getString(R.string.Open), pi)
                                .setAutoCancel(true);
                builder.setSound(soundUri);
                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(0, builder.build());
            }

In NotificationReceiver.class,
public class NotificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if("NotificationReceived".equals(action)) {
            String msg = MainActivity.NotificationMessage;
            Log.v("shuffTest","msg" + msg);
        }
    }
}

In my Manifest,
<receiver android:name="com.example.NotificationReceiver">
            <intent-filter>
                <action android:name="NotificationReceived" />
            </intent-filter>
        </receiver>

Why the log msg is not appearing. What is the mistake in my code?

A: Try to get the message from the intent, like this:
public class NotificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if("NotificationReceived".equals(action)) {
            String msg = intent.getStringExtra("NotificationMessage");
            Log.v("shuffTest","msg" + msg);
        }
    }
}


text:
Q: Me, my heart, and NYC Do these two sentences convey the same meaning:

*

*My heart belongs to NYC.

*My heart belongs in NYC.

A: The first one would be more suggestive of someone who loves NYC, but doesn't necessarily want to live there.
The second one would suggest the person does want, or need, to live there.
In practical usage, this difference would be very small and almost interchangeable.


text:
Q: Website not working on some IPs but is working on others I have been at it for a few days now but cannot seem to resolve the issue. My website is abc.com.
I was not able to access the website from home and thought it was down but it turns out that I could access it from my work. Upon checking further, it seems the website is accessible from some internet connections but not others.
I can't seem to understand what the issue is.
Any help would be greatly appreciated. Thanks.

A: There's a problem with the signature of your DNS zone. According to the top level registrar, it's supposed to be signed with a DNS key, but your name server hasn't signed. This means that anyone who uses a DNS resolver that checks whether the zone is properly signed isn't going to accept your zone.
The reason for signing a zone is of course that no evil third party should be able to hijack it. If you don't sign your zone with the key that's registered with the top level registrar, then nobody can know whether the information in the zone comes from the actual owner of the domain or if it's being faked.
You should report this error to your DNS provider. Further information can be found at https://zonemaster.iis.se/en/?resultid=d53221200167b1b9 . When they've fixed the error, they can re-run the Zonemaster test to verify that it's been correctly dealt with.

A: The DNS hasn't propagated your website worldwide yet. You can see the status thanks to this tool.
Here we see that it is partially avaiblable in US, and other countries.

You need to be more patient. If it doesn't resolve after a week, contact your DNS provider.


text:
Q: Why there are hearts around my Pokémon? I was playing sapphire today as usual but when I sent my zigzagoon to battle I noticed that there are hearts flown around him when it just came out of poke ball not the usual animations of lines or dots. Why is that?

A: Different kinds of Poké Balls have different animations for when they pop open. In your case, I believe it's either a Nest Ball or a Luxury Ball.


text:
Q: Last hit - Contest Programming Description
Andre and Beto are playing a computer game that rewards the players in a very particular way: only the one that gives the last hit to defeat a monster will get all the gold that the monster leave behind. This implies that, although others players may have helped to defeat the monster, only the one who gives the last hit will be rewarded.
Andre is intrigued with this system, and asked your help. Given the number of life points of the monster, the damage that Andre and Beto can cause, and the lead time necessary between two consecutive attacks, find out who will give the last hit on the monster, defeating it and getting the reward.
At the beginning both Andre and Beto will attack, dealing At and Bt damage points, respectively. After each attack, both Andre and Beto have to wait exactly Ad and Bd seconds, respectively, before they can attack again. Whenever Andre and Beto can attack at the same time (as in the beginning), Andre has the priority and attacks first. A monster is defeated when its life points come to less or equal to zero.
Input
The first line contains an integer T, indicating the number of test cases to follow.
Each test case starts with four integers At, Ad, Bt and Bd (1 ≤ At, Ad, Bt, Bd ≤ 100), indicating the attack damage and the lead time between two consecutive attacks of Andre and Beto, respectively.
Following there will be an integer H (1 ≤ H ≤ 10000), indicating the number of life points of the monster.
Output
For each test case print one line containing one name, this being "Andre" if he's the last one to hit the monster, or "Beto" otherwise.
My solution
#include <stdio.h>
#include <math.h>

int absolute(int x)
{
    return (x < 0) ? -x : x;
}
int main()
{
    int t;
    int i,j; //for loops
    scanf("%d",&t);
    for(i = 0; i < t; i++)
    {
        int att,ad,bt,bd;
        scanf("%d %d %d %d",&att,&ad,&bt,&bd);
        int h;
        scanf("%d",&h);

        int aux = 0;
        int dt = absolute(ad - bd);// time difference

        if(ad <= bd) //andre is faster ... So andre hits in every loop and beto waits for his turn
        {
            while(1)
            {
                h -= att; //andre hits
                if(h <= 0)
                {
                    printf("Andre\n");
                    break;
                }
                if(aux++ == dt)
                {
                    h -= bt;//beto hits
                    aux = 0;
                    if(h <= 0)
                    {
                        printf("Beto\n");
                        break;
                    }
                }
            }
        }
        else //beto is faster ... So beto hits in every loop and andre waits for his turn
        {
            while(1)
            {
                if(aux++ == dt) //first to hit is andre
                {
                    h -= att; //andre hits
                    aux = 0;
                    if(h <= 0)
                    {
                        printf("Andre\n");
                        break;
                    }
                }
                h -= bt; //beto hits
                if(h <= 0)
                {
                    printf("Beto\n");
                    break;
                }
            }
        }
    }
    return 0;
}

This solution gives WRONG ANSWER ... Someone has a hint ?

A: Here's a test case that you fail:
1
1 1 1 2
2

Your Output
Andre

I'm fairly sure the output should be...
Beto

Issues I'm seeing in your code

*

*Both Andre and Beto are supposed to attack on round 1

*If Andre attacks every 2nd round, and Beto attacks every 3rd round, your order of attacks will be incorrect.

Here's some working code:
#include <stdbool.h>
#include <stdio.h>
#include <math.h>

int main()
{
    int t;
    scanf("%d",&t);

    for(int i = 0; i < t; i++) {
        int at, ad, bt, bd, h;
        scanf("%d %d %d %d %d",&at, &ad, &bt, &bd, &h);

        int timestep = 0;
        while (true) {
            if (timestep % ad == 0) {
                h -= at;
            }
            if (h <= 0) {
                printf("Andre\n");
                break;
            }
            if (timestep % bd == 0) {
                h -= bt;
            }
            if (h <= 0) {
                printf("Beto\n");
                break;
            }
            timestep++;
        }
    }
}

Let's do some fuzzing with python
import subprocess
import random

def mine(inp):
    fd = subprocess.Popen("./mine", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    return fd.communicate(inp)[0]

def yours(inp):
    fd = subprocess.Popen("./yours", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    return fd.communicate(inp)[0]

def main():
    for i in range(100):
        inp = '1\n'
        inp += '{} {} {} {}\n'.format(random.randint(1, 100), random.randint(1, 100), random.randint(1, 100), random.randint(1, 100))
        inp += '{}\n'.format(random.randint(1, 1000))

        if mine(inp) != yours(inp):
            print inp.strip()
            print "My output:  ", mine(inp).strip()
            print "Your output:", yours(inp).strip()
            print

if __name__ == '__main__':
    main()

Then...
If we're confident about the output of my program. Which I am, then we can do use the fuzzing program to create random inputs that your program fails:
1
73 73 98 1
44
My output:   Andre
Your output: Beto

1
17 44 66 55
420
My output:   Beto
Your output: Andre

1
53 30 58 9
18
My output:   Andre
Your output: Beto

1
5 22 49 31
405
My output:   Beto
Your output: Andre

1
50 37 51 43
591
My output:   Beto
Your output: Andre

1
24 44 96 84
655
My output:   Beto
Your output: Andre

1
59 100 12 37
516
My output:   Andre
Your output: Beto

1
97 35 79 42
508
My output:   Beto
Your output: Andre

1
30 48 82 56
419
My output:   Beto
Your output: Andre

1
26 45 22 16
279
My output:   Andre
Your output: Beto

1
51 91 62 42
427
My output:   Andre
Your output: Beto

1
90 9 34 16
229
My output:   Beto
Your output: Andre

1
90 61 31 19
789
My output:   Andre
Your output: Beto

1
87 41 43 38
503
My output:   Andre
Your output: Beto

1
89 60 76 29
613
My output:   Andre
Your output: Beto


text:
Q: Getting serialize trait is not implemented for my struct The error I get is  at t: serialize_into(&mut f, t).unwrap(); :
the trait bound `T: models::_::_serde::Serialize` is not satisfied.
the trait `models::_::_serde::Serialize` is not implemented for `T`rustcE0277.
lib.rs(1, 1): required by a bound in this.
lib.rs(93, 8): required by this bound in `bincode::serialize_into`.
utils.rs(12, 19): consider restricting type parameter `T`.

But I have used #[derive(Deserialize, Debug, Serialize)] on the struct.
use bincode::serialize_into;
use std::io::BufWriter;

#[derive(Deserialize, Debug, Serialize)]
#[serde(tag = "m_tag")]
pub struct Profile {
        energy: HashMap<&'static str, i32>,
        guid: u64,
}

// in another file:
pub fn save_json(t:  &Profile) {
    let mut f = BufWriter::new(File::create("/tmp/foo.bar").unwrap());
    serialize_into(&mut f, t).unwrap();
}


text:
Q: How to lower I/O priority for file copying operations under Linux Mint? Whenever I copy files from a disk to another on my personal Linux system, the OS stops responding appropriately, the UI starts behaving erratically, any movies I'm playing will freeze and continue until the file transfer is done.
I don't care if the transfer takes longer.
Is there any way of lowering the I/O priority of these operations?
The main problem is when copying files using Dolphin.
I'm using Linux Mint KDE 16.

A: I am not sure how to apply that setting to all copy operations but, as a single time solution, you can use the ionice command. It will look something like that:
ionice -c 3 cp src dst

The -c is a class, which can be one of three possible:

*

*Idle (class 3) - A program running with idle io priority will only get disk time when no other program has asked for disk io for a defined grace period.

*Best effort (class 2) - This is the effective scheduling class for any process that has not asked for a specific io priority.

*Real Time (class 1) - The RT scheduling class is given first access to the disk, regardless of what else is going on in the system

For more details look here.


text:
Q: Bootstrap 4 all cards same size (multiple or single) I am facing an issue while trying to create a page contain N cards(single or multiple)
while in multiple all cards are as I want them to be, when it is a single card it shrinks and is not presented as I want it to be :

and a single card looks like this:

I am trying to understand what I am doing wrong.
this is the card HTML :

        {{expenseItem.amount}}

{{count}}

{{label}}

    Details

and it is located inside acomponent that should be a list :

Comp header

 total epenses per month {{expenses.total}}

   <app-pagination [paginationSize]="limit" [total]="total" (requierdPage)="getPage($event)"></app-pagination>

    <app-expnses-item [expenseItem]="expense"></app-expnses-item>

   <app-add-expense (onFormSubmitted)="onDataSubmit($event)"></app-add-expense>

what am I missing here?

A: The .card-deck should be placed directly in container instead of row. Remove the .row as it's flexbox, and should be used only to contain grid columns (col-*) which you're not using for the .card-deck.

        (repeat 1..n cards)

https://www.codeply.com/go/Gmch54KdgL


text:
Q: The source directory does not appear to contain CMakeLists.txt I would like to virtualize Android on my jetson nano using qemu + kvm + virglrenderer and I found these tutorials to accomplish the task :
this :
https://www.collabora.com/.../building-android-for-qemu.../
and this :
https://www.collabora.com/.../02/12/virtualizing-gpu-access/
so. on Ubuntu 20.10 I have added this script to the .bashrc file and I did : source ~/.bashrc
function add_export_env {
  local VAR="$1"
  shift
  local VAL=$(eval echo "\$$VAR")
  if [ "$VAL" ]; then
    VAL=$(concatenate_colon "$@" "$VAL");
  else
    VAL=$(concatenate_colon "$@");
  fi
  eval "export $VAR=\"$VAL\""
}
function prefix_setup {
  local PREFIX="$1"
  add_export_env PATH "$PREFIX/bin"
  add_export_env LD_LIBRARY_PATH "$PREFIX/lib"
  add_export_env PKG_CONFIG_PATH "$PREFIX/lib/pkgconfig/" "$PREFIX/share/pkgconfig/"
  add_export_env MANPATH "$PREFIX/share/man"
  export ACLOCAL_PATH="$PREFIX/share/aclocal"
  mkdir -p "$ACLOCAL_PATH"
  export ACLOCAL="aclocal -I $ACLOCAL_PATH"
}
function projectshell {
  case "$1" in
    virgl | virglrenderer)
        export ALT_LOCAL="/opt/local/virgl"
        mkdir -p "$ALT_LOCAL"
        prefix_setup "$ALT_LOCAL"
        ;;
  esac
}

and I have also installed these packages :
sudo apt install autoconf gcc-aarch64-linux-gnu libaio-dev libbluetooth-dev libbrlapi-dev libbz2-dev libcap-dev libcap-ng-dev libcurl4-gnutls-dev libepoxy-dev libfdt-dev libgbm-dev libgles2-mesa-dev libglib2.0-dev libibverbs-dev libjpeg8-dev liblzo2-dev libncurses5-dev libnuma-dev librbd-dev librdmacm-dev libsasl2-dev libsdl1.2-dev libsdl2-dev libseccomp-dev libsnappy-dev libssh2-1-dev libtool libusb-1.0-0 libusb-1.0-0-dev libvde-dev libvdeplug-dev libvte-2.90-dev libxen-dev valgrind xfslibs-dev xutils-dev zlib1g-dev

and configured these paths :
export PROJECT_PATH="/opt/qemu_android"
export VIRGLRENDERER_PATH="${PROJECT_PATH}/virglrenderer"
export QEMU_PATH="${PROJECT_PATH}/qemu" export LINUX_PATH="${PROJECT_PATH}/linux"
export ANDROID_PATH="${PROJECT_PATH}/android"
export ANDROID_TOOLS_PATH="${PROJECT_PATH}/android-tools"

then :
git clone git://anongit.freedesktop.org/virglrenderer

root@aorus:/opt/qemu_android/virglrenderer# ls

ci docs   perf-testing  virglrenderer.pc.inconfig.h.meson meson.build   src vtestCOPYING meson_options.txt  tests

root@aorus:/opt/qemu_android/virglrenderer# ./autogen.sh

bash: ./autogen.sh: File or directory not found

I don't know how to compile it,since the classic way does not work (mkdir build ; cd build ; cmake ..) it says :
CMake Error: The source directory does not appear to contain CMakeLists.txt. Specify --help for usage, or press the help button on the CMake GUI.

A: When you ran ls and saw the files in your virgilrenderer folder there isn't an ./autogen.sh but there is a meson.build
So let's try that.
sudo apt install build-essential
sudo apt install meson ninja-build
cd /opt/qemu_android/virglrenderer
meson compile

Once Meson is installed, and you are in the directory that the meson.build file is, you should be able to just run the meson compile command.
Official Docs for Meson


text:
Q: Как сделать UIButton-ссылку (например на YouTube)? Основной части нет, просто отдельный вопрос

A: Предполагается, что к этому коду прилагается вьюха с кнопкой. ViewController привязан к этому классу, а @IBAction привязан к кнопке (извините, что пишу это, так как не знаю вашего уровня).
import UIKit

class ViewController: UIViewController {

  @IBAction func button(_ sender: UIButton) {
    let url = URL(string: "https://www.youtube.com/watch?v=H9YxpwWNK9k")!
    UIApplication.shared.open(url, options: [:])
  }

}


text:
Q: How to store 36 bit image? I have a Raw Bayer image. Each channel(R,G and B) has bitdepth of 12. I would like to demosaic it and store it without losing the bitdepth in Matlab. How to store without losing the bitdepth?

A: You cannot store a 36 Bit image! The standard way of storing it is to Store as 16-Bit image format. So 16*3= 48 Bits e.g you can store it in .png format!
e.g
imwrite(A,'myImage.png');


text:
Q: Where can I download Biblatex? - a complete novice I am a complete novice latex and I am currently learning how to create the bibliography. The tutorial I am looking at is https://www.latex-tutorial.com/tutorials/biblatex/
It tells me to use the bibtex but I cannot find a site in google where I can download the program. Could anyone recommend a website I can download the bibtex?


text:
Q: Get Instagram Feeds using username/user id Earlier I had used
https://www.instagram.com/graphql/query/?query_id=17888483320059182&variables=$result
Now from this month as instagram has changed there api I am unable to get feeds.
Any suggestion will be helpfull

A: Follow my steps
first, you will need to register your application on the Instagram developer site and obtain your Client ID & Client Secret code, then you have to create access_token with Client ID & Client Secret
visit here : https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/ for creating Client ID, Client Secret & access_token
Then, add following code in your controller function
$access_token = 'xxxxxxxxxx.xxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // your access_token will be this format
$count_feed = 2; // how many feed want to load

$requestURL = 'https://api.instagram.com/v1/users/self/media/recent?access_token='.$access_token.'&count='.$count_feed;
$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $requestURL,
    CURLOPT_HEADER  => false,
    CURLOPT_RETURNTRANSFER => 1
));
$json_response = curl_exec($ch);
curl_close($ch);
$insta_feeds = json_decode($json_response, true);

_e($insta_feeds); // $insta_feeds['data'] will return feed

You can get the feed by using the Instagram library. check out the library here : https://github.com/suhindra/CodeIgniter-Instagram-API


text:
Q: Algorithm or Code for creating array, rule is as specified? I want to create 2D array as below:
For Example:
For level 3:

         7            => Array[2]

   3          6       => Array[1]

1     2     4     5   => Array[0]

i.e. Array = [[1,2,4,5], [3,6], [7]]

.
For level 4:

                    15                          => Array[3]

         7                      14              => Array[2]

   3          6           10           13       => Array[1]

1     2     4     5    8     9     11     12    => Array[0]

i.e. Array = [[1,2,4,5,8,9,11,12], [3,6,10,13], [7,14], [15]]

What I need is a function taking number of level as argument returning Array as mentioned above.
i.e:
def function(level):
    ''' ..........................

    ...........................'''
    return Array

A: Hint: Here is the last row of numbers
def last_row(level):
    m = 2 ** (level - 1)
    L = [0 for i in range(m)]
    L[0] = 1
    k = 1
    while k < m:
        incr = 2 * k - 1
        for i in range(k):
            L[k+i] = L[i] + incr
        k = incr + 1
    return L

A: Your data structure is recursive, so it's natural to use a recursive function to produce it.
The root node of the tree of depth depth is n = 2 ** depth - 1; it's more efficient to calculate that using bit shifting. The left subtree has a root node of n // 2, the right subtree is identical except that n // 2 is added to all its nodes.
Here's a recursive generator that produces the desired list.
def btree(depth):
    if depth < 1:
        return

    n = (1 << depth) - 1
    yield [n]

    a = n // 2
    for seq in btree(depth - 1):
        yield seq + [u + a for u in seq]

lst = list(btree(4))[::-1]
print(lst)

output
[[1, 2, 4, 5, 8, 9, 11, 12], [3, 6, 10, 13], [7, 14], [15]]

If you want to print the tree rows in top-down order, you can just do this:
for row in btree(5):
    print(row)

output
[31]
[15, 30]
[7, 14, 22, 29]
[3, 6, 10, 13, 18, 21, 25, 28]
[1, 2, 4, 5, 8, 9, 11, 12, 16, 17, 19, 20, 23, 24, 26, 27]

A: Here is another recursive solution that I figured. The left sub-tree value is floor(current value) and the right sub-tree value is (current value -1).
I pre-calculate the necessary powers of 2, but the draw-back is my passing of additional arguments (lists): In any case, hopefully this will be helpful for clarity when building a solution.
def driver(level):
    if level <= 0:
        return None
    # initialize the list to have (level) columns
    lst = [[] for i in range(level)]
    # pre-calculate the necessary powers of 2
    powers = [1]
    for i in range(1, level+1):
        powers.append(powers[i-1] << 1)

    # call the main calculation function
    calc(level, powers[level]-1, lst, powers)

    return lst

def calc(level, val, lst, powers):
    # add the value in pre-order
    lst[level-1].append(val)
    # base case, level is 1,
    # do not make additional recursive calls here
    if level > 1:
        # calculate values in the left sub-tree
        calc(level-1, val - powers[level-1], lst, powers)
        # calculate values in the right sub-tree
        calc(level-1, val-1, lst, powers)

print(driver(4))


text:
Q: Adding a fancybox to this wordpress theme I am buiding a new portfolio, you can see here.
www.mikelucid.com
My issue comes because the  tags have other html in then including an overlay that wyou actually click. This has made adding the fancy box impossible.
Would any expert be willing to take  a quick peak?
I was trying to do soething like this but couldnt get it working :/
$( document ).ready(function() {
    $("a.the_post").click(function(e) {
        var outerHTML = $("<div />").append($(this).find('.wp-post-image').clone()).html();
        console.log(outerHTML)
        $(this).fancybox({
            'content': outerHTML,
        });
        e.preventDefault();
    });
});

A: I don't know if this solves your issue but this piece of code
$(this).fancybox({
    'content': outerHTML,
});

doesn't trigger fancybox, it only binds fancybox to the referred element every time you click on a.the_post
Try doing this instead
$.fancybox({
    'content': outerHTML,
});


text:
Q: "Error retrieving consenter of type: etcdraft" when trying to set up Hyperledger Fabric I did the following the instructions in the manual when trying to set up Hyperledger Fabric 1.4.7 and having cloned the samples from GitHub and used the first-network starting point. At first, I got the expected output: (I removed all the references to EtcdRaft in configtx.yaml)
rm -r channel-artifacts/*
export FABRIC_CFG_PATH=$PWD
cryptogen generate --config=./crypto-config.yaml
configtxgen -profile TwoOrgsOrdererGenesis -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block
export CHANNEL_NAME=mychannel
configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP
configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org2MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org2MSP
docker-compose -f docker-compose-cli.yaml up -d

Now docker is up and I try this:
docker logs orderer.example.com

And after normal output, I get this:
2020-06-16 18:08:47.746 UTC [orderer.commmon.multichannel] newChainSupport -> PANI 008 Error retrieving consenter of type: etcdraft
panic: Error retrieving consenter of type: etcdraft

goroutine 1 [running]:
github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore.(*CheckedEntry).Write(0xc0000ec580, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/zapcore/entry.go:229 +0x546
github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).log(0xc000240070, 0x4, 0x156734e, 0x26, 0xc000347b30, 0x1, 0x1, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:234 +0x100
github.com/hyperledger/fabric/vendor/go.uber.org/zap.(*SugaredLogger).Panicf(...)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/go.uber.org/zap/sugar.go:159
github.com/hyperledger/fabric/common/flogging.(*FabricLogger).Panicf(...)
        /opt/gopath/src/github.com/hyperledger/fabric/common/flogging/zap.go:74
github.com/hyperledger/fabric/orderer/common/multichannel.newChainSupport(0xc000172000, 0xc00054a060, 0xc0003205d0, 0x16c8800, 0x208ffe0, 0xc000324540, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/multichannel/chainsupport.go:69 +0xa06
github.com/hyperledger/fabric/orderer/common/multichannel.(*Registrar).Initialize(0xc000172000, 0xc0003205d0)
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/multichannel/registrar.go:168 +0x252
github.com/hyperledger/fabric/orderer/common/server.initializeMultichannelRegistrar(0xc0003b8b80, 0x0, 0x0, 0x0, 0xc0002065a0, 0x2021b00, 0xc0003ee0e0, 0x2, 0x2, 0xc0003ee0f0, ...)
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:681 +0x4a5
github.com/hyperledger/fabric/orderer/common/server.Start(0x1543ab2, 0x5, 0xc0002c2480)
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:189 +0xa94
github.com/hyperledger/fabric/orderer/common/server.Main()
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x208
main.main()
        /opt/gopath/src/github.com/hyperledger/fabric/orderer/main.go:15 +0x20

But there is no more reference to EtcdRaft anywhere that I can find. What's going on?
EDIT:
Trying to add EtcdRaft creates this error instead:
2020-06-17 01:10:40.083 UTC [orderer.commmon.multichannel] Initialize -> INFO 00e Starting system channel 'byfn-sys-channel' with genesis block hash fbbc5d4bd63c38a9623fb3c3d68493d8441d3de4e249d9a8cabba0619978c56d and orderer type etcdraft
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0xfaee39]

EDIT:
I tried it with Hyperledger Fabric version 2.1, which requires Raft, and I get the same error from Raft as above.
EDIT:
For the sake of completeness, here's the full log of the log for the orderer for Hyperledger 1.4.7 and the full log for the orderer Hyperledger 2.1.0.

A: If you are receiving the panic:
Error retrieving consenter of type: etcdraft
This can generally be attributed to one of two things.

*

*You are using Fabric v1.4.0, rather than v1.4.1+.  Raft ordering was introduced in v1.4.1, which is often a topic of confusion.

*You have specified a Genesis Type of None and are using a version of Fabric prior to v2.2.0 which at the time of this writing is unreleased.  This bug is documented as FAB-17774 and should be included as part of v2.2.0.
If you ensure that the images you are using are current, and that genesis type is not set to none, I expect your errors will go away.
If on the other hand, you are attempting to use some consensus type other than etcdraft (which, for new deployments etcdraft is the recommended consensus type), then ensure that the consensus type in your configtx.yaml has been set to the appropriate type, for instance 'solo'.  Ensure that all artifacts, including any volumes persisted by your docker compose have been deleted, and try again.


text:
Q: How to declare my method to receive any kind of list as argument? public static int menu(String texto, ArrayList<String> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i));
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

I have this method that receives a text (texto) prompting the user to input an option number and an ArrayList with the options.
e.g. {Create entry, remove entry, quit}
solicitarNumero handles the request of the option number and verifies it.
Right now when I'm calling this method using variables of different classes (Franquicia, Gerente, Sistema) I have to go over each ArrayList and create a new one containing that class' toString.
Like so
for (Franquicia franquicia : listaFranquicia) {
    listaDatosFranquicia.add(franquicia.toString());
}

Then I use the method with the new ArrayList.
menu("Ingrese el numero de franquicia "
            + "que desea asignar a este control",
            listaDatosFranquicia) - 1));

Is there a way I could simply do
menu("Ingrese el numero de franquicia "
            + "que desea asignar a este control",
            listaFranquicia) - 1));

Without having to create a new ArrayList?

A: Yes. Change the method to
public static int menu(String texto, List<?> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i));
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

which is basically equivalent to:
public static int menu(String texto, List<?> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i).toString());
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

unless one of your options is null (in which case the second one will cause a NullPointerException, whereas the first one will print "null").
List<?> means: a list of some unknown type. But since all types extend java.lang.Object, and all you care about is the toString() representation of the objects, you don't really need to know the actual generic type of the list.

A: Not without changing the method menu.
listaFranquicia is a List<Franquicia> and the method expects a List<String> so you need to convert each Franquicia into a String and make a new list with the result, exactly with the code you have.
It's a bit cumbersome but note that with Java 8, it can be written more simply in a single line:
List<String> listaDatosFranquicia = listaFranquicia.stream()
                                                   .map(Franquicia::toString)
                                                   .collect(Collectors.toList());

A: I think a much better signature for your menu method would be
public static int menu(final String texto, final List<?> opciones)

This way you can accept any kind of list of objects, and it will rely on how that instance implements toString() method.
Also note I changed ArrayList to List. It is always better to use the interface instead of the specific implementation when possible.


text:
Q: How catch error in the front-end from response of expressjs? My problem is the next:

//express server
app.post('/register', (req, res) => {
    const {
        password,
        passwordConfirm
    } = req.body;
    if (password === passwordConfirm) {
     //...
    } else {
        res.status(400).json("Passwords aren't matching")
    }
})
//react function
    onSubmitSignIn = () => {
        const { password, passwordConfirm } = this.state;
        let data = new FormData();
        data.append('password', password);
        data.append('passwordConfirm', passwordConfirm);

        fetch('http://localhost:3001/register', {
            method: 'post',
            body: data
        })
        .then(response => response.json())
        .then(user => {
            //logs error message here
            console.log(user)
        })
        //but I want to catch it here, and set the message to the state
        .catch(alert => this.setState({alert}))
    }

When I send the status code, and the message from express as the response, the front-end obviously recognize it as the response, that's why it logs the message to the console as "user". But how to send error which goes to the catch function?

A: fetch will really only error if it for some reason can't reason the API. In other words it will error on network errors. It will not explicitly error for non 2XX status codes.
You need to check the ok property as described here:

*

*https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful

*https://developer.mozilla.org/en-US/docs/Web/API/Response/ok
--
fetch('http://localhost:3001/register', {
    method: 'post',
    body: data
 })
 .then(response => {
     if (!response.ok) {
         throw new Error('my api returned an error')
     }
     return response.json()
 })
 .then(user => {

      console.log(user)
  })
  .catch(alert => this.setState({alert}))

A: The problem is, that fetch is not recognizing the HTTP errors as Promise rejections.

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

(Source)
You can checkout the linked source of the fetch repo which also states a suggestion for handling HTTP error statuses.

A: What if you throw an error :
app.get("/", function (req, res) {
  throw new Error("BROKEN"); // Express will catch this on its own.
});

And then catch this error in the front end ?
See here for reference
EDIT
Maybe should you return the error with return next() so that the rest of the code is not processed in the server method :
 app.get("/", function (req, res) {
     return next(new Error('BROKEN'));
 });

A: //express server
app.post('/register', (req, res) => {
 try {
  const {
   password,
   passwordConfirm
  } = req.body;
  if (password === passwordConfirm) {
   //...
  } else {
   res.status(400).json("Passwords aren't matching")
  }
 } catch (error) {
  res.status(500).send(error);
 }
})
//react function
onSubmitSignIn = () => {
 const {
  password,
  passwordConfirm
 } = this.state;
 let data = new FormData();
 data.append('password', password);
 data.append('passwordConfirm', passwordConfirm);

 fetch('http://localhost:3001/register', {
   method: 'post',
   body: data
  })
  .then(response => response.json())
  .then(user => {
   //logs error message here
   console.log(user)
  })
  //but I want to catch it here, and set the message to the state
  .catch(alert => this.setState({
   alert
  }))
}


text:
Q: How to validate a user role using jaas and redirect user to specific module on the basis of Role Target:
I have 5 roles defined in web.xml and I need to implement the JAAS form based auth. I am successfully able to login but authentication based redirection is not working and still I am on login page with error that says invalid username or password. I cant understand how to handle this. Also, A user can have multiple roles and the user can roam anywhere on basis of this. I am using JSF, primefaces, Wildfly 10.x, Maven build structure, Mysql as database and JAAS obviously.
I have searched over web but no solution was able to solve my problem and I am still struggling.
Here is my web.xml

<security-role>
<description>Administrator</description>
<role-name>ADMIN</role-name>
</security-role>
<security-role>
    <description>Accounting</description>
    <role-name>ACCOUNTS</role-name>
</security-role>

<security-role>
    <description>HR Management</description>
    <role-name>HR</role-name>
</security-role>

<security-role>
    <description>normal pages</description>
    <role-name>BASIC</role-name>
</security-role>

<login-config>
     <auth-method>FORM</auth-method>
     <realm-name>custom-authentication-security</realm-name>
     <form-login-config>
          <form-login-page>/index.xhtml</form-login-page>

          <form-error-page>/index.xhtml?fail=true</form-error-page>

     </form-login-config>
</login-config>
<security-constraint>
    <web-resource-collection>
         <web-resource-name>custom-authentication-security</web-resource-name>
         <url-pattern>/user/*</url-pattern>
         <http-method>POST</http-method>
          <http-method>GET</http-method>
    </web-resource-collection>
    <auth-constraint>
         <role-name>ADMIN</role-name>
         <role-name>HR</role-name>
         <role-name>ACCOUNTS</role-name>
         <role-name>BASIC</role-name>
   </auth-constraint>
</security-constraint>

jboss-web.xml is
<jboss-web>
        <security-domain>custom-authentication-security</security-domain>
</jboss-web>

Here is the security domain definded in standalone.xml:
 <security-domain name="custom-authentication-security" cache-type="default">
                    <authentication>
                        <login-module code="com.hotel.security.JAASLoginModule" flag="required">
                            <module-option name="hashAlgorithm" value="MD5"/>
                            <module-option name="hashEncoding" value="base64"/>
                            <module-option name="unauthenticatedIdentity" value="guest"/>
                        </login-module>
                    </authentication>
</security-domain>

and finally my login() and commit() specified in JAASLoginModule :
public boolean login() throws LoginException {
        System.out.println("Login Mathod Called");

        if (callbackHandler == null){
            throw new LoginException("Error: no CallbackHandler available " +
            "to garner authentication information from the user");
        }
        Callback[] callbacks = new Callback[2];
        callbacks[0] = new NameCallback("username");
        callbacks[1] = new PasswordCallback("password: ", false);

        try {

            callbackHandler.handle(callbacks);
            username = ((NameCallback)callbacks[0]).getName();
            password = ((PasswordCallback)callbacks[1]).getPassword();

            if (debug) {
                LOGGER.debug("Username :" + username);
                LOGGER.debug("Password : " + new String(password));
            }

            if (username == null || password == null) {
                LOGGER.error("Callback handler does not return login data properly");
                throw new LoginException("Callback handler does not return login data properly");
            }
            System.out.println("Username:"+username);
            System.out.println("password:"+new String(password));
            System.out.println("isValidUser:"+isValidUser());

            if (isValidUser()) { //validate user.
                succeeded = true;
                return true;
            }

        } catch (IOException e) {
             e.printStackTrace();
        } catch (UnsupportedCallbackException e) {
             e.printStackTrace();
        }

        return false;
    }

    @Override
    public boolean commit() throws LoginException {
        if (succeeded == false) {
            return false;
        } else {
            System.out.println("Adding Principals");

            userPrincipal = new JAASUserPrincipal(username);
            if (!subject.getPrincipals().contains(userPrincipal)) {
                subject.getPrincipals().add(userPrincipal);
                LOGGER.debug("User principal added:" + userPrincipal);
            }
            passwordPrincipal = new JAASPasswordPrincipal(new String(password));
            if (!subject.getPrincipals().contains(passwordPrincipal)) {
                subject.getPrincipals().add(passwordPrincipal);
                LOGGER.debug("Password principal added: " + passwordPrincipal);
            }

            //populate subject with roles.
            List<String> roles = Arrays.asList( new String[] {"ADMIN","HR","ACCOUNT","BASIC"});
            for (String role: roles) {
                JAASRolePrincipal rolePrincipal = new JAASRolePrincipal(role);
                if (!subject.getPrincipals().contains(rolePrincipal)) {
                    System.out.println("Adding role :"+ role);
                    subject.getPrincipals().add(rolePrincipal);
                    LOGGER.debug("Role principal added: " + rolePrincipal);
                }
            }

            SessionManagerBean sessionBean=SessionFactoryImpl.getSessionManagerBean();
            sessionBean.setCurrentCuser(new CUserServiceImpl().getUserByName(username));

            sessionBean.setIsadmin(true);

            sessionBean.setIsuserloggedin(true);
            sessionBean.setUsername(username);
            sessionBean.setPassword(new String(password));

            commitSucceeded = true;

            LOGGER.info("Login subject were successfully populated with principals and roles");

            return true;
       }
   }

Now, when I am trying to access any page with url /user/ChangePassword.xhtml it redirect me to login.xhtml and when I pass incorrect credentials, is returns me to same page. that is correct. but URL is not changing to /index.xhtml this is issue -1.
When I pass correct login id and password, the URL changes to http://localhost:8080/HotelManager/user/j_security_check and once again I am getting message invalid userid password.
After successful login, it should be redirected to /user/ChangePassword.xhtml issue -2.
I need to handle a user and redirect him/her to specific page on the basis of Role issue -3.
Finding solution. Hope experts can help well.
Pardon me if I am not able to explain the situation properly.
Thanks in advance


text:
Q: Curl login php with hidden form i want to use curl to some site. But the site is required a hidden form.
Form HTML is like this:
<form method="get" name="login" action="example.com/procced.php">
    <input id="username" type="text" name="username" placeholder="Your email address" required /><br/>
    <input id="password" type="password" name="password" placeholder="Password" required />
    <input type="text" name="request_token" id="request_token" value="5433db648b28c3aaffcf63e650541c37aaa34614" style="display: none"/>
    <input type="submit" id="submit" value="Log in" />
</form>

how i curl php with that hidden form (name="requrest_token")

A: Try to use this:
$url = "otherwebsiterul";  // url where you want to access
$data = $_POST; // your form data as you want to pass.
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);


text:
Q: Data is not updating enter image description here
So unfortunetly my data is not updating even though I get a status request of 200 ok below are my front end and back end code
app.put('/movielist/updateMovie/:id',(req,res) =>{
  let update = req.body;
  mysqlConnection.query("UPDATE movielist SET name = ?, thumnail_path = ?, description = ?, year_released = ?, language_released = ? WHERE idmovielist = ?",
 [update.name,update.thumnail_path,update.description,update.year_released,update.language_released,req.params.id],function (err, results) {
    if (!err) {
      res.send("Movie list is updated");
    } else {
      console.log(err);
    }
  });
});

Above is my update query
$(function() {
  //Fill the list when the page loaded
  renderMovieList('movies');

  $("#movieAdded").click(function(a) {
    a.preventDefault();

    let mydata = {
      idmovielist: $($("#newForm")[0].intNum).val(),
      name: $($("#newForm")[0].name).val(),
      thumnail_path: $($("#newForm")[0].thumnail_path).val(),
      description: $($("#newForm")[0].description).val(),
      year_released: $($("#newForm")[0].year_released).val(),
      language_released: $($("#newForm")[0].language_released).val(),
    }

    displayMovie(mydata);

    $("#newForm").trigger("reset");
    $("#newForm").toggle();
  });

  $("#updateMovie").on("click", function(a) {
    a.preventDefault();

    let data = {
      idmovielist: $($("#updateForm")[0].intNum).val(),
      name: $($("#updateForm")[0].name).val(),
      thumnail_path: $($("#updateForm")[0].thumnail_path).val(),
      description: $($("#updateForm")[0].description).val(),
      year_released: $($("#updateForm")[0].year_released).val(),
      language_released: $($("#updateForm")[0].language_released).val(),
    }

    putMovie($($("#updateForm")[0].movieId).val(), data);

    $("#updateForm").trigger("reset");
    $("#updateForm").toggle();
  });

  $("body").on('click', '.editMovie', function(a) {
    a.preventDefault();

    getOneMovie($($(this)[0]).data("movieId"));
  });

  $("body").on('click', '.deleteMovie', function(a) {
    a.preventDefault();

    deleteMovie($($(this)[0]).data("movieId"));
  });

});

//FUNCTIONS PART----------------------------------------------

function renderMovieList() {
  alert('getList');
  $.ajax({
    method: "GET",
    url: "http://localhost:3000/movielist",
    dataType: "json",
    success: function(response) {
      $('#movies').empty();
      $.each(response, function(i, movie) {
        const rowText = "
" +
          "" + movie.idmovielist + "	" +
          "" + movie.name + "	" +
          "" + movie.thumbnail_path + "	" +
          "" + movie.description + "	" +
          "" + movie.year_released + "	" +
          "" + movie.language_released + "	" +
          "" + "<button button id = \"deleteMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal2\">Delete</button>" + "	" +
          "" + "<button button id = \"editMovie\" type=\"button\"  class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal2\">Edit</button>" + "	";
        $("#movies").append(rowText);
      });
    }
  });
}

function getOneMovie(id) {
  $.ajax({
    url: "http://localhost:3000/movielist" + id,
    method: 'GET',
    dataType: 'json',
    success: function(data) {
      $($("#updateForm")[0].movieId).val(data._id);
      $($("#updateForm")[0].intNum).val(data.intNum);
      $($("#updateForm")[0].name).val(data.name);
      $($("#updateForm")[0].thumnail_path).val(data.thumnail_path);
      $($("#updateForm")[0].description).val(data.description);
      $($("#updateForm")[0].year_released).val(data.year_released);
      $($("#updateForm")[0].language_released).val(data.language_released);
      $("#updateForm").show();
    }
  });
}

function displayMovie(mydata) {
  $.ajax({
    method: "POST",
    url: "http://localhost:3000/movielist/addMovie",
    dataType: "json",
    data: mydata,
    success: function(data) {
      console.log(data);
      renderMovieList();
    }
  });
}

function putMovie(data) {
  $.ajax({
    url: "http://localhost:3000/movielist/updateMovie/2",
    method: 'PUT',
    dataType: 'json',
    data: data,
    success: function(data) {
      console.log(data);
      getOneMovie();
    }
  });
}

function deleteMovie(id) {
  $.ajax({
    url: "http://localhost:3000/movielist/" + id,
    method: 'DELETE',
    dataType: 'json',
    success: function(data) {
      console.log(data);
    }
  });
}

So basically I set my values in my update query to question marks so I can manually enter them in the UI I had put single quotation marks on the '?' but I was getting null values what can I do so that the info can be updated


text:
Q: Удаление файлов в каталогах и подкаталогах старше определенной даты последнего изменения Уважаемые эксперты, помогите  разобраться.
Есть OpenBrowserDialog через него выбираем корневой каталог, в нем  содержатся подкаталоги с  тестовыми файлами.
Как организовать удаление всех файлов в подкаталогах которые старше определенной даты  последнего изменения? Можно ли установить дату визуально? Можно ли сделать  выбор диапазона который  не удалять, пример: удаляем все .txt файлы в каталогах  и подкаталогах кроме файлов  у которых дата последнего изменения (01.12.2019 - 31.12.2019).

A: все это можно для выбора даты используйте MonthCalendar в ToolBox если делаете на WinForms
вот пример поиска по папкам
список будет содержать пути ко всем найденным файлам
public List<string> Files = new List<string>();

метод для поиска во всех папках и под папках
   public void DirSearch(string sDir)
            {
                foreach (var f in Directory.GetFiles(sDir))
                {

                   Files.Add(f.ToLower());

                }
                foreach (var d in Directory.GetDirectories(sDir))
                {
                   DirSearch(d);
                }

            }

потом можете пройтись по списку с файлами и посмотреть какие файлы соответствуют вашим критерием и если надо удалить их


text:
Q: Launching Rattle I have tried launching rattle in my system, it failed every time. I am using a Mac, system details are given below:

*

*macOS Big Sur

*11.4 version

*Intel core i5 processor

Why am I receiving the same error?


text:
Q: Troublesome integrals in Hamiltonian matrix elements for a system of two interacting electrons I have a quantum mechanical system of two interacting electrons in one spatial dimension. The Hamiltonian of the system is of the form $H = h + \frac{1}{|x_1 - x_2|}$, where $h$ is a one-electron part irrelevant to the current question, and $x_1, x_2 \in [0, a],\, a > 0$ are spatial coordinates of the electrons in the system. I have decided to use configuration interaction method(Ritz method if you will) to solve the ground state energy of this system numerically. This involves expanding the exact two-electron wave function in a basis of Slater determinants
$$\frac{1}{\sqrt{2}}\begin{vmatrix} \chi_i(\mathbf{x}_1) & \chi_j(\mathbf{x}_1) \\ \chi_i(\mathbf{x}_2) & \chi_j(\mathbf{x}_2) \end{vmatrix}.$$
$\chi_i$ is a spin-"orbital", which is simply a product of a one-electron wave function $\psi_i$ and either spin eigenfunction $\alpha$ or $\beta$ (corresponding to spin-up and spin-down, this notation is from Modern Quantum Chemistry by Szabo and Ostlund). $\alpha$ and $\beta$ are functions of a spin-variable $\omega$ and they are orthonormal wrt an inner product which is denoted by an integral, so e.g. $\int \alpha^*(\omega)\beta(\omega) \,d\omega = 0 $ (bit of an abuse of notation). In addition, $\mathbf{x}_i = (x_i, \omega_i)$. Below I use overbar to denote the spin-part of a spin-orbital so that $\chi_i = \psi_i\alpha$ and $\bar{\chi}_i = \psi_i\beta$.
The problem I have lies in the evaluation of the integrals needed to calculate the Hamiltonian matrix elements for the configuration interaction method. One  type of these integrals is
$$I(\bar{\chi}_i, \chi_j, \bar{\chi}_k, \chi_l) \equiv \int d\mathbf{x}_1d\mathbf{x}_2
\big[\bar{\chi}_i(\mathbf{x}_1)\chi_j(\mathbf{x}_2) - \chi_j(\mathbf{x}_1)\bar{\chi}_i(\mathbf{x}_2)\big]
\frac{\bar{\chi}_k(\mathbf{x}_1)\chi_l(\mathbf{x}_2) - \chi_l(\mathbf{x}_1)\bar{\chi}_k(\mathbf{x}_2)}{|x_1-x_2|} \tag{1},$$
which involve Slater determinants formed by both a spin-orbital with spin-up and a spin-orbital with spin-down. Now, if I were to directly use the orthonormality of $\alpha$ and $\beta$, I would get
$$I(\bar{\chi}_i, \chi_j, \bar{\chi}_k, \chi_l) = \int \frac{dx_1dx_2}{|x_1-x_2|}
\big[\psi_i(x_1)\psi_j(x_2)\psi_k(x_1)\psi_l(x_2) + \psi_j(x_1)\psi_i(x_2)\psi_l(x_1)\psi_k(x_2)\big] \tag{2},$$
which very much looks like a diverging integral to me since $\frac{1}{|x_1-x_2|}$ has a singularity at $x_1 = x_2$, while the nominator of the integrand does not vanish at $x_1 = x_2$. Integrals such as $I(\chi_i, \chi_j, \chi_k, \chi_l)$ and $I(\bar{\chi}_i, \bar{\chi}_j, \bar{\chi}_k, \bar{\chi}_l)$ can be simplified to
$$ \int dx_1dx_2
\big[\psi_i(x_1)\psi_j(x_2) - \psi_j(x_1)\psi_i(x_2)\big]
\frac{\psi_k(x_1)\psi_l(x_2) - \psi_l(x_1)\psi_k(x_2)}{|x_1-x_2|}.$$
which is finite thanks to the antisymmetrized wavefunctions, which vanish at $x_1=x_2$, in the integrand.
Assuming steps between (1) and (2) aren't justified, I have tried other approaches for calculating $(1)$ and found that
$$
\int dx_1dx_2
\big[\psi_i(x_1)\psi_j(x_2) - \psi_j(x_1)\psi_i(x_2)\big]
\frac{\psi_k(x_1)\psi_l(x_2) - \psi_l(x_1)\psi_k(x_2)}{|x_1-x_2|}
= I(\bar{\chi}_i, \chi_j, \bar{\chi}_k, \chi_l) + I(\bar{\chi}_i, \chi_j, {\chi}_k, \bar{\chi}_l)  $$
but this doesn't seem to lead anywhere.
Is there a way to express $I(\bar{\chi}_i, \chi_j, \bar{\chi}_k, \chi_l)$ as a convergent integral involving only spatial wave functions $\psi_i$ or is this model/formalism unfounded applied to this system?
Edit: To give a bit more background, I am trying to get results similar to the ones obtained in this paper. One of the methods they use in that paper is actually Ritz method, but with a bit different basis set and and without spin.
I am also aware of the close relationship to 1D hydrogen atom which was pointed out by Vadim in their answer. I believe I should be able to get finite results in this case(see the earlier paper). And after thinking about it more, I think my best bet is to use a different set of basis functions.

A: Firstly, it seems that you haven't correctly used the orthonormality of the spin functions, as your integral lacks the exchange term. This is probably the result of inconsistent notation, as $\alpha,\beta$ mean spin states of two electrons ($x_1$ and $x_2$) but not necessarily different spin states.
Secondly, in one dimension the Coulomb interaction may still diverge - this is certainly the case for the attractive interaction - see the classical paper of Loudon, much cited in connection to excitons in carbon nanotubes.
Finally, perhaps the Coulombn interaction in your problem is not at all $1/|x_1-x_2|$? E.g., in quantum wires this is certainly not the case - although the electrons may be confined to 1D, the Coulomb interaction remains three-dimensional; moreover, it may be screened.

A: An integral with a $1/|x|$   need not diverge.  For example
$$
\int_{|x|<R} \frac 1 {|x|}d^3x = 4\pi \int_0^R \left(\frac 1 r\right) r^2 dr = 2\pi  R^2
$$
does not diverge.


text:
Q: writing an app on iOS 5 - backward compatible? Im using iOS5 to write my app. So does that mean it will only run on devices running iOS5 or are these apps backward compatible with other versions of iOS?
If they are not compatible how do I write them so they are?
Any help would be greatly appreciated.
Thanks

A: In your applications build settings you can set the "iOS Deployment Target" variable. In the current SDK this goes down to version 3.0. You cannot use the latest features then, but your app will run on the specified target. Also be sure that you build for armv6 and armv7 architectures when specifying a deployment target lower that 5.0 (but XCode will warn you in that case).


text:
Q: Data Object unable to summation inside the computed properties in VUE js 3 Let see the following code segment in vue.js 3,
<template>

Computed Total - {{getPrice()}}

</template>

After run this code it is showing, error  'items' is not defined  no-undef
As we know that computed property doesn't need to declarer any argument. Then what's wrong with the code?

A: There are few problems with your code:

*

*When using computed property, don't use () - it is a property, not a function

Computed Total - {{ getPrice }}

*All members of data, computed or methods when used in the script part of the Vue component, must be referenced with this ...for example this.items
computed: {
        getPrice() {
            return this.items.reduce((total, curr) => total + curr.price, 0)
        }
    }


text:
Q: basic_string::resize Error When Deploying Custom Sklearn Model on GCP I want to deploy a successful custom training job on GCP using a prebuilt scikit-learn container. The model I am using is a scikit-learn RandomForestClassifier saved using joblib. The deployment fails with
message: "terminate called after throwing an instance of 'std::length_error'"
However, based on this question, I can make a prediction by accessing GCSFS with the following:
from io import BytesIO
import numpy
blob = bucket.blob('project/model/model.joblib')
model_file = BytesIO()
blob.download_to_file(model_file)
model = joblib.load(model_file)
# Predict with one sample
print(model.predict(numpy.array([1,1,24,1,0,211,2,31]).reshape(1,-1)))

It also runs with gcloud ai-platform local predict --model-dir gs://modeldir \ --json-instances input.json \ --framework scikit-learn
If it runs successfully locally, I don't understand why it fails in the prediction container.


text:
Q: how to write a query in sequelize to find all todos associated with user_id I am writing first todo list app using node express ejs and sequelize with sqlite
my sqlite.js file for database schemas is as follow
const Sequelize = require("sequelize");
const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: "./src/backend/databases/database.sqlite",
});

const users = sequelize.define("user", {
   username: {
    type: Sequelize.STRING,
  },
  email: {
    type: Sequelize.STRING,
    unique: true,
    allowNull: false,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const lists = sequelize.define("list", {
  item: {
    type: Sequelize.STRING,
  },
  edit: {
    type: Sequelize.BOOLEAN,
  },
  done: {
    type: Sequelize.STRING,
  },
  user_id: {
    type: Sequelize.NUMBER,
  },
});

sequelize
  .sync()
  .then(() => {
    console.log("tables have been successfully created");
    //  return sequelize.drop();
  })
  .catch((e) => console.log(e));

module.exports = {
  users: users,
  lists: lists,
};

I want to access and display all the todos related to user_id. i have used sequelize findall method as following
const dbConn = require("../databases/sqlite.js");
const list = dbConn.list;

 list.findAll({ where: { user_id: user_id } }).then((todoList) => {
    res
      .render("profile", { todoList: todoList })
      .catch((err) => console.error(err));
  });

but I am failed to display in the ejs file. it says todo list is undefined
ejs file

Added tasks

              <% for( let i = 0; i< todoList.length ; i++){ %>
                <% console.log(todoList[i])%>
              <% } %>

error shown is --
[ todoList is not defined ]
how do I change my approach to show all the todos associated with single user_id
thanks in advance

A: list.findAll({ where: { user_id: user_id } }).then((todoLists) => {
    res
      .render("profile", { todoLists });
  }).catch((err) => console.error(err));

can you please tell me where are you getting the user_id from ?


text:
Q: How to update a dataframe column in pyspark based on another column value without using withColumn feature? I have a dataframe in which I am trying to update a column value.
To do this, we can simply use spark.sql and run an update query on the dataframe.
But is there a way we can use dataframe's native API to do the same ?
I was able to set values of a new column by first creating it with withColumn and then setting its value based on a condition.
val df2 = df.withColumn("req_id", when(col("status") === "9088","Generated")
      .when(col("status") === "9089","Deactive")
      .otherwise("Unknown"))

But what if I already have a column req_id and it is with some values (not default values) where I want to update its value based on the column value status.
How can I update the value of the column req_id without doing a workaround like creating a new column and then updating its value ?
Any help is appreciated.

A: As @blackbishop mentioned in his comment :
val df2 = df.withColumn("req_id", when(col("status") === "9088","Generated")
      .when(col("status") === "9089","Deactive")
      .otherwise("Unknown"))

Will either create the column req_id or replace the values inside it if the column already exist.


text:
Q: Retrieving the JWT token from WSO2 IS using SSO OIDC authentication protocol I am implementing a basic NodeJS app that connects to WSO2 Identity Server for authentication.
I configured it using SSO with openid-connect. When I receive the callback, the jwt token is returned as a fragment identifier as I think it is returned as a GET request. How do I retrieve this JWT from the server side itself?
This is how the URL looks like when I try to login

https://localhost:9443/oauth2/authorize?response_type=id_token&client_id={CLIENT_ID}&scope=openid%20profile%20email&nonce=aaa&redirect_uri=http://localhost:3001/auth/callback

replaced the client_id with the actual client_id from what the Service Provider gave
this is a sample of how WSO2 returns the callback.

http://localhost:3001/auth/callback#id_token={TOKEN}

A: If you are using JAVA for your back-end development you can use a servlet filter to intercept this JWT token and process it. Following is a sample filter that you can use. You can use WSO2 Application Server to deploy your application.
public class JWTAction implements Filter {
private static final Logger logger = Logger.getLogger(JWTAction.class);
private static final PropertyReader propertyReader = new PropertyReader();

/**
 * This method is for get public key
 *
 * @return return for getting public key
 * @throws IOException              if unable to load the file
 * @throws KeyStoreException        if unable to get instance
 * @throws CertificateException     if unable to certify
 * @throws NoSuchAlgorithmException cause by other underlying exceptions(KeyStoreException)
 */

private static PublicKey getPublicKey() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

    InputStream file = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(propertyReader.getSsoKeyStoreName());
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    //loading key store with password
    keystore.load(file, propertyReader.getSsoKeyStorePassword().toCharArray());
    Certificate cert = keystore.getCertificate(propertyReader.getSsoCertAlias());
    return cert.getPublicKey();
}

public void init(FilterConfig filterConfig) {

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                     FilterChain filterChain) throws IOException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String jwt = request.getHeader("X-JWT-Assertion");
    String ssoRedirectUrl = propertyReader.getSsoRedirectUrl();

    if (jwt == null || "".equals(jwt)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to {}");
        }
        response.sendRedirect(ssoRedirectUrl);
        return;
    }

    String username = null;
    String roles = null;

    try {

        SignedJWT signedJWT = SignedJWT.parse(jwt);
        JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) getPublicKey());

        if (signedJWT.verify(verifier)) {
            if (logger.isDebugEnabled()) {
                logger.debug("JWT validation success for token: {}");
            }
            username = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/emailaddress").toString();
            roles = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/role").toString();
            if (logger.isDebugEnabled()) {
                logger.debug("User = {" + username + "} | Roles = " + roles);
            }
        } else {
            logger.error("JWT validation failed for token: {" + jwt + "}");
            response.sendRedirect(ssoRedirectUrl);
            return;
        }
    } catch (ParseException e) {
        logger.error("Parsing JWT token failed");
    } catch (JOSEException e) {
        logger.error("Verification of jwt failed");
    } catch (Exception e) {
        logger.error("Failed to validate the jwt {" + jwt + "}");
    }

    if (username != null && roles != null) {
        request.getSession().setAttribute("user", username);
        request.getSession().setAttribute("roles", roles);
    }

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ServletException e) {
        logger.error("Failed to pass the request, response objects through filters", e);
    }
}

public void destroy() {

}

}


text:
Q: Redirect_to rails 4 - could not find by lecture id My models
  class Course
       has_many :lessons, through: :chapters
end

class Lesson
  belongs_to :chapter
  has_one :course, through: :chapter
end

class User
  has_many :user_lessons
end

class UserLesson
   #fields: user_id, lesson_id, completed(boolean)
   belongs_to :user
   belongs_to :lesson
end

class Chapter
   has_many :lessons
   belongs_to :course
end

My UserLesson Controller:
 class UserLessonsController < ApplicationController
   before_filter :set_user_and_lesson
   def create
     @user_lesson = UserLession.create(user_id: @user.id, lession_id:    @lesson.id, completed: true)
if @user_lesson.save
  # redirect_to Course show action///// How can I redirect to that?
else
  # take the appropriate action
end
  end
 end

Basically what I want to to is to redirect_to the show action of the Course that has the lesson? (it is basically a go back to the whole list of lessons. Lessons are nested within Course) The problem is that could not find lecture id.
No route matches {:action=>"show", :controller=>"lectures", :id=>nil}    missing required keys: [:id]

Routes.rb
  resources :courses do

      resources :lessons

  end

   resources :user_lessons

Links that send the data to create method
   <%= link_to 'Back to Lesson list', user_lessons_path(@user_lesson, user_lesson: {user_id: 'current_user.id', lesson_id: 'lesson.id'}), :method => :post, data: {confirm: 'are you sure?'} %>

A: Pass the id in your redirect_to method:
redirect_to :controller=>'courses', :action => 'show', :id => @user_lesson.lesson.course.id

Update after your question edit:
Change this:
   <%= link_to 'Back to Lesson list', user_lessons_path(@user_lesson, user_lesson: {user_id: 'current_user.id', lesson_id: 'lesson.id'}), :method => :post, data: {confirm: 'are you sure?'} %>

to:
   <%= link_to 'Back to Lesson list', user_lessons_path(@user_lesson, user_lesson: {user_id: current_user.id, lesson_id: lesson.id}), :method => :post, data: {confirm: 'are you sure?'} %>

which is basically changing this:
user_lesson: {user_id: 'current_user.id', lesson_id: 'lesson.id'}

to:
user_lesson: {user_id: current_user.id, lesson_id: lesson.id}

see if that works.

A: redirect_to lessons_path(@user_lesson)

But you should define show action in your UserLessons controller.

A: Here's what I would do:
modify lesson class
class Lesson
  belongs_to :chapter
  has_one :course, through: :chapter #changed from :lecture since it's nowhere in your model structure
end

then you can use
redirect_to @lesson.course

to redirect to a lesson's course
Hope I got this right :)
Edit: I see that you mentioned lecture in multiple occasions but it's nowhere to be found in what you provided.... so I'm assuming it's now Course ? :)
If that's the case... change this as well
class Chapter
  has_many :lessons
  belongs_to :course # was lecture
end


text:
Q: Decomposition of complete graph $K_{n}$ into cycles when $n$=9 Clearly, in a complete graph $K_n$, number of edges $=\dfrac{n(n-1)}{2}$
so number of such cycle produced during decomposition= $\dfrac{n(n-1)}{2n}=\dfrac{n-1}{2}$
 clearly for $n=9$,
number of  decomposable  graph $=4$.
then why in graph theory by West has written that this construction fails for $n=9$
i am writing the solution from begining as
For $n = 5$ and $n = 7$, it suffices to use cycles formed by traversing the
vertices with constant difference:
$(0,1,2,3,4)$ and $(0,2,4,1,3)$ for $n = 5$
$ (0, 1, 2, 3, 4, 5, 6)$, $(0, 2, 4, 6, 1, 3, 5)$, and $(0, 3, 6, 2, 5, 1, 4)$ for $n = 7$.
This construction fails for $n = 9$ since the edges with difference $3$ form
three $3$-cycles. The cyclically symmetric construction below treats the ver-
tex set as $\mathbb{Z}$8 together with one special vertex.
Please help...

A: Suppose that you start at vertex $0$ and always go from vertex $k$ to vertex $(k+d)\bmod 9$ for some fixed distance $d$. When $d=1$ your path is
$$0\to 1\to 2\to 3\to 4\to 5\to 6\to 7\to 8\to 0\;,$$
represented by the cycle $(0,1,2,3,4,5,6,7,8)$. When $d=2$ it's
$$0\to 2\to 4\to 6\to 8\to 1\to 3\to 5\to 7\to 0\;,$$
represented by the cycle $(0,2,4,6,8,1,3,5,7)$. (Note that $8+2=10$, and $10\bmod 9=1$.) So far we have two of the desired four $9$-cycles. When we try $d=3$, however, we don't get a $9$-cycle: we get the path
$$0\to 3\to 6\to 0\;,$$
corresponding to the $3$-cycle $(0,3,6)$. The problem is that $9$, the desired cycle length, is a multiple of $d$ in this case. Whenever that happens, taking 'steps' of length $d$ will close the cycle too early. (In fact the cycle will close too early whenever $\gcd(n,d)>1$.)
We can go ahead and try $d=4$, and it works fine, because $\gcd(9,4)=1$; we get the path
$$0\to 4\to 8\to \to 3\to 7\to 2\to 6\to 1\to 5\to 0\;,$$
corresponding to the cycle $(0,4,8,3,7,2,6,1,5)$, and we now have three of the four desired $9$-cycles. What happens if we keep trying larger values of $d$?
When $d=5$ we get the path
$$0\to 5\to 1\to 6\to 2\to 7\to 3\to 8\to 4\to 0\;.$$
It's the right length, but it's not a new cycle: it's simply the $d=4$ cycle in reverse, so it uses exactly the same edges of $K_9$. This is because $5\equiv-4\pmod 9$, so a step size of $5$ is the same as a step size of $-4$, which of course simply runs through the $d=4$ path in reverse. Similarly, $d=6$ produces the path
$$0\to 6\to 3\to 0\;,$$
the reversal of the $d=3$ path, since $6\equiv-3\pmod9$. I'll leave it to you to check that $d=7$ produces the reversal of the $d=2$ path, and $d=8$ the reversal of the $d=1$ path. Of course $d=0$ goes nowhere. Values of $d$ that are congruent modulo $9$ produce exactly the same path, and every integer is congruent modulo $9$ to one of the integers $0,1,2,3,4,5,6,7$, and $8$, so we have found all of the paths that can be produced by taking 'steps' of a constant size $d$. There are five of them; three are $9$-cycles, one is a $3$-cycle, and one is a $1$-cycle. This approach therefore cannot produce a decomposition of $K_9$ into four $9$-cycles.


text:
Q: Add two columns together using apache-nifi I have following scenario. I one database table I have :
| id | name | basic_salary | allowance |
_______________________________________|
| 1  | sach | 2000         | 1000      |
| 2  | nala | 5000         | 2500      |
|______________________________________|

add basic_salary and allowance togther and making it as net_salary and insert to a new table called net_salary
For first step, I used ExecuteSQLRecord processor and can get all the records. But problem is : How to add those two columns coming in flowfile.
So final result should be :
| id | name | net_salary |
|________________________|
| 1  | sach | 3000       |
| 2  | nala | 7500       |

This is directly related to my previous variable question.
How to handle flowfile variables to perform operations in apache-nifi?
I used How to compute the sum of multiple columns in PostgreSQL inside ExecuteSQL processor, but it can not understand flowfile variables.

A: There is a tricky one. Use UpdateRecord twice.
The first one is
Record Reader               CSVReader
Record Writer               CSVRecordSetWriter
Replacement Value Strategy  Record Path Value
/net_salary                 concat(/basic_salary, ',', /allowance)

and the second one is
Record Reader               CSVReader
Record Writer               CSVRecordSetWriter
Replacement Value Strategy  Literal Value
/net_salary                 ${field.value:substringBefore(','):toNumber():plus(${field.value:substringAfter(','):toNumber()})}

where it gives the result as follows.
id,name,basic_salary,allowance,net_salary
1,sach,2000,1000,3000
2,nala,5000,2500,7500


text:
Q: Find a number in a sequence using divide and conquer I have a sequence A = [x1, x2,...,xn] in which x1 = 0 and xk > xk-1 for each k=2,3,...n.
For example we can have [0, 2, 3, 5, 7]. In such sequence it turns out that:

*

*If xc < c then xi < i for each 1 <= i <= c and,

*If xc > c then xi > i for each c <= i <= n
I want to find a number m which belongs to sequence such that xm = m.
Is it possible to implement such an algorithm using divide and conquer technique?

A: This is the thing what Binary Search does. But just in divide and conquer technique.
Here are C++ code looks like -
int findNumber(int st, int ed, int tar, const vector<int> x) {
    if (st == ed) {
        if (x[st] == tar) return st;
        else {
            return -1;
        }
    }
    int mid = (st + ed) / 2;
    if (x[mid] < mid) {
        return findNumber(mid+1, ed, tar, x);
    } else {
        return findNumber(st, mid-1, star, x);
    }
}

Call this method as findNumber(0, x.size() - 1, tar, x)


text:
Q: Can I use other plugins in my plugin in webpack 4? I have a working webpack configuration.
Now I want to make a single plugin.
I tried this suggestion but no success.
Using a loader inside a webpack plugin

A: This was the solution for me
module.exports = class MyPlugin {
    constructor(options = {}) {
        this.options = options;
    }
    apply(compiler) {
        new OtherPlugin({}).apply(compiler);
    }
}


text:
Q: Survival analysis in time series I have a dataset of patients who're prescribed a medication over the period of 3 years. The drug was supplied to each patient in different time intervals. I want to do a survival analysis to monitor recurrent events (i.e., events occurring multiple times).
The problem with the data is that, for some patients, the events do not occur in those time intervals where the drug is prescribed (e.g., an event may occur before/after the drug supply period). If I don't adjust this problem, using conventional survival analysis methods like Cox proportional hazard model may under/over-estimate the risk of events happening (because an event can happen when the drug supply is 0). So, how can I resolve this issue?

A: This might be handled by standard recurrent-event analysis allowing for time-dependent covariates (in this case, in particular whether the drug was being provided during each time interval). The general principles and illustrations for analysis in SAS, Stata and R are nicely presented in a recent paper by Amorim and Cai.
In R, the simplest approach would be to format the data with columns for (patientID, startTime, stopTime, event, drugStatus, otherCovariateValues...) with a separate row starting with each change of drug (or of other time-dependent covariates) or ending with each event. See this vignette for ways to format data this way. Including an ID for each patient allows correction for the correlations of results within individuals, e.g. by including a term of cluster(patientID) as a predictor in the model. This approach would be appropriate if the occurrence of an event is simply a function of the covariates and drug status at the time of the event, and if subsequent recurrent events were independent of prior events (given the present values of drug/covariates).
There isn't a problem here with events happening absent the drug. Presumably your interest is in whether the drug affects the probability/timing of an event occurring, and this analysis would address this issue directly provided that the above assumptions hold.
It is possible to model more complicated situations in which prior events themselves influence the probability of subsequent events, cumulative exposure to drug rather than instantaneous exposure is related to events, and so on. The references linked above are useful starting points for exploring these possibilities.

A: Frailty is another way that let you process your recurrent data.In survival package in R,  simply use frailty(patient ID) when you use your model.
    Fit <- coxph(surv(start,stop,event)~ predictor1+ predictor2+.....+ frailty( patient ID), data)


text:
Q: iis 6: Asp extension and html extension Suppose to have some asp code into a file Main.asp and suppose you want to include this file into other files with .htm extension.
I tried to create a new file mapping for *.htm (for asp.dll) in IIS 6.2 on windows 8.1, but this does not work.
I also try to include .asp file in a file with .htm extension (SSI allowed for .htm extension). The file is included but cannot <%> code  does not execute anymore.
I tried to create a masterpage and then to use

So, to have mixed asp code and simple html text in a page with .htm extension seems impossible.
Any suggestion?


text:
Q: Place 3d object on real object in Augmented Reality I am new to Augmented Reality, and I am creating a application where I will scan products and then I need to place 3d object on it to explain features.
Let say I am scanning a remote control, after scanning I have to show what on/off button do by pointing at it,
What volume button do by pointing at it, what channel button do by pointing at it etc
I searched a lot on internet couldn't find anything

A: First you have to generate a cad 3d model object which simulate your real model then from MTG application provided by vuforia create your model specific dataset after generating try to import it in unity and add to model target in your app. Now you can map your 3d model to real world object.


text:
Q: How to mock NSURLConnection.sendAsynchronousRequest in unit testing I have a function in which i am calling a network call as,
func newtorkCall() {
    //some other code
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:
        NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        if (data != nil) {
            //save the data in a variable temp
        }
    })
}

this is working fine and i am getting the data.
But i want to mock this NSURLConnection.sendAsynchronousRequest in unit testing so that i can hardcode the data and pass it to the variable temp in the source code and test it.
How can I do it?